PageSourceSearch

https://studiojungle.ai/assets/Index-CBgnOMCF.js

js studiojungle.ai collected 2026-10-05 14:20:09 UTC 2,595,523 bytes, 8,342 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/github-context-Dv4ueDwl.js","assets/index-TQG2ztjm.js","assets/vendor-monaco-K2VEKovO.js","assets/vendor-swagger-Bf7V8oR3.js","assets/vendor-swagger-0lcTflT8.css","assets/index-DNmKgs8f.css","assets/dropdown-menu-D17hKiE9.js","assets/check-DX1qY1zh.js","assets/badge-DKzwBJSz.js","assets/progress-B3zdPJWQ.js","assets/loader-circle-9UcafR3w.js","assets/database-CM2ulyuy.js","assets/chevron-down-CRT4HvDB.js","assets/circle-check-BViyeKMM.js","assets/circle-alert-XNNmTwWJ.js","assets/sparkles-DXp1XtxN.js","assets/input-CKlOBTjl.js","assets/EmailVerificationNotice-CYRasWqJ.js","assets/button-DtOMgFYX.js","assets/mail-WVDAbKYu.js","assets/label-BtL3YS2C.js","assets/textarea-ClMqUDrR.js","assets/circle-help-BGdmKT9G.js","assets/card-7VZRgwza.js","assets/StudioJungleMark-By26SLFG.js","assets/wrench-CFsKwpJR.js","assets/globe-DjgAQT17.js","assets/wand-sparkles-BT4zbDqe.js","assets/shield-check-p65qGa2s.js","assets/reference-artifacts-DcjQeVRl.js","assets/lock-B-37gHjp.js","assets/crown-B3SdS7fn.js","assets/brain-CWfI49U7.js","assets/zap-p1HVi94e.js","assets/arrow-right-C0DAM7jw.js","assets/layers-CZGje1SD.js","assets/chart-column-BJHVGUoI.js","assets/credit-card-_BGqL_0-.js","assets/image-CQBJyKgX.js","assets/trending-up-z7rwuhUc.js","assets/key-round-Dbn6jnS3.js","assets/user-plus-DQvZdKbi.js","assets/eye-sO_vDJE5.js","assets/refresh-cw-643fMIYJ.js","assets/file-code-2-DXiJCiLI.js","assets/users-DeQ4wUwU.js","assets/log-out-DsnecIU7.js","assets/arrow-left-ItJqViyp.js","assets/vendor-sandbox-Bdf4sJER.js","assets/vendor-sandbox-9CEnUXvW.css","assets/cloud-cuacwNPK.js","assets/shield-_9vMyv1d.js","assets/leaf-DisNpsTH.js","assets/eye-off-DVPlUTOY.js","assets/external-link-1cYqniwe.js","assets/search-CR-knjpd.js","assets/file-text-C8EcMb4T.js","assets/workflow-B6whsTNu.js","assets/github-DMWbm4WK.js","assets/MonacoEditor-DOseMS1r.js","assets/home-suggestions-IJ561fbD.js"])))=>i.map(i=>d[i]);
2var IL=Object.defineProperty;var OL=(e,t,r)=>t in e?IL(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Qe=(e,t,r)=>OL(e,typeof t!="symbol"?t+"":t,r);import{c as ke,s as G,a as Us,b as W,j as a,d as sl,e as Tr,f as En,g as Fa,h as vn,i as Uo,k as Ii,l as L,D as uw,m as RL,n as dw,o as pw,p as ac,X as qn,q as DL,r as qg,A as hw,C as L_,t as $_,R as F_,u as nd,v as Mt,T as Ar,w as gs,L as Xf,x as pp,y as ML,_ as ju,z as fn,B as LL,E as $L,P as FL,N as BL}from"./index-TQG2ztjm.js";import{r as m,c as gm,g as zs,R as H,a as B_}from"./vendor-monaco-K2VEKovO.js";import{u as fw,C as ia,a as U_,R as mw,h as gw,b as xw,F as yw,c as io,d as z_,e as UL,I as zL,S as ni,H as xm,D as Kl,f as Yl,g as Jl,i as hu,j as ki,k as Qr}from"./dropdown-menu-D17hKiE9.js";import{B as Ge}from"./badge-DKzwBJSz.js";import{P as qL,a as Kr}from"./progress-B3zdPJWQ.js";import{L as ze}from"./loader-circle-9UcafR3w.js";import{D as Hn}from"./database-CM2ulyuy.js";import{C as Yr}from"./chevron-down-CRT4HvDB.js";import{C as mn}from"./circle-check-BViyeKMM.js";import{C as is}from"./circle-alert-XNNmTwWJ.js";import{S as Dn}from"./sparkles-DXp1XtxN.js";import{I as Cn}from"./input-CKlOBTjl.js";import{u as q_,P as Ai,S as Xl,E as HL}from"./EmailVerificationNotice-CYRasWqJ.js";import{B as Q,b as H_}from"./button-DtOMgFYX.js";import{L as $n}from"./label-BtL3YS2C.js";import{T as Cd,S as Li}from"./textarea-ClMqUDrR.js";import{r as bw,i as WL,t as ic,b as VL,K as ba,c as rd,P as Kt,u as Hg,d as GL,n as KL,e as W_,f as YL,g as JL,h as XL,j as jc,k as V_,l as ZL,m as G_,o as K_,p as QL,q as e$,s as vw,v as ww,w as t$,x as Y_,z as jw,A as n$,B as r$,C as oc,D as s$,E as rr,Y as a$,F as i$,G as o$,H as l$,I as c$,J as u$,L as d$,R as p$}from"./vendor-swagger-Bf7V8oR3.js";import{C as Nw,a as h$}from"./circle-help-BGdmKT9G.js";import{C as Wn}from"./check-DX1qY1zh.js";import{C as f$,a as m$,b as g$,c as x$,S as J_}from"./card-7VZRgwza.js";import{S as ri,L as y$}from"./StudioJungleMark-By26SLFG.js";import{U as X_,H as _p,R as Es,W as al}from"./wrench-CFsKwpJR.js";import{G as Br}from"./globe-DjgAQT17.js";import{M as Tp,W as b$,C as sd}from"./wand-sparkles-BT4zbDqe.js";import{S as el}from"./shield-check-p65qGa2s.js";import{u as kw,I as v$,P as ym,n as af,c as Z_,S as Zd,a as Pd,M as Q_,b as eT,p as w$,m as j$,d as N$,e as Nc,J as k$,T as S$}from"./reference-artifacts-DcjQeVRl.js";import{K as Ep}from"./key-round-Dbn6jnS3.js";import{L as Bs}from"./lock-B-37gHjp.js";import{U as tT}from"./user-plus-DQvZdKbi.js";import{M as nT}from"./mail-WVDAbKYu.js";import{E as ys}from"./eye-sO_vDJE5.js";import{R as zr}from"./refresh-cw-643fMIYJ.js";import{F as Nu}from"./file-code-2-DXiJCiLI.js";import{L as tl}from"./layers-CZGje1SD.js";import{C as si}from"./chart-column-BJHVGUoI.js";import{U as Zl}from"./users-DeQ4wUwU.js";import{L as zb}from"./log-out-DsnecIU7.js";import{A as ei}from"./arrow-left-ItJqViyp.js";import{W as C$,D as P$,o as A$}from"./vendor-sandbox-Bdf4sJER.js";import{C as ya}from"./cloud-cuacwNPK.js";import{S as os}from"./shield-_9vMyv1d.js";import{Z as hr}from"./zap-p1HVi94e.js";import{L as fu}from"./leaf-DisNpsTH.js";import{I as ad}from"./image-CQBJyKgX.js";import{E as ku}from"./eye-off-DVPlUTOY.js";import{E as Is}from"./external-link-1cYqniwe.js";import{C as rT}from"./crown-B3SdS7fn.js";import{S as ja}from"./search-CR-knjpd.js";import{a as sT,B as Ip}from"./brain-CWfI49U7.js";import{F as kh}from"./file-text-C8EcMb4T.js";import{B as _$,G as oo,S as sa,K as Ql,a as T$,A as lc,P as E$,W as I$}
2from"./workflow-B6whsTNu.js";import{T as Sw}from"./trending-up-z7rwuhUc.js";import{A as Sh}from"./arrow-right-C0DAM7jw.js";import{G as to}from"./github-DMWbm4WK.js";import{C as O$}from"./credit-card-_BGqL_0-.js";/**
3 * @license lucide-react v0.462.0 - ISC
4 *
5 * This source code is licensed under the ISC license.
6 * See the LICENSE file in the root directory of this source tree.
7 */const R$=ke("Apple",[["path",{d:"M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z",key:"3s7exb"}],["path",{d:"M10 2c1 .5 2 2 2 5",key:"fcco2y"}]]);/**
8 * @license lucide-react v0.462.0 - ISC
9 *
10 * This source code is licensed under the ISC license.
11 * See the LICENSE file in the root directory of this source tree.
12 */const aT=ke("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/**
13 * @license lucide-react v0.462.0 - ISC
14 *
15 * This source code is licensed under the ISC license.
16 * See the LICENSE file in the root directory of this source tree.
17 */const D$=ke("ArrowDownWideNarrow",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]]);/**
18 * @license lucide-react v0.462.0 - ISC
19 *
20 * This source code is licensed under the ISC license.
21 * See the LICENSE file in the root directory of this source tree.
22 */const qb=ke("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
23 * @license lucide-react v0.462.0 - ISC
24 *
25 * This source code is licensed under the ISC license.
26 * See the LICENSE file in the root directory of this source tree.
27 */const Ck=ke("ArrowUpNarrowWide",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h4",key:"q8tih4"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h10",key:"jvxblo"}]]);/**
28 * @license lucide-react v0.462.0 - ISC
29 *
30 * This source code is licensed under the ISC license.
31 * See the LICENSE file in the root directory of this source tree.
32 */const iT=ke("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
33 * @license lucide-react v0.462.0 - ISC
34 *
35 * This source code is licensed under the ISC license.
36 * See the LICENSE file in the root directory of this source tree.
37 */const M$=ke("Asterisk",[["path",{d:"M12 6v12",key:"1vza4d"}],["path",{d:"M17.196 9 6.804 15",key:"1ah31z"}],["path",{d:"m6.804 9 10.392 6",key:"1b6pxd"}]]);/**
38 * @license lucide-react v0.462.0 - ISC
39 *
40 * This source code is licensed under the ISC license.
41 * See the LICENSE file in the root directory of this source tree.
42 */const L$=ke("BellPlus",[["path",{d:"M19.3 14.8C20.1 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 1 0 1.9.2 2.8.7",key:"guizqy"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}],["path",{d:"M18 5v6",key:"g5ayrv"}]]);/**
43 * @license lucide-react v0.462.0 - ISC
44 *
45 * This source code is licensed under the ISC license.
46 * See the LICENSE file in the root directory of this source tree.
47 */const oT=ke("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
48 * @license lucide-react v0.462.0 - ISC
49 *
50 * This source code is licensed under the ISC license.
51 * See the LICENSE file in the root directory of this source tree.
52 */const Pk=ke("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/**
53 * @license lucide-react v0.462.0 - ISC
54 *
55 * This source code is licensed under the ISC license.
56 * See the LICENSE file in the root directory of this source tree.
57 */const Wg=ke("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/**
58 * @license lucide-react v0.462.0 - ISC
59 *
60 * This source code is licensed under the ISC license.
61 * See the LICENSE file in the root directory of this source tree.
62 */const $$=ke("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/**
63 * @license lucide-react v0.462.0 - ISC
64 *
65 * This source code is licensed under the ISC license.
66 * See the LICENSE file in the root directory of this source tree.
67 */const F$=ke("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/**
68 * @license lucide-react v0.462.0 - ISC
69 *
70 * This source code is licensed under the ISC license.
71 * See the LICENSE file in the root directory of this source tree.
72 */const B$=ke("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/**
73 * @license lucide-react v0.462.0 - ISC
74 *
75 * This source code is licensed under the ISC license.
76 * See the LICENSE file in the root directory of this source tree.
77 */const lT=ke("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/**
78 * @license lucide-react v0.462.0 - ISC
79 *
80 * This source code is licensed under the ISC license.
81 * See the LICENSE file in the root directory of this source tree.
82 */const U$=ke("ChartNoAxesColumn",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/**
83 * @license lucide-react v0.462.0 - ISC
84 *
85 * This source code is licensed under the ISC license.
86 * See the LICENSE file in the root directory of this source tree.
87 */const z$=ke("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",ke
87y:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/**
88 * @license lucide-react v0.462.0 - ISC
89 *
90 * This source code is licensed under the ISC license.
91 * See the LICENSE file in the root directory of this source tree.
92 */const q$=ke("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/**
93 * @license lucide-react v0.462.0 - ISC
94 *
95 * This source code is licensed under the ISC license.
96 * See the LICENSE file in the root directory of this source tree.
97 */const cT=ke("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]);/**
98 * @license lucide-react v0.462.0 - ISC
99 *
100 * This source code is licensed under the ISC license.
101 * See the LICENSE file in the root directory of this source tree.
102 */const aa=ke("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
103 * @license lucide-react v0.462.0 - ISC
104 *
105 * This source code is licensed under the ISC license.
106 * See the LICENSE file in the root directory of this source tree.
107 */const Lr=ke("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/**
108 * @license lucide-react v0.462.0 - ISC
109 *
110 * This source code is licensed under the ISC license.
111 * See the LICENSE file in the root directory of this source tree.
112 */const Ak=ke("CloudDownload",[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]]);/**
113 * @license lucide-react v0.462.0 - ISC
114 *
115 * This source code is licensed under the ISC license.
116 * See the LICENSE file in the root directory of this source tree.
117 */const H$=ke("CloudSun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]);/**
118 * @license lucide-react v0.462.0 - ISC
119 *
120 * This source code is licensed under the ISC license.
121 * See the LICENSE file in the root directory of this source tree.
122 */const W$=ke("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/**
123 * @license lucide-react v0.462.0 - ISC
124 *
125 * This source code is licensed under the ISC license.
126 * See the LICENSE file in the root directory of this source tree.
127 */const hp=ke("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
128 * @license lucide-react v0.462.0 - ISC
129 *
130 * This source code is licensed under the ISC license.
131 * See the LICENSE file in the root directory of this source tree.
132 */const uT=ke("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
133 * @license lucide-react v0.462.0 - ISC
134 *
135 * This source code is licensed under the ISC license.
136 * See the LICENSE file in the root directory of this source tree.
137 */const V$=ke("Compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
138 * @license lucide-react v0.462.0 - ISC
139 *
140 * This source code is licensed under the ISC license.
141 * See the LICENSE file in the root directory of this source tree.
142 */const _k=ke("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]]);/**
143 * @license lucide-react v0.462.0 - ISC
144 *
145 * This source code is licensed under the ISC license.
146 * See the LICENSE file in the root directory of this source tree.
147 */const Tk=ke("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}
147],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/**
148 * @license lucide-react v0.462.0 - ISC
149 *
150 * This source code is licensed under the ISC license.
151 * See the LICENSE file in the root directory of this source tree.
152 */const Hb=ke("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
153 * @license lucide-react v0.462.0 - ISC
154 *
155 * This source code is licensed under the ISC license.
156 * See the LICENSE file in the root directory of this source tree.
157 */const Cw=ke("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/**
158 * @license lucide-react v0.462.0 - ISC
159 *
160 * This source code is licensed under the ISC license.
161 * See the LICENSE file in the root directory of this source tree.
162 */const dT=ke("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/**
163 * @license lucide-react v0.462.0 - ISC
164 *
165 * This source code is licensed under the ISC license.
166 * See the LICENSE file in the root directory of this source tree.
167 */const pT=ke("FileMinus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}]]);/**
168 * @license lucide-react v0.462.0 - ISC
169 *
170 * This source code is licensed under the ISC license.
171 * See the LICENSE file in the root directory of this source tree.
172 */const Vg=ke("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/**
173 * @license lucide-react v0.462.0 - ISC
174 *
175 * This source code is licensed under the ISC license.
176 * See the LICENSE file in the root directory of this source tree.
177 */const hT=ke("FilePlus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);/**
178 * @license lucide-react v0.462.0 - ISC
179 *
180 * This source code is licensed under the ISC license.
181 * See the LICENSE file in the root directory of this source tree.
182 */const Pw=ke("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/**
183 * @license lucide-react v0.462.0 - ISC
184 *
185 * This source code is licensed under the ISC license.
186 * See the LICENSE file in the root directory of this source tree.
187 */const Wb=ke("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
188 * @license lucide-react v0.462.0 - ISC
189 *
190 * This source code is licensed under the ISC license.
191 * See the LICENSE file in the root directory of this source tree.
192 */const G$=ke("FolderCode",[["path",{d:"M10 10.5 8 13l2 2.5",key:"m4t9c1"}],["path",{d:"m14 10.5 2 2.5-2 2.5",key:"14w2eb"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z",key:"1u1bxd"}]]);/**
193 * @license lucide-react v0.462.0 - ISC
194 *
195 * This source code is licensed under the ISC license.
196 * See the LICENSE file in the root directory of this source tree.
197 */const cc=ke("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
198 * @license lucide-react v0.462.0 - ISC
199 *
200 * This source code is licensed under the ISC license.
201 * See the LICENSE file in the root directory of this source tree.
202 */const K$=ke("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);/**
203 * @license lucide-react v0.462.0 - ISC
204 *
205 * This source code is licensed under the ISC license.
206 * See the LICENSE file in the root directory of this source tree.
207 */const Y$=ke("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}
207]]);/**
208 * @license lucide-react v0.462.0 - ISC
209 *
210 * This source code is licensed under the ISC license.
211 * See the LICENSE file in the root directory of this source tree.
212 */const Gg=ke("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/**
213 * @license lucide-react v0.462.0 - ISC
214 *
215 * This source code is licensed under the ISC license.
216 * See the LICENSE file in the root directory of this source tree.
217 */const J$=ke("GitMerge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]);/**
218 * @license lucide-react v0.462.0 - ISC
219 *
220 * This source code is licensed under the ISC license.
221 * See the LICENSE file in the root directory of this source tree.
222 */const fT=ke("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/**
223 * @license lucide-react v0.462.0 - ISC
224 *
225 * This source code is licensed under the ISC license.
226 * See the LICENSE file in the root directory of this source tree.
227 */const Op=ke("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/**
228 * @license lucide-react v0.462.0 - ISC
229 *
230 * This source code is licensed under the ISC license.
231 * See the LICENSE file in the root directory of this source tree.
232 */const X$=ke("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
233 * @license lucide-react v0.462.0 - ISC
234 *
235 * This source code is licensed under the ISC license.
236 * See the LICENSE file in the root directory of this source tree.
237 */const Z$=ke("Heading",[["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M6 20V4",key:"1w1bmo"}],["path",{d:"M18 20V4",key:"o2hl4u"}]]);/**
238 * @license lucide-react v0.462.0 - ISC
239 *
240 * This source code is licensed under the ISC license.
241 * See the LICENSE file in the root directory of this source tree.
242 */const Q$=ke("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/**
243 * @license lucide-react v0.462.0 - ISC
244 *
245 * This source code is licensed under the ISC license.
246 * See the LICENSE file in the root directory of this source tree.
247 */const e6=ke("Italic",[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]]);/**
248 * @license lucide-react v0.462.0 - ISC
249 *
250 * This source code is licensed under the ISC license.
251 * See the LICENSE file in the root directory of this source tree.
252 */const mT=ke("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/**
253 * @license lucide-react v0.462.0 - ISC
254 *
255 * This source code is licensed under the ISC license.
256 * See the LICENSE file in the root directory of this source tree.
257 */const t6=ke("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/**
258 * @license lucide-react v0.462.0 - ISC
259 *
260 * This source code is licensed under the ISC license.
261 * See the LICENSE file in the root directory of this source tree.
262 */const Yo=ke("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
263 * @license lucide-react v0.462.0 - ISC
264 *
265 * This source code is licensed under the ISC license.
266 * See the LICENSE file in the root directory of this source tree.
267 */const Ek=ke("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/**
268 * @license lucide-react v0.462.0 - ISC
269 *
270 * This source code is licensed under the ISC license.
271 * See the LICENSE file in the root directory of this source tree.
272 */const Ik=ke("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/**
273 * @license lucide-react v0.462.0 - ISC
274 *
275 * This source code is licensed under the ISC license.
276 * See the LICENSE file in the root directory of this source tree.
277 */const gT=ke("ListTree",[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]]);/**
278 * @license lucide-react v0.462.0 - ISC
279 *
280 * This source code is licensed under the ISC license.
281 * See the LICENSE file in the root directory of this source tree.
282 */const n6=ke("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/**
283 * @license lucide-react v0.462.0 - ISC
284 *
285 * This source code is licensed under the ISC license.
286 * See the LICENSE file in the root directory of this source tree.
287 */const xT=ke("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/**
288 * @license lucide-react v0.462.0 - ISC
289 *
290 * This source code is licensed under the ISC license.
291 * See the LICENSE file in the root directory of this source tree.
292 */const r6=ke("MessageSquareText",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/**
293 * @license lucide-react v0.462.0 - ISC
294 *
295 * This source code is licensed under the ISC license.
296 * See the LICENSE file in the root directory of this source tree.
297 */const s6=ke("MicVocal",[["path",{d:"m11 7.601-5.994 8.19a1 1 0 0 0 .1 1.298l.817.818a1 1 0 0 0 1.314.087L15.09 12",key:"80a601"}],["path",{d:"M16.5 21.174C15.5 20.5 14.372 20 13 20c-2.058 0-3.928 2.356-6 2-2.072-.356-2.775-3.369-1.5-4.5",key:"j0ngtp"}],["circle",{cx:"16",cy:"7",r:"5",key:"d08jfb"}]]);/**
298 * @license lucide-react v0.462.0 - ISC
299 *
300 * This source code is licensed under the ISC license.
301 * See the LICENSE file in the root directory of this source tree.
302 */const Aw=ke("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/**
303 * @license lucide-react v0.462.0 - ISC
304 *
305 * This source code is licensed under the ISC license.
306 * See the LICENSE file in the root directory of this source tree.
307 */const a6=ke("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
308 * @license lucide-react v0.462.0 - ISC
309 *
310 * This source code is licensed under the ISC license.
311 * See the LICENSE file in the root directory of this source tree.
312 */const i6=ke("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.
312074z",key:"s0h3yz"}]]);/**
313 * @license lucide-react v0.462.0 - ISC
314 *
315 * This source code is licensed under the ISC license.
316 * See the LICENSE file in the root directory of this source tree.
317 */const o6=ke("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/**
318 * @license lucide-react v0.462.0 - ISC
319 *
320 * This source code is licensed under the ISC license.
321 * See the LICENSE file in the root directory of this source tree.
322 */const l6=ke("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/**
323 * @license lucide-react v0.462.0 - ISC
324 *
325 * This source code is licensed under the ISC license.
326 * See the LICENSE file in the root directory of this source tree.
327 */const c6=ke("PackageSearch",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["circle",{cx:"18.5",cy:"15.5",r:"2.5",key:"b5zd12"}],["path",{d:"M20.27 17.27 22 19",key:"1l4muz"}]]);/**
328 * @license lucide-react v0.462.0 - ISC
329 *
330 * This source code is licensed under the ISC license.
331 * See the LICENSE file in the root directory of this source tree.
332 */const yT=ke("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
333 * @license lucide-react v0.462.0 - ISC
334 *
335 * This source code is licensed under the ISC license.
336 * See the LICENSE file in the root directory of this source tree.
337 */const bT=ke("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/**
338 * @license lucide-react v0.462.0 - ISC
339 *
340 * This source code is licensed under the ISC license.
341 * See the LICENSE file in the root directory of this source tree.
342 */const no=ke("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/**
343 * @license lucide-react v0.462.0 - ISC
344 *
345 * This source code is licensed under the ISC license.
346 * See the LICENSE file in the root directory of this source tree.
347 */const u6=ke("PartyPopper",[["path",{d:"M5.8 11.3 2 22l10.7-3.79",key:"gwxi1d"}],["path",{d:"M4 3h.01",key:"1vcuye"}],["path",{d:"M22 8h.01",key:"1mrtc2"}],["path",{d:"M15 2h.01",key:"1cjtqr"}],["path",{d:"M22 20h.01",key:"1mrys2"}],["path",{d:"m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10",key:"hbicv8"}],["path",{d:"m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17",key:"1i94pl"}],["path",{d:"m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7",key:"1cofks"}],["path",{d:"M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z",key:"4kbmks"}]]);/**
348 * @license lucide-react v0.462.0 - ISC
349 *
350 * This source code is licensed under the ISC license.
351 * See the LICENSE file in the root directory of this source tree.
352 */const vT=ke("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
353 * @license lucide-react v0.462.0 - ISC
354 *
355 * This source code is licensed under the ISC license.
356 * See the LICENSE file in the root directory of this source tree.
357 */const d6=ke("PencilLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]]);/**
358 * @license lucide-react v0.462.0 - ISC
359 *
360 * This source code is licensed under the ISC license.
361 * See the LICENSE file in the root directory of this source tree.
362 */const uc=ke("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/**
363 * @license lucide-react v0.462.0 - ISC
364 *
365 * This source code is licensed under the ISC license.
366 * See the LICENSE file in the root directory of this source tree.
367 */const p6=ke("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
368 * @license lucide-react v0.462.0 - ISC
369 *
370 * This source code is licensed under the ISC license.
371 * See the LICENSE file in the root directory of this source tree.
372 */const Oi=ke("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
373 * @license lucide-react v0.462.0 - ISC
374 *
375 * This source code is licensed under the ISC license.
376 * See the LICENSE file in the root directory of this source tree.
377 */const Ma=ke("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}
377],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/**
378 * @license lucide-react v0.462.0 - ISC
379 *
380 * This source code is licensed under the ISC license.
381 * See the LICENSE file in the root directory of this source tree.
382 */const h6=ke("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/**
383 * @license lucide-react v0.462.0 - ISC
384 *
385 * This source code is licensed under the ISC license.
386 * See the LICENSE file in the root directory of this source tree.
387 */const Ok=ke("Puzzle",[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]]);/**
388 * @license lucide-react v0.462.0 - ISC
389 *
390 * This source code is licensed under the ISC license.
391 * See the LICENSE file in the root directory of this source tree.
392 */const f6=ke("RadioTower",[["path",{d:"M4.9 16.1C1 12.2 1 5.8 4.9 1.9",key:"s0qx1y"}],["path",{d:"M7.8 4.7a6.14 6.14 0 0 0-.8 7.5",key:"1idnkw"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}],["path",{d:"M16.2 4.8c2 2 2.26 5.11.8 7.47",key:"ojru2q"}],["path",{d:"M19.1 1.9a9.96 9.96 0 0 1 0 14.1",key:"rhi7fg"}],["path",{d:"M9.5 18h5",key:"mfy3pd"}],["path",{d:"m8 22 4-11 4 11",key:"25yftu"}]]);/**
393 * @license lucide-react v0.462.0 - ISC
394 *
395 * This source code is licensed under the ISC license.
396 * See the LICENSE file in the root directory of this source tree.
397 */const m6=ke("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/**
398 * @license lucide-react v0.462.0 - ISC
399 *
400 * This source code is licensed under the ISC license.
401 * See the LICENSE file in the root directory of this source tree.
402 */const g6=ke("Redo2",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/**
403 * @license lucide-react v0.462.0 - ISC
404 *
405 * This source code is licensed under the ISC license.
406 * See the LICENSE file in the root directory of this source tree.
407 */const x6=ke("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/**
408 * @license lucide-react v0.462.0 - ISC
409 *
410 * This source code is licensed under the ISC license.
411 * See the LICENSE file in the root directory of this source tree.
412 */const y6=ke("Rewind",[["polygon",{points:"11 19 2 12 11 5 11 19",key:"14yba5"}],["polygon",{points:"22 19 13 12 22 5 22 19",key:"1pi1cj"}]]);/**
413 * @license lucide-react v0.462.0 - ISC
414 *
415 * This source code is licensed under the ISC license.
416 * See the LICENSE file in the root directory of this source tree.
417 */const Ri=ke("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
418 * @license lucide-react v0.462.0 - ISC
419 *
420 * This source code is licensed under the ISC license.
421 * See the LICENSE file in the root directory of this source tree.
422 */const Kg=ke("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
423 * @license lucide-react v0.462.0 - ISC
424 *
425 * This source code is licensed under the ISC license.
426 * See the LICENSE file in the root directory of this source tree.
427 */const ai=ke("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/**
428 * @license lucide-react v0.462.0 - ISC
429 *
430 * This source code is licensed under the ISC license.
431 * See the LICENSE file in the root directory of this source tree.
432 */const b6=ke("ServerCog",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5",key:"tn8das"}],["path",{d:"M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5",key:"1g2pve"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m15.7 13.4-.9-.3",key:"1jwmzr"}],["path",{d:"m9.2 10.9-.9-.3",key:"qapnim"}],["path",{d:"m10.6 15.7.3-.9",key:"quwk0k"}],["path",{d:"m13.6 15.7-.4-1",key:"cb9xp7"}],["path",{d:"m10.8 9.3-.4-1",key:"1uaiz5"}],["path",{d:"m8.3 13.6 1-.4",key:"s6srou"}],["path",{d:"m14.7 10.8 1-.4",key:"4d31cq"}],["path",{d:"m13.4 8.3-.3.9",key:"1bm987"}]]);/**
433 * @license lucide-react v0.462.0 - ISC
434 *
435 * This source code is licensed under the ISC license.
436 * See the LICENSE file in the root directory of this source tree.
437 */const wT=ke("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
438 * @license lucide-react v0.462.0 - ISC
439 *
440 * This source code is licensed under the ISC license.
441 * See the LICENSE file in the root directory of this source tree.
442 */const v6=ke("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
442y:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
443 * @license lucide-react v0.462.0 - ISC
444 *
445 * This source code is licensed under the ISC license.
446 * See the LICENSE file in the root directory of this source tree.
447 */const w6=ke("SkipForward",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/**
448 * @license lucide-react v0.462.0 - ISC
449 *
450 * This source code is licensed under the ISC license.
451 * See the LICENSE file in the root directory of this source tree.
452 */const j6=ke("SquareTerminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]);/**
453 * @license lucide-react v0.462.0 - ISC
454 *
455 * This source code is licensed under the ISC license.
456 * See the LICENSE file in the root directory of this source tree.
457 */const N6=ke("StarOff",[["path",{d:"M8.34 8.34 2 9.27l5 4.87L5.82 21 12 17.77 18.18 21l-.59-3.43",ke
457y:"16m0ql"}],["path",{d:"M18.42 12.76 22 9.27l-6.91-1L12 2l-1.44 2.91",key:"1vt8nq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/**
458 * @license lucide-react v0.462.0 - ISC
459 *
460 * This source code is licensed under the ISC license.
461 * See the LICENSE file in the root directory of this source tree.
462 */const jT=ke("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/**
463 * @license lucide-react v0.462.0 - ISC
464 *
465 * This source code is licensed under the ISC license.
466 * See the LICENSE file in the root directory of this source tree.
467 */const k6=ke("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
468 * @license lucide-react v0.462.0 - ISC
469 *
470 * This source code is licensed under the ISC license.
471 * See the LICENSE file in the root directory of this source tree.
472 */const Di=ke("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/**
473 * @license lucide-react v0.462.0 - ISC
474 *
475 * This source code is licensed under the ISC license.
476 * See the LICENSE file in the root directory of this source tree.
477 */const S6=ke("TableProperties",[["path",{d:"M15 3v18",key:"14nvp0"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
478 * @license lucide-react v0.462.0 - ISC
479 *
480 * This source code is licensed under the ISC license.
481 * See the LICENSE file in the root directory of this source tree.
482 */const C6=ke("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/**
483 * @license lucide-react v0.462.0 - ISC
484 *
485 * This source code is licensed under the ISC license.
486 * See the LICENSE file in the root directory of this source tree.
487 */const Yg=ke("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
488 * @license lucide-react v0.462.0 - ISC
489 *
490 * This source code is licensed under the ISC license.
491 * See the LICENSE file in the root directory of this source tree.
492 */const P6=ke("TestTubeDiagonal",[["path",{d:"M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3",key:"1ub6xw"}],["path",{d:"m16 2 6 6",key:"1gw87d"}],["path",{d:"M12 16H4",key:"1cjfip"}]]);/**
493 * @license lucide-react v0.462.0 - ISC
494 *
495 * This source code is licensed under the ISC license.
496 * See the LICENSE file in the root directory of this source tree.
497 */const NT=ke("TestTube",[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]]);/**
498 * @license lucide-react v0.462.0 - ISC
499 *
500 * This source code is licensed under the ISC license.
501 * See the LICENSE file in the root directory of this source tree.
502 */const A6=ke("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
503 * @license lucide-react v0.462.0 - ISC
504 *
505 * This source code is licensed under the ISC license.
506 * See the LICENSE file in the root directory of this source tree.
507 */const oa=ke("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
508 * @license lucide-react v0.462.0 - ISC
509 *
510 * This source code is licensed under the ISC license.
511 * See the LICENSE file in the root directory of this source tree.
512 */const kT=ke("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
513 * @license lucide-react v0.462.0 - ISC
514 *
515 * This source code is licensed under the ISC license.
516 * See the LICENSE file in the root directory of this source tree.
517 */const _6=ke("Underline",[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",ke
517y:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]]);/**
518 * @license lucide-react v0.462.0 - ISC
519 *
520 * This source code is licensed under the ISC license.
521 * See the LICENSE file in the root directory of this source tree.
522 */const T6=ke("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/**
523 * @license lucide-react v0.462.0 - ISC
524 *
525 * This source code is licensed under the ISC license.
526 * See the LICENSE file in the root directory of this source tree.
527 */const _w=ke("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
528 * @license lucide-react v0.462.0 - ISC
529 *
530 * This source code is licensed under the ISC license.
531 * See the LICENSE file in the root directory of this source tree.
532 */const E6=ke("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/**
533 * @license lucide-react v0.462.0 - ISC
534 *
535 * This source code is licensed under the ISC license.
536 * See the LICENSE file in the root directory of this source tree.
537 */const ST=ke("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);/**
538 * @license lucide-react v0.462.0 - ISC
539 *
540 * This source code is licensed under the ISC license.
541 * See the LICENSE file in the root directory of this source tree.
542 */const CT=ke("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/**
543 * @license lucide-react v0.462.0 - ISC
544 *
545 * This source code is licensed under the ISC license.
546 * See the LICENSE file in the root directory of this source tree.
547 */const PT=ke("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),AT=[{id:"build",name:"Build",model:"Claude",description:"Generating pages, components, edge functions, and database schema",status:"pending"},{id:"review",name:"Review & Repair",model:"GPT-5.5",description:"Second-pass review of routes, auth flows, and code quality — fixes issues before delivery",status:"pending"}];function Rk(){return{active:!1,phases:AT.map(e=>({...e})),currentPhaseIndex:-1,startedAt:null,completedAt:null,modelsUsed:[]}}function I6(e){return e!=null&&e.phase_event?e.phase_event:null}const O6=`{
548  "name": "studiojungle-app",
549  "private": true,
550  "version": "0.0.0",
551  "type": "module",
552  "scripts": {
553    "dev": "vite",
554    "build": "vite build",
555    "preview": "vite preview"
556  },
557  "dependencies": {
558    "react": "^18.3.1",
559    "react-dom": "^18.3.1",
560    "react-router-dom": "^6.27.0",
561    "@supabase/supabase-js": "^2.49.1",
562    "lucide-react": "^0.469.0",
563    "clsx": "^2.1.1",
564    "tailwind-merge": "^2.5.4",
565    "class-variance-authority": "^0.7.1"
566  },
567  "devDependencies": {
568    "@types/react": "^18.3.12",
569    "@types/react-dom": "^18.3.1",
570    "@vitejs/plugin-react": "^4.3.4",
571    "autoprefixer": "^10.4.20",
572    "postcss": "^8.4.49",
573    "tailwindcss": "^3.4.16",
574    "typescript": "^5.6.3",
575    "vite": "^5.4.11"
576  }
577}
578`,R6=`import { defineConfig } from 'vite';
579import react from '@vitejs/plugin-react';
580import { fileURLToPath } from 'node:url';
581
582export default defineConfig({
583  plugins: [react()],
584  resolve: {
585    alias: {
586      '@': fileURLToPath(new URL('./src', import.meta.url)),
587    },
588  },
589});
590`,D6=`import type { Config } from 'tailwindcss';
591
592export default {
593  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
594  theme: {
595    extend: {
596      fontFamily: {
597        sans: ['Inter', 'ui-sans-serif', 'system-ui', 'sans-serif'],
598        display: ['Fraunces', 'Georgia', 'serif'],
599      },
600    },
601  },
602  plugins: [],
603} satisfies Config;
604`,M6=`export default {
605  plugins: {
606    tailwindcss: {},
607    autoprefixer: {},
608  },
609};
610`,L6=`{
611  "compilerOptions": {
612    "target": "ES2020",
613    "useDefineForClassFields": true,
614    "lib": ["ES2020", "DOM", "DOM.Iterable"],
615    "module": "ESNext",
616    "skipLibCheck": true,
617    "moduleResolution": "bundler",
618    "allowImportingTsExtensions": true,
619    "resolveJsonModule": true,
620    "isolatedModules": true,
621    "noEmit": true,
622    "jsx": "react-jsx",
623    "strict": true,
624    "noUnusedLocals": false,
625    "noUnusedParameters": false,
626    "noFallthroughCasesInSwitch": true,
627    "baseUrl": ".",
628    "paths": { "@/*": ["./src/*"] }
629  },
630  "include": ["src"],
631  "references": [{ "path": "./tsconfig.node.json" }]
632}
633`,$6=`{
634  "compilerOptions": {
635    "composite": true,
636    "skipLibCheck": true,
637    "module": "ESNext",
638    "moduleResolution": "bundler",
639    "allowSyntheticDefaultImports": true
640  },
641  "include": ["vite.config.ts"]
642}
643`,F6=`<!doctype html>
644<html lang="en">
645  <head>
646    <meta charset="UTF-8" />
647    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
648    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
649    <title>Studio Jungle App</title>
650    <link rel="preconnect" href="https://fonts.googleapis.com" />
651    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
652    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Fraunces:opsz,[email protected],400;9..144,600;9..144,700&display=swap" rel="stylesheet" />
653    <style>
654      /* Inline loader shown until React mounts. Visible during Vite's
655         boot + dep install + initial bundle, so customers see a
656         polished animation instead of a blank white frame or (worst
657         case) the E2B "Closed Port Error" page. Removed by main.tsx
658         once createRoot().render() is called. */
659      .sj-boot-loader { position:fixed; inset:0; display:flex; align-items:center; justify-content:center; flex-direction:column; gap:24px; background:radial-gradient(circle at 30% 20%, #f0f9ff 0%, #fafafa 60%); font-family:Inter, ui-sans-serif, system-ui, sans-serif; z-index:9999; transition:opacity .4s ease; }
660      .sj-boot-loader.is-hidden { opacity:0; pointer-events:none; }
661      .sj-boot-loader .sj-loader-ring { width:48px; height:48px; border-radius:50%; border:3px solid rgba(15,23,42,0.08); border-top-color:#3b82f6; animation:sj-spin 0.9s linear infinite; }
662      .sj-boot-loader .sj-loader-label { color:#0f172a; font-size:13px; font-weight:500; opacity:.72; letter-spacing:.2px; }
663      .sj-boot-loader .sj-loader-sub { color:#64748b; font-size:11px; opacity:.65; max-width:280px; text-align:center; line-height:1.5; }
664      @keyframes sj-spin { to { transform:rotate(360deg); } }
665    </style>
666  </head>
667  <body>
668    <div class="sj-boot-loader" id="sj-boot-loader">
669      <div class="sj-loader-ring" aria-hidden="true"></div>
670      <div class="sj-loader-label">Preparing your preview…</div>
671      <div class="sj-loader-sub">Building components and wiring routes. This takes a few seconds on first load.</div>
672    </div>
673    <div id="root"></div>
674    <script type="module" src="/src/main.tsx"><\/script>
675  </body>
676</html>
677`,B6=`import { StrictMode } from 'react';
678import { createRoot } from 'react-dom/client';
679import { BrowserRouter } from 'react-router-dom';
680import App from './App';
681import './index.css';
682
683createRoot(document.getElementById('root')!).render(
684  <StrictMode>
685    <BrowserRouter>
686      <App />
687    </BrowserRouter>
688  </StrictMode>,
689);
690
691// Fade out the boot loader (index.html) once React has rendered. requestAnimationFrame
692// ensures the first paint of the real app lands before we trigger the transition,
693// so customers see a smooth handoff instead of a white flash.
694requestAnimationFrame(() => {
695  const loader = document.getElementById('sj-boot-loader');
696  if (loader) {
697    loader.classList.add('is-hidden');
698    setTimeout(() => loader.remove(), 400);
699  }
700});
701`,U6=`// Replace this with your real routes/components. The scaffold is just
702// to make the project bootable on first render — overwrite freely.
703export default function App() {
704  return (
705    <main className="min-h-screen flex items-center justify-center">
706      <p className="text-sm text-slate-500">Building your app…</p>
707    </main>
708  );
709}
710`,z6=`@tailwind base;
711@tailwind components;
712@tailwind utilities;
713
714:root {
715  font-family: 'Inter', ui-sans-serif, system-ui, sans-serif;
716  color-scheme: light;
717}
718
719html, body, #root { height: 100%; }
720body { margin: 0; }
721`,q6=`import { clsx, type ClassValue } from 'clsx';
722import { twMerge } from 'tailwind-merge';
723
724export function cn(...inputs: ClassValue[]) {
725  return twMerge(clsx(inputs));
726}
727`,Tw=[{path:"package.json",content:O6,language:"json"},{path:"vite.config.ts",content:R6,language:"ts"},{path:"tailwind.config.ts",content:D6,language:"ts"},{path:"postcss.config.js",content:M6,language:"js"},{path:"tsconfig.json",content:L6,language:"json"},{path:"tsconfig.node.json",content:$6,language:"json"},{path:"index.html",content:F6,language:"html"},{path:"src/main.tsx",content:B6,language:"tsx"},{path:"src/App.tsx",content:U6,language:"tsx"},{path:"src/index.css",content:z6,language:"css"},{path:"src/lib/utils.ts",content:q6,language:"ts"}];new Set(Tw.map(e=>e.path));const H6=Object.fromEntries(Tw.map(e=>[e.path,e.content]));function fp(e,t){if(!e||typeof t!="string")return!1;const r=H6[e];return r?t===r:!1}const Vb=".sj/rules.md",Gb=".sj/blueprint.md",Kb=".sj/mistakes.md",Rp=".sj/plan.md",Dp=".sj/build-notes.md",W6=new Set(["package.json",".gitignore",".env",".env.local",".env.example","components.json","package-lock.json","bun.lock","bun.lockb","pnpm-lock.yaml","yarn.lock","tsconfig.tsbuildinfo"]),V6=[/(^|\/)tsconfig(?:\.[^.\/]+)?\.json$/i,/(^|\/)(?:vite|tailwind|postcss|eslint)\.config\.(?:[cm]?[jt]s)$/i];function _T(){return new Date().toISOString().slice(0,10)}function TT(e){return e===".sj"||e.startsWith(".sj/")||e===".studiojungle"||e.startsWith(".studiojungle/")}function Ul(e){var r;if(!e||TT(e))return!1;const t=((r=e.split("/").pop())==null?void 0:r.toLowerCase())||"";return!(!t||W6.has(t)||V6.some(n=>n.test(e))||/^readme(?:\.[a-z0-9]+)?$/i.test(t))}function Sy(e){const t=(r,n="")=>{for(const s of r){const i=n?`${n}/${s.name}`:s.name;if(s.type==="file"&&Ul(i)&&!fp(i,s.content)||s.type==="folder"&&s.children&&t(s.children,i))return!0}return!1};return t(e)}function G6(){return`# Project rules
728
729These rules become binding after the first substantive build. During the initial scaffold, treat them as the default contract for all later edits.
730
731## Scope
732- Modify only the files the user names, or the minimum extra wiring files required.
733- Do not regenerate the whole app for a small request.
734- Do not refactor, reorganize, rename, or restyle unrelated code.
735
736## File targeting
737- Decide the minimum file set before editing.
738- Read existing files first instead of guessing their contents.
739- Use file inventory plus read/list tools to inspect only the relevant files.
740- If a needed file does not exist, create only that file plus the smallest required wiring.
741- Do not create a second Home/Landing page or duplicate a route when the project already has one.
742
743## Edit style
744- Prefer surgical edits over full-file rewrites for existing files.
745- Reuse existing components, hooks, helpers, and patterns instead of duplicating them.
746- Preserve working routes, auth, database wiring, and visual design unless the task asks to change them.
747
748## Quality bar
749- Ship work at a very high Lovable-style standard: intentional layout, clear hierarchy, polished spacing, and cohesive typography.
750- Avoid generic AI-looking UI, repeated filler sections, placeholder copy, or default blue/button styling unless the brand actually calls for it.
751- Every touched screen should feel complete: loading, empty, error, hover, focus, and mobile states should be considered when relevant.
752- Use realistic sample data, meaningful labels, and believable content instead of lorem ipsum or vague placeholders.
753- Do not leave broken links, dead buttons, orphan routes, or unfinished sections in the touched area.
754
755## Protected areas
756- Do not touch package.json, vite/tailwind/tsconfig, schema, auth, secrets, or cloud config unless the request clearly requires it.
757- Do not change shared design tokens, spacing systems, or typography unless the task is explicitly about styling.
758
759## Cost discipline
760- Inspect only the files relevant to the task.
761- Avoid blind whole-file rewrites when a small replacement will work.
762- Keep diffs small, targeted, and easy to review.
763
764## Escalation
765- Ask before risky or broad changes, especially auth, database, billing, storage, routing, or files over roughly 200 lines.
766- If the request conflicts with these rules, pause and ask instead of guessing.
767
768## Project memory
769- Before every build/edit, read .sj/blueprint.md, .sj/rules.md, .sj/mistakes.md, .sj/plan.md, and .sj/build-notes.md.
770- Keep .sj/plan.md focused on the active task.
771- Keep .sj/build-notes.md updated with what changed, what passed, what failed, and what to test.
772- Keep .sj/blueprint.md updated with what was built, what is pending, and key architecture decisions.
773`}function K6(e,t){const r=(e==null?void 0:e.trim())||"Untitled Project",n=(t==null?void 0:t.trim())||"Initial project brief not captured yet.";return`# Project blueprint
774
775## Project brief
776${r}: ${n}
777
778## Built so far
779- Project initialized. No substantive app scaffold is recorded yet.
780
781## Pending
782- Initial scaffold or next requested feature build.
783
784## Architecture
785- Architecture not locked yet. Follow the current project files and user prompts.
786
787## Last session
788${_T()} — Project metadata initialized.
789`}function Y6(){return`# Known mistakes to avoid
790
791Studio Jungle reads this before every build/edit. Add recurring project-specific failures here so the AI does not repeat them.
792
793## Routing and pages
794- Do not create duplicate Home, Landing, Login, Signup, or Not Found pages when one already exists.
795- Do not claim a page exists or is wired without checking the file and router/App entry.
796- When adding a route, update the router/App file and any relevant nav/CTA links in the same change.
797
798## Build failures seen often
799- Do not put unescaped apostrophes inside single-quoted TypeScript strings; use double quotes or template literals.
800- Do not use Node-only imports such as \`path\` or \`__dirname\` in Vite browser config unless the project already supports it.
801- Do not create local imports without also emitting the imported files.
802- Do not use Tailwind dynamic class names that the compiler cannot see.
803
804## Product behavior
805- Do not say “done” unless code changed or you verified the requested behavior already exists.
806- Do not push database/schema/auth/cloud changes unless the user explicitly selected or requested them.
807- Do not rebuild from scratch for a small edit; inspect and patch the relevant surface only.
808`}function J6(){return`# Current plan
809
810No active plan yet.
811
812When a build starts, Studio Jungle writes:
813- user request
814- detected intent
815- files to inspect
816- files likely to change
817- validation to run
818`}function X6(){return`# Build notes
819
820## ${_T()}
821- Project memory initialized.
822- Future runs should append what changed, what passed, what failed, and what to test.
823`}function ET(e={}){return[{path:Vb,content:G6()},{path:Gb,content:K6(e.projectName,e.projectDescription)},{path:Kb,content:Y6()},{path:Rp,content:J6()},{path:Dp,content:X6()}]}function IT(e,t){if(t.length===0)return!1;const[r,...n]=t,s=e.find(i=>i.name===r);return s?n.length===0?s.type==="file":s.type!=="folder"||!s.children?!1:IT(s.children,n):!1}function Yb(e,t,r){const[n,...s]=t;if(!n)return e;const i=e.findIndex(o=>o.name===n);if(s.length===0)return i>=0?e:[...e,{name:n,type:"file",content:r}];if(i>=0){const o=e[i];if(o.type!=="folder")return e;const l=Yb(o.children||[],s,r),c=[...e];return c[i]={...o,children:l},c}return[...e,{name:n,type:"folder",children:Yb([],s,r)}]}function Z6(e,t={}){let r=e;const n=[];
823for(const s of ET(t)){const i=s.path.split("/").filter(Boolean);IT(r,i)||(r=Yb(r,i,s.content),n.push(s))}return{tree:r,created:n}}const Q6=new Set(["autodb","questions","secret_request","secret-request"]);function jl(e){const t=[],r=e.replace(/\r\n/g,`
824`).split(`
825`);let n=!1,s="",i=[];const o=()=>{const{language:l,filename:c}=eF(s),u=i.join(`
826`).trim();if(!u||Q6.has(l))return;const d=c||tF(l,u);if(d){if(/^untitled\./i.test(d)){console.warn(`[response-parser] dropping untitled.* fence (language="${l}", content starts: ${u.slice(0,60).replace(/\n/g," ")}...)`);return}t.push({filename:d,language:l,content:u})}};for(const l of r){const c=l.match(/^\s*```(.*)$/);if(!n){if(c){const u=(c[1]||"").trim();if(!u)continue;n=!0,s=u,i=[]}continue}if(c){const u=(c[1]||"").trim();u?(o(),n=!0,s=u,i=[]):(o(),n=!1,s="",i=[]);continue}i.push(l)}return n&&i.length>0&&o(),t}function eF(e){const t=e.trim().split(/\s+/).filter(Boolean),r=(t[0]||"text").toLowerCase(),n=t[1]||"",s=/^[\w./\-]+\.[a-zA-Z0-9]+$/.test(n)&&!n.includes("://")?n:"";return{language:r,filename:s}}function tF(e,t){if(e==="html"){const l=t.match(/<!--\s*route:\s*(\/[^\s]*)\s*-->/i),c=l==null?void 0:l[1];if(c)return c==="/"?"index.html":`${c.replace(/^\//,"")}.html`}if(e==="sql")return"schema.sql";if(e==="json"&&t.includes('"dependencies"'))return"package.json";if(e==="json"&&t.includes('"compilerOptions"'))return"tsconfig.json";if(t.includes("defineConfig")&&t.includes("vite"))return"vite.config.ts";if(t.includes("tailwindcss")&&t.includes("content:"))return"tailwind.config.ts";if(t.includes("ReactDOM.createRoot"))return"src/main.tsx";if(e==="css"&&t.includes("@tailwind"))return"src/index.css";const r=t.match(/\/\/\s*([\w./\-]+\.\w+)/);if(r)return r[1];const n=t.match(/(?:export\s+(?:default\s+)?)?(?:function|const|class)\s+(\w+)/),s=(n==null?void 0:n[1])||"untitled",o={tsx:".tsx",typescript:".ts",ts:".ts",jsx:".jsx",javascript:".js",js:".js",html:".html",css:".css",scss:".scss",python:".py",py:".py",sql:".sql",json:".json",yaml:".yaml",yml:".yaml",bash:".sh",shell:".sh"}[e]||`.${e}`;return`${s}${o}`}function nF(e){const t=[];let r=e.replace(/```[a-zA-Z]*\s*([\w./\-]+\.[a-zA-Z]+)?[ \t]*\n[\s\S]*?```/g,(n,s)=>(s&&t.push(s),""));return r=r.replace(/```[a-zA-Z]*\s*[\w./\-]*[ \t]*\n[\s\S]*$/g,""),r=r.replace(/^[-*•]\s*`?(?:src|public|pages|components|hooks|lib|utils|styles)\/[\w./\-]+\.\w+`?\s*$/gm,""),r=r.replace(/`(?:src|public|pages|components|hooks|lib|utils|styles)\/[\w./\-]+\.\w+`/g,""),r=r.replace(/(?:generated\s+)?(?:here\s+are\s+the\s+)?files?(?:\s+for\s+[\w\s]+)?:\s*\n(?:\s*[-*•\d.]\s*`?[\w./\-]+\.\w+`?\s*\n?)*/gi,""),r=r.replace(/^\d+\.\s*`?(?:src|public|pages|components|hooks|lib|utils|styles)\/[\w./\-]+\.\w+`?\s*$/gm,""),r=r.replace(/✅\s*Done!?\s*(?:\n[\s\S]*)?$/i,"✅ Done!"),r=r.replace(/^\s*(?:src|public|pages|components)\/[\w./\-]+\.\w+\s*$/gm,""),r=r.replace(/<(?:!DOCTYPE|html|head|body|meta|link|script|style|div|section|header|footer|nav|main|aside|article|span|p|h[1-6]|ul|ol|li|a|img|button|form|input|textarea|select|option|table|tr|td|th|thead|tbody|label|svg|path|circle|rect|line|polyline|polygon|g|defs|use|symbol|clipPath|mask|pattern|title|noscript)\b[^>]*>[\s\S]*?<\/\w+>|<(?:!DOCTYPE|meta|link|img|input|br|hr|source|embed|track|wbr|col|area)\b[^>]*\/?\s*>/gi,""),r=r.replace(/<\/?(?:div|section|header|footer|nav|main|aside|article|span|p|h[1-6]|ul|ol|li|a|img|button|form|input|textarea|select|option|table|tr|td|th|thead|tbody|label|html|head|body|meta|link|script|style|svg|path|circle|rect|noscript)\b[^>]*>/gi,""),r=r.replace(/(?:^|\n)\s*(?:[\w.#\-\[\]:,\s>+~]+\{[^}]*\}\s*)+/g,`
827`),{cleaned:r.replace(/\n{3,}/g,`
828
829`).trim(),files:t}}function Mo(e){const t=[];for(const r of e){const n=r.filename.split("/");OT(t,n,r.content)}return t}function OT(e,t,r){if(t.length===0)return;const[n,...s]=t;if(s.length===0){const i=e.find(o=>o.name===n&&o.type==="file");i?i.content=r:e.push({name:n,type:"file",content:r})}else{let i=e.find(o=>o.name===n&&o.type==="folder");i||(i={name:n,type:"folder",children:[]},e.push(i)),i.children||(i.children=[]),OT(i.children,s,r)}}const Ad=[{id:"phase-1",pattern:/📋\s*App Specification|PHASE 1|App Specification/i,title:"Ap
829p Specification",description:"Defining features, user roles, and core purpose"},{id:"phase-2",pattern:/🗺️\s*Route Map|PHASE 2|Route Map/i,title:"Route Map",description:"Mapping all pages, routes, and navigation"},{id:"phase-3",pattern:/🗄️\s*Database Schema|PHASE 3|Database Schema/i,title:"Database Schema",description:"Designing tables, columns, and relationships"},{id:"phase-4",pattern:/📡\s*API Contract|PHASE 4|API Contract/i,title:"API Contract",description:"Defining all endpoints and data flows"},{id:"phase-5",pattern:/🧩\s*Component Registry|PHASE 5|Component Registry/i,title:"Component Registry",description:"Registering UI components per page"},{id:"phase-6",pattern:/⚡\s*Action Map|PHASE 6|Action Map/i,title:"Action Map",description:"Mapping every button, form, and interaction"},{id:"phase-7",pattern:/PHASE 7|Code Generation/i,title:"Code Generation",description:"Generating code modules"},{id:"phase-8",pattern:/✅\s*Validation Report|PHASE 8|Validation Pass/i,title:"Validation Pass",description:"Checking routes, actions, APIs, and DB coverage"},{id:"phase-9",pattern:/🔧\s*Repair Summary|PHASE 9|Repair Pass/i,title:"Repair Pass",description:"Fixing detected issues"}];function rF(e,t,r){const n=[],s=r||"";let i=-1;for(let o=0;o<Ad.length;o++)Ad[o].pattern.test(s)&&(i=o);if(i>=0){for(let o=0;o<=Math.max(i,0);o++){const l=Ad[o],c=l.pattern.test(s),u=o===i;n.push({id:l.id,title:l.title,description:l.description,status:c?t&&u?"running":"done":t?"pending":"done"})}if(t&&i<Ad.length-1){const o=Ad[i+1];n.push({id:o.id,title:o.title,description:o.description,status:"pending"})}}else n.push({id:"analyze",title:"Analyzing Request",description:"Understanding requirements and planning implementation",status:e.length>0?"done":t?"running":"done",logs:["Parsed user requirements","Identified components needed"]});if(e.length>0){const o=e.filter(p=>p.language==="html").length,l=e.filter(p=>["tsx","jsx","typescript","ts"].includes(p.language)).length,c=e.filter(p=>p.language==="sql").length,u=e.length-o-l-c,d=[];l>0&&d.push(`${l} component${l>1?"s":""}`),o>0&&d.push(`${o} page${o>1?"s":""}`),c>0&&d.push(`${c} schema file${c>1?"s":""}`),u>0&&d.push(`${u} other file${u>1?"s":""}`),n.push({id:"gen-files",title:`Generated ${e.length} Files`,description:d.join(", "),status:t?"running":"done",logs:e.map(p=>p.filename)})}return e.length>0&&n.push({id:"preview",title:"Building Preview",description:"Rendering generated application",status:t?"pending":"done",logs:t?void 0:["Preview ready"]}),n}function sF(e){const t=e.match(/<!--\s*route:\s*(\/[^\s]*)\s*-->/i);return t?t[1]:null}function aF(e){const t=sF(e.content);if(t)return t;const r=(e.filename.split("/").pop()||"").toLowerCase();return r==="index.html"||r==="index.htm"?"/":null}function iF(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()}function oF(e){const t=e.filename.replace(/\\/g,"/"),r=t.split("/").filter(Boolean);if(r.length===0)return null;const s=r[r.length-1].replace(/\.[^.]+$/,""),i=r.findIndex(u=>/^(pages|routes|screens|views)$/i.test(u)),o=i>=0?r.slice(i+1,-1):[],l=s.replace(/(?:Page|Screen|View)$/i,"").replace(/^Index$/i,"").trim();if(/^(App|Home|Landing|Index)$/i.test(s)||/^(Home|Landing|Index)$/i.test(l))return"/";l&&o.push(l);const c=o.map(u=>u.replace(/^\((.+)\)$/i,"$1")).map(u=>iF(u)).filter(Boolean).filter(u=>u!=="index");return c.length===0?/(?:^|\/)(?:pages|routes|screens|views)\//i.test(t)?"/":null:`/${c.join("/")}`}function lF(e){return["/","/home","/homepage","/landing","/landing-page","/index","/index.html"].includes(ii(e))}function su(e){const t=ii(e);return lF(t)?"/":t}function cF(e){var t,r,n,s;return((t=e.match(/export\s+default\s+function\s+(\w+)/))==null?void 0:t[1])||((r=e.match(/function\s+(\w+)\s*\(/))==null?void 0:r[1])||((n=e.match(/(?:export\s+default\s+)?const\s+(\w+)\s*=/))==null?void 0:n[1])||((s=e.match(/class\s+(\w+)\s+extends/))==null?void 0:s[1])||null}function uF(e){const t=new Map,r=e.filter(n=>/(?:^|\/)App\.[tj]sx?$/i.test(n.filename));for(const n of r){const s=new Map,i=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g;let o;for(;(o=i.exec(n.content))!==null;){const[,u,d]=o;if(!/(?:^|\/)(?:pages|routes|screens|views)\//i.test(d)&&!d.startsWith("./pages/")&&!d.startsWith("@/pages/"))continue;const p=d.replace(/^@\//,"src/").replace(/^\.\//,"src/").replace(/\.(tsx|jsx|ts|js)$/i,"");s.set(u,p)}const l=/<Route\b[^>]*\bpath=\{?["'`]([^"'`{}]+)["'`]\}?[^>]*\belement=\{?\s*<(\w+)/g;let c;for(;(c=l.exec(n.content))!==null;){const[,u,d]=c,p=ii(u);if(!p||p.includes(":")||p==="*")continue;t.set(d,p);const h=s.get(d);h&&(t.set(h,p),t.set(`${h}.tsx`,p),t.set(`${h}.jsx`,p))}}return t}const Dk=new Set(["/list","/detail"]);function dF(e){return e==="/"?"Home":e.replace(/^\//,"").replace(/[-_/]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())||"Route"}function pF(e){var n;const t=[],r=e.match(/const\s+content[^=]*=\s*(\{[\s\S]*\})\s*(?:;\s*\nexport|\nexport)/);if(!r)return t;try{const s=JSON.parse(r[1]),i=new Set,o=(l,c)=>{const u=su(l.startsWith("/")?l:`/${l}`);i.has(u)||(i.add(u),t.push({id:u,name:c}
829))};for(const l of((n=s.navigation)==null?void 0:n.items)||[])typeof(l==null?void 0:l.path)=="string"&&typeof(l==null?void 0:l.label)=="string"&&o(l.path,l.label);for(const l of s.tabs||[])typeof(l==null?void 0:l.path)=="string"&&typeof(l==null?void 0:l.label)=="string"&&o(l.path,l.label);for(const[l,c]of Object.entries(s.routes||{})){const u=su(`/${l}`);i.has(u)||(i.add(u),t.push({id:u,name:(c==null?void 0:c.title)||dF(u)}))}}catch{return t}return t}function id(e){const t=[],r=uF(e),n=l=>{if(l.language!=="html")return!1;const c=l.content;return/<div\s+id=["']root["'][^>]*>\s*(?:<!--[\s\S]*?-->\s*)?<\/div>/i.test(c)?/<script\s+type=["']module["'][^>]*\bsrc=["']\/?src\/main\.[tj]sx?["']/i.test(c)||/\/@vite\/client/i.test(c)||/<title>\s*Studio\s*Jungle/i.test(c)&&/Studiojungle|studiojungle\.ai/i.test(c):!1},s=e.filter(l=>l.language==="html"&&!n(l));for(const l of s){const c=aF(l),u=l.content.includes("<html")||l.content.includes("<!DOCTYPE")?l.content:Lk(l.content),d=Mk(u,l.filename),p=c==="/"?"Home":c?c.replace(/^\//,"").replace(/[-_]/g," ").replace(/\b\w/g,h=>h.toUpperCase()):l.filename.replace(/\.\w+$/,"").split("/").pop()||l.filename;t.push({id:c||`html-${l.filename}`,name:p,filename:l.filename,html:d})}const i=new Set(t.map(l=>su(l.id)));{const l=[/^main\.[tj]sx?$/i,/router\.[tj]sx?$/i,/context\.[tj]sx?$/i,/provider\.[tj]sx?$/i,/types?\.[tj]s$/i,/utils?\.[tj]s$/i,/\.config\./i,/\.d\.ts$/i],c=e.filter(d=>{if(!["tsx","jsx"].includes(d.language))return!1;const p=d.filename.split("/").pop()||d.filename;if(!(/(?:^|\/)(?:pages|routes|screens|views)\//i.test(d.filename)||/(?:Page|Screen|View)\.[tj]sx?$/i.test(p)||/^(?:Home|Landing|App|Index)\.[tj]sx?$/i.test(p))||l.some(g=>g.test(p))||/^use[A-Z]/.test(p)||d.content.split(`
830`).length<8||!/return\s*\(?\s*<[a-zA-Z]/i.test(d.content))return!1;const f=d.content.match(/(?:export\s+(?:default\s+)?)?(?:function|const|class)\s+(\w+)/),x=(f==null?void 0:f[1])||"";return!(!x||x==="untitled")}),u=e.find(d=>d.language==="css");for(const d of c){const p=cF(d.content),h=d.filename.replace(/\\/g,"/").replace(/\.(tsx|jsx)$/i,""),f=p&&r.get(p)||r.get(h)||r.get(d.filename.replace(/\\/g,"/"))||oF(d),x=f?su(f):null;if(x&&i.has(x))continue;const g=d.filename.replace(/\.\w+$/,"").split("/").pop()||d.filename,y=f==="/"?"Home":f?f.replace(/^\//,"").replace(/[-_]/g," ").replace(/\b\w/g,v=>v.toUpperCase()):g,b=jF(d.content);if(b){const v=f||`page-${d.filename}`;t.push({id:v,name:y,filename:d.filename,html:Mk(Lk(b,u==null?void 0:u.content),d.filename)}),i.add(su(v))}}}const o=new Set;for(let l=0;l<t.length;l++){const c=su(t[l].id);if(o.has(c)){t.splice(l,1),l--;continue}c==="/"&&(t[l].id="/",t[l].name="Home"),o.add(c)}return t.length>0&&!t.find(l=>l.id==="/")&&(t[0].id="/",t[0].name===t[0].filename.replace(/\.\w+$/,"").split("/").pop()&&(t[0].name="Home")),mF(t),fF(t),t.length>0&&bF(t),RT(t),t}function RT(e){const t=new Set(e.map(l=>ii(l.id))),r=["/login","/signin","/signup","/register","/auth","/forgot-password","/reset-password"];e.some(l=>r.includes(ii(l.id)))&&r.forEach(l=>t.add(l)),t.add("/");const s=new Set,i=/(?:href|to)=["'](\/?[a-zA-Z][a-zA-Z0-9\-_/]*)["']/g;for(const l of e){let c;for(;(c=i.exec(l.html))!==null;){const u=c[1];u.startsWith("mailto:")||u.startsWith("tel:")||u.startsWith("http")||u==="#"||s.add(ii(u))}}const o=[];return s.forEach(l=>{t.has(l)||o.push(l)}),o}const Cy={hero:["https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=1200&h=600&fit=crop","https://images.unsplash.com/photo-1519389950473-47ba0277781c?w=1200&h=600&fit=crop","https://images.unsplash.com/photo-1504384308090-c894fdcc538d?w=1200&h=600&fit=crop","https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=600&fit=crop"],product:["https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=600&h=600&fit=crop","https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?w=600&h=600&fit=crop","https://images.unsplash.com/photo-1572635196237-14b3f281503f?w=600&h=600&fit=crop","https://images.unsplash.com/photo-1585386959984-a4155224a1ad?w=600&h=600&fit=crop","https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=600&h=600&fit=crop","https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=600&h=600&fit=crop"],avatar:["https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200&h=200&fit=crop","https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=200&h=200&fit=crop","https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&h=200&fit=crop","https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200&h=200&fit=crop","https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=200&h=200&fit=crop"],general:["https://images.unsplash.com/photo-1497366216548-37526070297c?w=800&h=500&fit=crop","https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=800&h=500&fit=crop","https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=800&h=500&fit=crop","https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=800&h=500&fit=crop","https://images.unsplash.com/photo-1518770660439-4636190af475?w=800&h=500&fit=crop","https://images.unsplash.com/photo-1550751827-4bd374c3f58b?w=800&h=500&fit=crop"],food:["https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=600&h=600&fit=crop","https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?w=600&h=600&fit=crop"],fashion:["https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=800&h=500&fit=crop"]};function hF(e,t,r){const n=(e+t).toLowerCase();return/avatar|profile|user|author|testimonial|review/i.test(n)||/rounded-full|w-1[0-6]|h-1[0-6]|w-8|h-8|w-10|h-10|w-12|h-12/i.test(n)?"avatar":/product|item|shop|cart|price|buy|store|merchandise/i.test(n)||/product|shop|ecommerce|store/i.test(r.slice(0,500).toLowerCase())?"product":/hero|banner|cover|jumbotron|w-full.*h-[4-9]|h-\[.*px\]/i.test(n)?"hero":/food|dish|meal|recipe|restaurant|menu/i.test(n)||/restaurant|food|menu/i.test(r.slice(0,500).toLowerCase())?"food":"general"}function fF(e){const t=[/^\.?\//,/^(?:src|assets|images|public)\//i,/^@\//,/^(?:placeholder|image|photo|img)\d*\.(?:png|jpg|jpeg|svg|webp)$/i,/^\{\{.*\}\}$/,/^\$\{.*\}$/,/^undefined$|^null$|^$/,/placehold\.co|placeholder\.com|via\.placeholder/i,/^__placeholder__$/,/^\[[\w.]+\]$/],r=s=>s.includes("unsplash.com")?/photo-\d{10,}/.test(s):!0,n=s=>!s||s==="undefined"||s==="null"||t.some(i=>i.test(s))||/^https?:\/\//.test(s)&&!r(s)?!0:!(/^https?:\/\//.test(s)||/^data:|^blob:/.test(s));for(const s of e){const i={};s.html=s.html.replace(/src="\[[\w.]+\]"/gi,'src=""').replace(/src='\[[\w.]+\]'/gi,"src=''"),s.html=s.html.replace(/<img([^>]*?)\ssrc\s*=\s*(?:(["'])(.*?)\2|([^\s>]+))([^>]*?)>/gi,(o,l,c,u,d,p)=>{const h=String(u??d??"").trim().replace(/^['"]|['"]$/g,"");if(!n(h))return o;const f=hF(l,p,s.html),x=Cy[f];i[f]=((i[f]||0)+1)%x.length;const g=x[i[f]];let y=`${l} src="${g}"${p}`;return/class=/.test(y)?/object-cover/.test(y)||(y=y.replace(/class="([^"]*)"/,'class="$1 object-cover"')):y=y.replace(/^/,' class="object-cover" '),/loading=/.test(y)||(y+=' loading="lazy"'),`<img${y}>`}),s.html=s.html.replace(/background-image:\s*url\(["']?([^"')]+)["']?\)/gi,(o,l)=>{const c=(l||"").trim();if(!n(c))return o;const u=Cy.hero;return i.bg=((i.bg||0)+1)%u.length,`background-image: url('${u[i.bg]}')`}),s.html=s.html.replace(/(<script[\s\S]*?<\/script>)/gi,o=>o.replace(/((?:image|avatar|photo|picture|thumbnail|img|src|poster|
830cover|banner|icon|logo)(?:_url|Url|URL|_src|Src)?)\s*:\s*(['"])((?:(?!\2).)*)\2/gi,(l,c,u,d)=>{const p=d.trim();if(/^https?:\/\//.test(p)&&!n(p)||/^data:|^blob:/.test(p)||p==="")return l;const h=c.toLowerCase();let f="general";/avatar|profile|user|author|person/.test(h)?f="avatar":/product|item|merchandise/.test(h)?f="product":/hero|banner|cover/.test(h)?f="hero":/food|dish|meal/.test(h)&&(f="food");const x=Cy[f],g="js_"+f;return i[g]=((i[g]||0)+1)%x.length,`${c}: ${u}${x[i[g]]}${u}`}))}}function mF(e){const t=new Set(e.map(l=>ii(l.id))),r=/href=["']\/?(?:login|signin|signup|register|auth|forgot-password|reset-password)["']/i,n=e.some(l=>r.test(l.html)),s=/(?:sign\s*in|log\s*in|sign\s*up|register|create\s*account|forgot\s*password)/i,i=e.some(l=>s.test(l.html));if(!n&&!i)return;const o=[{route:"/auth",name:"Auth",generator:gF},{route:"/forgot-password",name:"Forgot Password",generator:xF}];for(const{route:l,name:c,generator:u}of o)(l==="/auth"?["/auth","/login","/signin","/signup","/register"]:[l]).some(p=>t.has(p))||(e.push({id:l,name:c,filename:`${l.slice(1)}.html`,html:u()}),t.add(l))}function Ew(e){return`<!DOCTYPE html>
831<html lang="en">
832<head>
833<meta charset="utf-8">
834<meta name="viewport" content="width=device-width, initial-scale=1">
835<!-- route: ${e} -->
836<script src="https://cdn.tailwindcss.com"><\/script>
837<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
838<script>
839tailwind.config = {
840  theme: {
841    extend: {
842      fontFamily: { sans: ['Plus Jakarta Sans', 'system-ui', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] },
843      colors: {
844        brand: { 50:'#eff4ff', 100:'#dbe6fe', 200:'#bfd3fe', 300:'#93b4fd', 400:'#6090fa', 500:'#3b76f6', 600:'#2563eb', 700:'#1d4fd8', 800:'#1e40af', 900:'#1e3a8a' },
845        accent: { 50:'#effefb', 100:'#c8fff4', 200:'#90ffe9', 300:'#51f7da', 400:'#1de4c5', 500:'#05b89a', 600:'#049880', 700:'#077a68', 800:'#096054', 900:'#0a5046' },
846      }
847    }
848  }
849}
850<\/script>
851<style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:'Plus Jakarta Sans',system-ui,sans-serif;min-height:100vh}</style>
852</head>`}function gF(){return`${Ew("/auth")}
853<body class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-brand-50 flex items-center justify-center p-4">
854  <div class="w-full max-w-md">
855    <div class="bg-white/80 backdrop-blur-xl rounded-2xl shadow-xl shadow-brand-500/5 border border-slate-200/60 p-8">
856      <div class="text-center mb-8">
857        <div class="w-12 h-12 bg-gradient-to-br from-brand-500 to-brand-600 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-brand-500/25">
858          <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
859        </div>
860        <h1 id="auth-title" class="text-2xl font-bold text-slate-900">Welcome back</h1>
861        <p id="auth-subtitle" class="text-sm text-slate-500 mt-1">Sign in to your account</p>
862      </div>
863      <div id="auth-error" style="display:none" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700"></div>
864      <div id="auth-success" style="display:none" class="mb-4 p-3 bg-green-50 border border-green-200 rounded-xl text-sm text-green-700"></div>
865      <form id="auth-form" class="space-y-4">
866        <div id="name-field" style="display:none">
867          <label class="block text-sm font-medium text-slate-700 mb-1">Full Name</label>
868          <input id="input-name" type="text" placeholder="John Doe" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition" />
869        </div>
870        <div>
871          <label class="block text-sm font-medium text-slate-700 mb-1">Email</label>
872          <input id="input-email" type="email" placeholder="[email protected]" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition" required />
873        </div>
874        <div>
875          <label class="block text-sm font-medium text-slate-700 mb-1">Password</label>
876          <input id="input-password" type="password" placeholder="••••••••" minlength="6" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition" required />
877        </div>
878        <div id="login-extras" class="flex items-center justify-between">
879          <label class="flex items-center gap-2 text-sm text-slate-600"><input type="checkbox" class="rounded accent-brand-600" /> Remember me</label>
880          <a href="/forgot-password" class="text-sm text-brand-600 hover:text-brand-700 font-medium">Forgot password?</a>
881        </div>
882        <button id="submit-btn" type="submit" class="w-full py-2.5 bg-gradient-to-r from-brand-600 to-brand-500 hover:from-brand-700 hover:to-brand-600 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-brand-500/20 hover:shadow-lg hover:shadow-brand-500/30">
883          <span id="submit-text">Sign In</span>
884        </button>
885      </form>
886      <div class="mt-6 flex items-center gap-3">
887        <div class="flex-1 h-px bg-slate-200"></div>
888        <span class="text-xs text-slate-400 font-medium">or</span>
889        <div class="flex-1 h-px bg-slate-200"></div>
890      </div>
891      <div class="mt-4 text-center">
892        <p class="text-sm text-slate-500">
893          <span id="toggle-prompt">Don't have an account?</span>
894          <button id="toggle-btn" onclick="toggleAuthMode()" class="text-brand-600 hover:text-brand-700 font-semibold ml-1">Sign Up</button>
895        </p>
896      </div>
897    </div>
898    <p class="text-center text-[11px] text-slate-400 mt-4">Secured with end-to-end encryption</p>
899  </div>
900  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.min.js"><\/script>
901  <script>
902  var isLogin = true;
903  var supabaseClient = null;
904
905  // Try to init from embedded meta tags first (works outside preview iframe)
906  function tryInitFromMeta() {
907    var metaUrl = document.querySelector('meta[name="sb-url"]');
908    var metaKey = document.querySelector('meta[name="sb-key"]');
909    if (metaUrl && metaKey && metaUrl.content && metaKey.content) {
910      try {
911        supabaseClient = window.supabase.createClient(metaUrl.content, metaKey.content);
912        return true;
913      } catch(err) { console.error('Meta init failed:', err); }
914    }
915    // Try localStorage fallback (set by preview parent)
916    try {
917      var savedUrl = localStorage.getItem('sj_auth_url');
918      var savedKey = localStorage.getItem('sj_auth_key');
919      if (savedUrl && savedKey) {
920        supabaseClient = window.supabase.createClient(savedUrl, savedKey);
921        return true;
922      }
923    } catch(e) {}
924    return false;
925  }
926
927  // Request auth config from parent studio (preview mode)
928  if (!tryInitFromMeta()) {
929    window.parent.postMessage({ type: 'request-auth-config' }, '*');
930    setTimeout(function() { if (!supabaseClient) window.parent.postMessage({ type: 'request-auth-config' }, '*'); }, 1000);
931    setTimeout(function() { if (!supabaseClient) window.parent.postMessage({ type: 'request-auth-config' }, '*'); }, 3000);
932  }
933  window.addEventListener('message', function(e) {
934    if (e.data && e.data.type === 'auth-config' && e.data.url && e.data.anonKey) {
935      try {
936        supabaseClient = window.supabase.createClient(e.data.url, e.data.anonKey);
937        // Persist for future page loads (e.g. navigating within the app)
938        try { localStorage.setItem('sj_auth_url', e.data.url); localStorage.setItem('sj_auth_key', e.data.anonKey); } catch(se) {}
939      } catch(err) { console.error('Failed to init Supabase client:', err); }
940    }
941  });
942
943  function showError(msg) {
944    var el = document.getElementById('auth-error');
945    el.textContent = msg;
946    el.style.display = 'block';
947    document.getElementById('auth-success').style.display = 'none';
948  }
949  function showSuccess(msg) {
950    var el = document.getElementById('auth-success');
951    el.textContent = msg;
952    el.style.display = 'block';
953    document.getElementById('auth-error').style.display = 'none';
954  }
955
956  function toggleAuthMode() {
957    isLogin = !isLogin;
958    document.getElementById('auth-error').style.display = 'none';
959    document.getElementById('auth-success').style.display = 'none';
960    document.getElementById('auth-title').textContent = isLogin ? 'Welcome back' : 'Create account';
961    document.getElementById('auth-subtitle').textContent = isLogin ? 'Sign in to your account' : 'Sign up for a new account';
962    document.getElementById('name-field').style.display = isLogin ? 'none' : 'block';
963    document.getElementById('login-extras').style.display = isLogin ? 'flex' : 'none';
964    document.getElementById('submit-text').textContent = isLogin ? 'Sign In' : 'Create Account';
965    document.getElementById('toggle-prompt').textContent = isLogin ? "Don't have an account?" : 'Already have an account?';
966    document.getElementById('toggle-btn').textContent = isLogin ? 'Sign Up' : 'Sign In';
967  }
968
969  document.getElementById('auth-form').addEventListener('submit', async function(e) {
970    e.preventDefault();
971    if (!supabaseClient) {
972      showError('Authentication is not configured for this project. Connect a Supabase instance in the Auto DB panel first.');
973      return;
974    }
975    var email = document.getElementById('input-email').value.trim();
976    var password = document.getElementById('input-password').value;
977    var btn = document.getElementById('submit-btn');
978    btn.disabled = true;
979    btn.style.opacity = '0.6';
980    document.getElementById('auth-error').style.display = 'none';
981
982    try {
983      if (isLogin) {
984        var result = await supabaseClient.auth.signInWithPassword({ email: email, password: password });
985        if (result.error) throw result.error;
986        showSuccess('Signed in successfully! Redirecting...');
987        setTimeout(function() { window.parent.postMessage({ type: 'nav-page', pageId: '/' }, '*'); }, 1000);
988      } else {
989        var name = document.getElementById('input-name').value.trim();
990        var result = await supabaseClient.auth.signUp({
991          email: email,
992          password: password,
993          options: { data: { display_name: name } }
994        });
995        if (result.error) throw result.error;
996        if (result.data.user && !result.data.session) {
997          showSuccess('Check your email for a confirmation link to complete sign up.');
998        } else {
999          showSuccess('Account created! Redirecting...');
1000          setTimeout(function() { window.parent.postMessage({ type: 'nav-page', pageId: '/' }, '*'); }, 1000);
1001        }
1002      }
1003    } catch(err) {
1004      showError(err.message || 'Authentication failed. Please try again.');
1005    } finally {
1006      btn.disabled = false;
1007      btn.style.opacity = '1';
1008    }
1009  });
1010  <\/script>
1011</body>
1012</html>`}function xF(){return`${Ew("/forgot-password")}
1013<body class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-accent-50 flex items-center justify-center p-4">
1014  <div class="w-full max-w-md">
1015    <div class="bg-white/80 backdrop-blur-xl rounded-2xl shadow-xl shadow-accent-500/5 border border-slate-200/60 p-8">
1016      <div class="text-center mb-8">
1017        <div class="w-12 h-12 bg-gradient-to-br from-accent-500 to-accent-600 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-accent-500/25">
1018          <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>
1019        </div>
1020        <h1 class="text-2xl font-bold text-slate-900">Reset password</h1>
1021        <p class="text-sm text-slate-500 mt-1">Enter your email and we'll send a reset link</p>
1022      </div>
1023      <div id="fp-error" style="display:none" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700"></div>
1024      <form id="fp-form" class="space-y-4">
1025        <div>
1026          <label class="block text-sm font-medium text-slate-700 mb-1">Email address</label>
1027          <input id="fp-email" type="email" placeholder="[email protected]" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-accent-500/20 focus:border-accent-500 transition" required />
1028        </div>
1029        <button id="fp-btn" type="submit" class="w-full py-2.5 bg-gradient-to-r from-accent-600 to-accent-500 hover:from-accent-700 hover:to-accent-600 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-accent-500/20">
1030          <span id="fp-btn-text">Send Reset Link</span>
1031        </button>
1032      </form>
1033      <div id="fp-success" style="display:none" class="text-center py-4">
1034        <div class="w-10 h-10 bg-accent-100 rounded-full flex items-center justify-center mx-auto mb-3">
1035          <svg class="w-5 h-5 text-accent-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
1036        </div>
1037        <p class="text-sm text-slate-700 font-medium">Check your email for a reset link</p>
1038      </div>
1039      <div class="mt-6 text-center">
1040        <a href="/auth" class="text-sm text-brand-600 hover:text-brand-700 font-medium">← Back to sign in</a>
1041      </div>
1042    </div>
1043  </div>
1044  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.min.js"><\/script>
1045  <script>
1046  var fpClient = null;
1047
1048  // Try meta tags / localStorage first
1049  (function() {
1050    var metaUrl = document.querySelector('meta[name="sb-url"]');
1051    var metaKey = document.querySelector('meta[name="sb-key"]');
1052    if (metaUrl && metaKey && metaUrl.content && metaKey.content) {
1053      try { fpClient = window.supabase.createClient(metaUrl.content, metaKey.content); return; } catch(e) {}
1054    }
1055    try {
1056      var savedUrl = localStorage.getItem('sj_auth_url');
1057      var savedKey = localStorage.getItem('sj_auth_key');
1058      if (savedUrl && savedKey) { fpClient = window.supabase.createClient(savedUrl, savedKey); return; }
1059    } catch(e) {}
1060  })();
1061
1062  if (!fpClient) {
1063    window.parent.postMessage({ type: 'request-auth-config' }, '*');
1064    setTimeout(function() { if (!fpClient) window.parent.postMessage({ type: 'request-auth-config' }, '*'); }, 1000);
1065  }
1066
1067  window.addEventListener('message', function(e) {
1068    if (e.data && e.data.type === 'auth-config' && e.data.url && e.data.anonKey) {
1069      try {
1070        fpClient = window.supabase.createClient(e.data.url, e.data.anonKey);
1071        try { localStorage.setItem('sj_auth_url', e.data.url); localStorage.setItem('sj_auth_key', e.data.anonKey); } catch(se) {}
1072      } catch(err) { console.error(err); }
1073    }
1074  });
1075
1076  document.getElementById('fp-form').addEventListener('submit', async function(e) {
1077    e.preventDefault();
1078    var errorEl = document.getElementById('fp-error');
1079    errorEl.style.display = 'none';
1080
1081    if (!fpClient) {
1082      errorEl.textContent = 'Authentication is not configured for this project.';
1083      errorEl.style.display = 'block';
1084      return;
1085    }
1086
1087    var email = document.getElementById('fp-email').value.trim();
1088    var btn = document.getElementById('fp-btn');
1089    btn.disabled = true;
1090    document.getElementById('fp-btn-text').textContent = 'Sending...';
1091
1092    try {
1093      var result = await fpClient.auth.resetPasswordForEmail(email, {
1094        redirectTo: window.location.origin + '/reset-password'
1095      });
1096      if (result.error) throw result.error;
1097      document.getElementById('fp-form').style.display = 'none';
1098      document.getElementById('fp-success').style.display = 'block';
1099    } catch(err) {
1100      errorEl.textContent = err.message || 'Failed to send reset link.';
1101      errorEl.style.display = 'block';
1102    } finally {
1103      btn.disabled = false;
1104      document.getElementById('fp-btn-text').textContent = 'Send Reset Link';
1105    }
1106  });
1107  <\/script>
1108</body>
1109</html>`}function ii(e){if(!e)return"/";let n=((e.startsWith("/")?e:`/${e}`).split("#")[0].split("?")[0]||"/").replace(/\/+/g,"/");return n==="/index"||n==="/index.html"?"/":(n=n.replace(/\/index\.html$/i,"").replace(/\.html$/i,""),n.length>1&&(n=n.replace(/\/$/,"")),n||"/")}function yF(e){const t={},r=[["/products","/shop","/store","/catalog","/items","/browse"],["/cart","/basket","/shopping-cart","/bag"],["/checkout","/payment","/pay","/order"],["/about","/about-us","/who-we-are"],["/contact","/contact-us","/get-in-touch","/support"],["/categories","/collections","/departments"],["/account","/profile","/my-account","/user"],["/orders","/my-orders","/order-history"],["/wishlist","/favorites","/saved"],["/faq","/help","/faqs"],["/blog","/news","/articles","/posts"],["/pricing","/plans","/price"],["/dashboard","/admin","/panel"],["/settings","/preferences","/config"]];for(const s of e){const i=ii(s),o=new Set([i,`${i}/`,`${i}.html`,`${i}/index.html`]);i==="/"&&(o.add("/index"),o.add("/index.html"));for(const l of r)l.includes(i)&&l.forEach(c=>o.add(c));o.forEach(l=>{t[ii(l)]=s})}const n=e.includes("/auth")?"/auth":e.find(s=>/(?:^|[\/_-])(auth|login|signup|signin|register)(?:[\/_\.-]|$)/i.test(s));return n&&["/auth","/login","/signin","/signup","/register","/forgot-password","/reset-password"].forEach(s=>{t[ii(s)]=n}),t}function bF(e){const r=e.map(s=>({id:s.id,name:s.name})).map(s=>s.id),n=yF(r);for(const s of e){const i=s.id;["/auth","/login","/signin","/signup","/register","/reset-password","/forgot-password"].includes(ii(i));const o=`
1110<!-- Auto-injected navigation routing script (no visible nav bar — controlled by studio) -->
1111<script>
1112(function(){
1113
1114  var routeAliasMap = ${JSON.stringify(n)};
1115  var BASE_ORIGIN = 'http://localhost';
1116
1117  function normalizePath(pathname){
1118    if (!pathname) return '/';
1119    var raw = pathname.split('#')[0].split('?')[0] || '/';
1120    var normalized = raw.startsWith('/') ? raw : '/' + raw;
1121    normalized = normalized.replace(//+/g, '/');
1122    if (normalized === '/index' || normalized === '/index.html') return '/';
1123    normalized = normalized.replace(//index.html$/i, '').replace(/.html$/i, '');
1124    if (normalized.length > 1) normalized = normalized.replace(//$/, '');
1125    return normalized || '/';
1126  }
1127
1128  function resolveInternalRoute(pathname){
1129    var normalized = normalizePath(pathname);
1130    return routeAliasMap[normalized] || null;
1131  }
1132
1133  function showToast(msg, isWarning){
1134    var el = document.createElement('div');
1135    el.textContent = msg;
1136    var bgColor = isWarning ? 'rgba(234,88,12,0.9)' : 'rgba(0,0,0,0.8)';
1137    el.style.cssText = 'position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:'+bgColor+';color:#fff;padding:8px 18px;border-radius:10px;font-size:12px;z-index:99999;pointer-events:none;opacity:0;transition:opacity .2s;max-width:90%;text-align:center';
1138    document.body.appendChild(el);
1139    requestAnimationFrame(function(){ el.style.opacity='1'; });
1140    setTimeout(function(){ el.style.opacity='0'; setTimeout(function(){ el.remove(); },300); },2500);
1141  }
1142
1143  function postNav(routeId, hash){
1144    if (!routeId) return;
1145    showToast('Navigating to ' + routeId + (hash || ''));
1146    window.parent.postMessage({ type:'nav-page', pageId: routeId, hash: hash || '' }, '*');
1147  }
1148
1149  function navigateByUrl(urlLike){
1150    try {
1151      var rawUrl = String(urlLike || '').trim();
1152      if (!rawUrl || rawUrl === '#' || /^(mailto:|tel:|javascript:)/i.test(rawUrl)) return false;
1153      var url = new URL(rawUrl, BASE_ORIGIN);
1154      var targetRoute = resolveInternalRoute(url.pathname);
1155      if (!targetRoute) return false;
1156      postNav(targetRoute, url.hash || '');
1157      return true;
1158    } catch (_err) {
1159      return false;
1160    }
1161  }
1162
1163  var originalPushState = history.pushState;
1164  history.pushState = function(state, title, url){
1165    if (url != null && navigateByUrl(url)) return;
1166    return originalPushState.apply(history, arguments);
1167  };
1168
1169  var originalReplaceState = history.replaceState;
1170  history.replaceState = function(state, title, url){
1171    if (url != null && navigateByUrl(url)) return;
1172    return originalReplaceState.apply(history, arguments);
1173  };
1174
1175  try {
1176    var originalOpen = window.open;
1177    window.open = function(url, target, features){
1178      if (url != null && navigateByUrl(url)) return null;
1179      return originalOpen ? originalOpen.call(window, url, target, features) : null;
1180    };
1181  } catch (_err) {}
1182
1183  try {
1184    var originalAssign = window.location.assign.bind(window.location);
1185    window.location.assign = function(url){
1186      if (navigateByUrl(url)) return;
1187      return originalAssign(url);
1188    };
1189  } catch (_err) {}
1190
1191  try {
1192    var originalReplace = window.location.replace.bind(window.location);
1193    window.location.replace = function(url){
1194      if (navigateByUrl(url)) return;
1195      return originalReplace(url);
1196    };
1197  } catch (_err) {}
1198
1199  document.addEventListener('click', function(e){
1200    var clickable = e.target && e.target.closest
1201      ? e.target.closest('a[href],[href],[to],[data-href],[data-to],[onclick]')
1202      : null;
1203    if (!clickable) return;
1204
1205    var href = clickable.getAttribute('href')
1206      || clickable.getAttribute('to')
1207      || clickable.getAttribute('data-href')
1208      || clickable.getAttribute('data-to');
1209    var onclickAttr = clickable.getAttribute('onclick') || '';
1210    if (!href && onclickAttr) {
1211      var locationMatch = onclickAttr.match(/(?:window.)?location(?:.href)?s*=s*['"]([^'"]+)['"]/i)
1212        || onclickAttr.match(/location.(?:assign|replace)(s*['"]([^'"]+)['"]s*)/i);
1213      href = locationMatch ? locationMatch[1] : '';
1214    }
1215
1216    if (!href || href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:') || href.startsWith('javascript:')) return;
1217    if (clickable.getAttribute('target') === '_blank' || clickable.hasAttribute('download')) return;
1218
1219    // ALWAYS prevent default for internal-looking links to stop iframe from navigating away
1220    e.preventDefault();
1221    e.stopPropagation();
1222
1223    try {
1224      if (navigateByUrl(href)) return;
1225
1226      var url = new URL(href, BASE_ORIGIN);
1227      if (/^https?:/i.test(String(href)) && url.origin !== BASE_ORIGIN) {
1228        showToast('Opening external link');
1229        window.open(url.toString(), '_blank', 'noopener,noreferrer');
1230        return;
1231      }
1232
1233      var route = normalizePath(url.pathname);
1234      // Fallback: page not generated yet → go to home (or whichever page is
1235      // available) instead of leaving the user staring at a blank iframe.
1236      // Also notify the parent so the unresolved-routes banner can show.
1237      showToast('Page "' + route + '" not generated yet — showing home', true);
1238      window.parent.postMessage({ type:'unresolved-route', route: route }, '*');
1239      window.parent.postMessage({ type:'nav-page', pageId: '/', hash: '' }, '*');
1240    } catch (_err) {
1241      showToast('Could not navigate — going home', true);
1242      window.parent.postMessage({ type:'nav-page', pageId: '/', hash: '' }, '*');
1243    }
1244  }, true);
1245
1246  document.addEventListener('submit', function(e){
1247    var form = e.target && e.target.closest ? e.target.closest('form') : null;
1248    if (!form) return;
1249
1250    var action = form.getAttribute('action');
1251    if (!action) return;
1252
1253    try {
1254      var url = new URL(action, window.location.origin);
1255      if (url.origin !== window.location.origin) return;
1256      e.preventDefault();
1257      if (!navigateByUrl(url.toString())) {
1258        showToast('Route not available in preview yet');
1259      }
1260    } catch (_err) {}
1261  }, true);
1262})();
1263<\/script>
1264<!-- End navigation -->`,l=s.html.match(/<body[^>]*>/i);if(l&&l.index!==void 0){const c=l.index+l[0].length;s.html=s.html.slice(0,c)+o+s.html.slice(c)}}}function vF(e){const t=e.replace(/^\//,"").replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())||"Page",r=`${Ew(e)}
1265<body class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-brand-50">
1266  <div class="max-w-4xl mx-auto px-6 py-16">
1267    <div class="bg-white/80 backdrop-blur-xl rounded-2xl shadow-xl shadow-brand-500/5 border border-slate-200/60 p-12 text-center">
1268      <div class="w-14 h-14 bg-gradient-to-br from-brand-500 to-accent-500 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg shadow-brand-500/20">
1269        <svg class="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/></svg>
1270      </div>
1271      <h1 class="text-3xl font-bold text-slate-900 mb-3">${t}</h1>
1272      <p class="text-slate-500 text-sm max-w-md mx-auto mb-8">This page was auto-generated as a placeholder. Ask the AI to build out the full <code class="px-1.5 py-0.5 bg-slate-100 rounded text-xs font-mono text-brand-600">${e}</code> page with your desired content.</p>
1273      <div class="flex items-center justify-center gap-3">
1274        <a href="/" class="px-5 py-2.5 bg-gradient-to-r from-brand-600 to-brand-500 hover:from-brand-700 hover:to-brand-600 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-brand-500/20">← Back to Home</a>
1275      </div>
1276    </div>
1277  </div>
1278</body>
1279</html>`;return{id:e,name:t,filename:`${e.slice(1).replace(/\//g,"-")||"page"}.html`,html:r}}function Mk(e,t){if(!e||!t)return e;let r=0,n=1;return e.replace(/<([a-zA-Z][a-zA-Z0-9-]*)/g,(s,i,o,l)=>{const c=(l.slice(r,o).match(/\n/g)||[]).length;n+=c,r=o;const u=l.slice(o,o+200);return/\sdata-sj-source\s*=/.test(u.split(">")[0]||"")?s:`${s} data-sj-source="${t}:${n}"`})}function Lk(e,t){return`<!DOCTYPE html>
1280<html lang="en">
1281<head>
1282<meta charset="utf-8">
1283<meta name="viewport" content="width=device-width, initial-scale=1">
1284<script src="https://cdn.tailwindcss.com"><\/script>
1285<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
1286<style>
1287*{box-sizing:border-box;margin:0;padding:0}
1288body{font-family:'Inter',system-ui,sans-serif;min-height:100vh}
1289img{max-width:100%;height:auto}
1290${t||""}
1291</style>
1292</head>
1293<body class="min-h-screen bg-white">
1294${e}
1295</body>
1296</html>`}function wF(e){const t=e.trim();if(!t||!/<(?:div|main|section|article|header|footer|nav|form|button|a|h[1-6]|p|ul|ol|li|table|img)\b/i.test(t))return!1;const r=t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").trim();return!(/^[\s,;)}\]]+/.test(r)||/[{}]\)|\)\}|=>|;\s*\}|\}
1296\s*,|\{\s*\)/.test(r)||/\b(?:const|let|var|return|function)\s+[A-Za-z_$]/.test(r))}function jF(e){let t="";const r=e.match(/return\s*\(\s*/);if(r&&r.index!==void 0){const i=r.index+r[0].length;t=$k(e,i)}if(!t){const i=e.match(/=>\s*\(\s*/);if(i&&i.index!==void 0){const o=i.index+i[0].length;t=$k(e,o)}}if(!t){const i=e.match(/=>\s*(<[a-zA-Z][\s\S]*)/);i&&(t=i[1])}if(!t){const i=e.match(/return\s+(<[a-zA-Z][\s\S]*)/);i&&(t=i[1])}if(!t)return"";const s=NF(t).replace(/;\s*\}[\s;]*/g,"").replace(/export\s+default\s+\w+;?/g,"").replace(/^\s*\)\s*;?\s*$/gm,"").trim();return wF(s)?s:""}function $k(e,t){let r=0,n=null;for(let o=t;o<e.length;o++){const l=e[o],c=o>0?e[o-1]:"";if(!n&&(l==='"'||l==="'"||l==="`")&&c!=="\\"){n=l;continue}if(n&&l===n&&c!=="\\"){n=null;continue}if(!n&&(l==="("&&r++,l===")")){if(r===0)return e.slice(t,o).trim();r--}}const s=e.slice(t),i=s.lastIndexOf("</");if(i>0){const o=s.indexOf(">",i);if(o>0)return s.slice(0,o+1).trim()}return""}function NF(e){return e.replace(/<(?:Router)?NavLink\b/g,"<a").replace(/<Link\b/g,"<a").replace(/<\/Link>/g,"</a>").replace(/<\/(?:Router)?NavLink>/g,"</a>").replace(/className=/g,"class=").replace(/htmlFor=/g,"for=").replace(/\bto=\{`([^`]*)`\}/g,'href="$1"').replace(/\bto=\{"([^"]*)"\}/g,'href="$1"').replace(/\bto=\{'([^']*)'\}/g,'href="$1"').replace(/\bto="([^"]*)"/g,'href="$1"').replace(/\bto='([^']*)'/g,'href="$1"').replace(/\bsrc=\{[^}]+\}/g,'src="__placeholder__"').replace(/\b(href|to)=\{[^}]+\}/g,'$1=""').replace(/\{\/\*[\s\S]*?\*\/\}/g,"").replace(/\s+on[A-Z]\w*=\{[^}]*\}/g,"").replace(/\s+ref=\{[^}]*\}/g,"").replace(/\s+key=\{[^}]*\}/g,"").replace(/\s+style=\{[^}]*\}/g,"").replace(/\{`([^`]*)`\}/g,"$1").replace(/\{"([^"]*)"\}/g,"$1").replace(/\{'([^']*)'\}/g,"$1").replace(/\{(\w+)\.(\w+)\}/g,"[$1.$2]").replace(/\{(\w+)\}/g,"[$1]").replace(/\{[\s\S]*?\.map\([\s\S]*?\)\}/g,"").replace(/\{[^{}]*\?[^{}]*:[^{}]*\}/g,"").replace(/<([A-Z]\w+)([^>]*?)\/>/g,"<div$2></div>").replace(/<([A-Z]\w+)([^>]*)>([\s\S]*?)<\/\1>/g,"<div$2>$3</div>").replace(new RegExp("<(img|br|hr|input|meta|link)([^>]*?)(?<!\\/)>","g"),"<$1$2 />").replace(/\{[^}]*\}/g,"")}const DT="(window.location.pathname.match(/^\\/(ey[A-Za-z0-9._-]+)/)?.[0]) || ''";function kF(e){return/from\s+['"]react-router-dom['"]/.test(e)&&/<Routes\b|<Link\b|useRoutes\b/.test(e)}function SF(e){let t=e;if(/from\s+['"]react-router-dom['"]/.test(t))/BrowserRouter/.test(t)||(t=t.replace(/import\s+\{([^}]+)\}\s+from\s+['"]react-router-dom['"]/,(r,n)=>`import { ${n.trim()}, BrowserRouter } from 'react-router-dom'`));else{const r=t.match(/import\s+.*from\s+['"]react-dom\/client['"]/);r?t=t.replace(r[0],`${r[0]}
1297import { BrowserRouter } from 'react-router-dom';`):t=`import { BrowserRouter } from 'react-router-dom';
1298${t}`}return/<BrowserRouter\b/.test(t)||(t=t.replace(/(<App\s*\/>)/,`<BrowserRouter basename={${DT}}>
1299      $1
1300    </BrowserRouter>`)),t}function CF(e){let t=e.replace(/<BrowserRouter\b[^>]*>\s*/g,"");return t=t.replace(/\s*<\/BrowserRouter>/g,""),t=t.replace(/import\s+\{([^}]+)\}\s+from\s+['"]react-router-dom['"]/g,(r,n)=>{const s=n.split(",").map(i=>i.trim()).filter(i=>i&&i!=="BrowserRouter");return s.length===0?"":`import { ${s.join(", ")} } from 'react-router-dom'`}),t=t.replace(/\nimport\s+\{\s*\}\s+from\s+['"]react-router-dom['"]\s*;?\n/g,`
1301`),t}function MT(e,t){const r=kF(t),n=/<BrowserRouter\b/.test(t);if(!r&&!n)return null;let s=e,i=t,o=!1;return n&&(i=CF(t),i!==t&&(o=!0)),r&&!/<BrowserRouter\b/.test(s)&&(s=SF(s),o=!0),o?{mainContent:s,appContent:i}:null}function PF(e){const t=e.toLowerCase();return t.includes("useRoutes() may be used only in the context of a <Router>")||t.includes("cannot destructure property 'basename'")||t.includes('cannot destructure property "basename"')||t.includes("duplicate_router")||t.includes("<Link>")&&t.includes("router")}function AF(e){return/replace\s*\(\s*\/\[\//.test(e)||/replace\s*\(\s*\/\/\$/.test(e)||/BASE_URL\s*\?\s*import\.meta/.test(e)}function bm(e){return!e||!/<BrowserRouter\b/.test(e)||/<BrowserRouter[^>]*\bbasename\s*=/.test(e)&&!AF(e)?e:e.replace(/<BrowserRouter\b[^>]*>
1301/,`<BrowserRouter basename={${DT}}>`)}function _F(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").split("\\").join("/");if(r!=="src/main.tsx"&&r!=="src/main.jsx")return t;const n=bm(t.content);return n===t.content?t:{...t,content:n}})}function LT(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"&&typeof n.content=="string"?r.push({path:s.replace(/^\/+/,"").split("\\").join("/"),content:n.content}):n.type==="folder"&&n.children&&r.push(...LT(n.children,s))}return r}function TF(e){const t=[],r=LT(e),n=r.find(l=>l.path==="src/main.tsx"||l.path==="src/main.jsx"),s=r.find(l=>l.path==="src/App.tsx"||l.path==="src/App.jsx"),i=new Map;if(n&&s){const l=MT(n.content,s.content);l&&(l.mainContent&&l.mainContent!==n.content&&i.set(n.path,bm(l.mainContent)),l.appContent&&l.appContent!==s.content&&i.set(s.path,l.appContent))}const o=(l,c="")=>l.map(u=>{const d=c?`${c}/${u.name}`:u.name;if(u.type==="file"&&typeof u.content=="string"){const p=d.replace(/^\/+/,"").split("\\").join("/");let h=u.content;return i.has(p)?h=i.get(p):(p==="src/main.tsx"||p==="src/main.jsx")&&(h=bm(u.content)),h!==u.content?(t.push({path:p,content:h}),{...u,content:h}):u}return u.type==="folder"&&u.children?{...u,children:o(u.children,d)}:u});return{tree:o(e),repaired:t}}function EF(){try{const t=window.localStorage.getItem("sj_preview_backend");if(t==="e2b"||t==="vercel")return t}catch{}return void 0==="vercel"?"vercel":"e2b"}const IF=new Set(["start","apply","restart","reinstall","add_deps"]),of=new Map;function Iw(e){if(!e)return!1;try{if(sessionStorage.getItem(`sj-defer-warmup:${e}`)||sessionStorage.getItem("sj_pending_new_project"))return!0}catch{}return!1}async function Fk(e){const t=EF()==="e2b"?"e2b-preview-runtime":"vercel-preview-runtime",{data:r,error:n}=await G.functions.invoke(t,{body:{action:e.action,project_id:e.projectId,files:e.files,deps:e.deps,manifest:e.manifest,preview_path:e.previewPath||"/",env:e.env||{},package_hash:e.packageHash,files_hash:e.filesHash,sandbox_id:e.sandboxId||void 0}});if(n){const s=n.context;if(s&&typeof s.json=="function")try{const l=await s.json();if(l&&typeof l=="object"){const c=l;return c._http_status=s.status,s.status>=500&&console.error("[preview-runtime] edge function 5xx",{action:e.action,projectId:e.projectId,status:s.status,body:c}),c}}catch{try{const l=await s.text();if(l){const c=JSON.parse(l);if(c&&typeof c=="object"){const u=c;return u._http_status=s.status,s.status>=500&&console.error("[preview-runtime] edge function 5xx",{action:e.action,projectId:e.projectId,status:s.status,body:u}),u}}}catch{}}const i=n.message||"Vercel preview runtime request failed",o=/agent_ws_failed/i.test(i);return{ok:!1,error:i,code:o?"agent_ws_failed":/failed to send a request|failed to fetch|404|503|edge function/i.test(i)?"vercel_preview_not_configured":"vercel_preview_request_failed"}}return r||{}}async function Pr(e){const{action:t,projectId:r}=e;if(!r||!IF.has(t))return Fk(e);if(Iw(r)&&(t==="start"||t==="restart"))return{ok:!1,code:"preview_warmup_deferred",error:"Warmup deferred until first build files land"};const s=(of.get(r)??Promise.resolve({})).catch(()=>({})).then(()=>Fk(e));of.set(r,s);try{return await s}finally{of.get(r)===s&&of.delete(r)}}const OF=Object.freeze(Object.defineProperty({__proto__:null,callVercelPreviewRuntime:Pr,shouldDeferPreviewWarmup:Iw},Symbol.toStringTag,{value:"Module"})),Qd=new Map,RF=4*60*1e3,DF=60*1e3;function MF(e){return Date.now()-e.startedAt<RF}function Jb(e){if(!e||Iw(e))return;const t=Qd.get(e);if(t&&MF(t))return;const r=window.setTimeout(()=>{const s=Qd.get(e);s&&!s.used&&console.info("[sandbox-prefire] wasted",{projectId:e,ageMs:Date.now()-s.startedAt})},DF),n={startedAt:Date.now(),wasteTimerId:r,used:!1};Qd.set(e,n),console.info("[sandbox-prefire] started",{projectId:e}),Pr({action:"start",projectId:e,files:[]}).catch(()=>{window.clearTimeout(r),Qd.delete(e)})}function Bk(e){if(!e)return;const t=Qd.get(e);if(!t||t.used)return;t.used=!0,window.clearTimeout(t.wasteTimerId);const r=Date.now()-t.startedAt;console.info("[sandbox-prefire] used",{projectId:e,ageMs:r})}const _d={buildMode:"ai-guided",target:"web",architecture:{frontend:"React",backend:"Node.js (NestJS)",database:"Supabase",auth:"Built-in Auth",mobileFramework:"none",mobileBackend:"supabase"},capabilities:{generateUI:!0,generateAPIs:!0,generateSchema:!0,generateWorkflows:!0,modifyExisting:!0,deleteRefactor:!1},aiBehavior:{creativity:50,strictness:50,explainDecisions:!1,showReasoning:!1},lifecycleStage:"prototype",focusArea:"general"};function $T(e){return[...e].map(t=>t.type==="folder"?{...t,children:$T(t.children||[])}:t).sort((t,r)=>t.type!==r.type?t.type==="folder"?-1:1:t.name.localeCompare(r.name))}function LF(e){const t=[];
1301for(const r of e){const n=(r.path||r.name).split("/").filter(Boolean);if(n.length===0)continue;let s=t;for(let i=0;i<n.length;i++){const o=n[i];if(i===n.length-1){const u=s.find(d=>d.type==="file"&&d.name===o);u?u.content=r.content||void 0:s.push({name:o,type:"file",content:r.content||void 0});continue}let c=s.find(u=>u.type==="folder"&&u.name===o);c||(c={name:o,type:"folder",children:[]},s.push(c)),c.children||(c.children=[]),s=c.children}}return $T(t)}async function Uk(e,t,r){try{const n=ET({projectName:t,projectDescription:r}).map(i=>({project_id:e,name:i.path.split("/").pop()||i.path,path:i.path,content:i.content,language:"md"})),s=Tw.map(i=>({project_id:e,name:i.path.split("/").pop()||i.path,path:i.path,content:i.content,language:i.language}));await G.from("project_files").upsert([...n,...s],{onConflict:"project_id,path"})}catch(n){console.warn("[useProject] Failed to seed project meta files:",n)}}function Co(e,t,r=new Map){const n=!!t&&e.user_id===t;return{id:e.id,name:e.name,description:e.description,thumbnail_url:e.thumbnail_url??null,created_at:e.created_at,updated_at:e.updated_at,first_build_at:e.first_build_at??null,ownerUserId:e.user_id,isOwner:n,currentUserRole:n?"owner":r.get(e.id)??null}}function $F(){const{user:e,emailVerified:t}=Us(),[r,n]=m.useState(null),[s,i]=m.useState([]),[o,l]=m.useState(!0),c=m.useCallback(async()=>{if(!e)return;const[{data:g},{data:y}]=await Promise.all([G.from("projects").select("*").order("updated_at",{ascending:!1}),G.from("project_collaborators").select("project_id, role").eq("user_id",e.id).not("accepted_at","is",null)]),b=new Map;for(const v of y||[])v.project_id&&(v.role==="editor"||v.role==="viewer")&&b.set(v.project_id,v.role);g&&i(g.map(v=>Co(v,e.id,b))),n(v=>v&&Co({id:v.id,name:v.name,description:v.description,thumbnail_url:v.thumbnail_url,created_at:v.created_at,updated_at:v.updated_at,first_build_at:v.first_build_at,user_id:v.ownerUserId},e.id,b))},[e]);m.useEffect(()=>{if(!e){l(!1);return}(async()=>{try{if(sessionStorage.getItem("sj_pending_new_project")==="1"||sessionStorage.getItem("sj_pending_prompt")){l(!1);return}}catch{}let y=null;try{y=new URLSearchParams(window.location.search).get("project")}catch{}if(y){const{data:v}=await G.from("projects").select("*").eq("id",y).maybeSingle();if(v){n(Co(v,e.id)),await c(),l(!1);return}}const{data:b}=await G.from("projects").select("*").eq("user_id",e.id).order("updated_at",{ascending:!1}).limit(1).single();if(b)n(Co(b,e.id));else{if(!t){n(null),await c(),l(!1);return}const{data:v}=await G.from("projects").insert({user_id:e.id,name:"My Project"}).select().single();v&&(n(Co(v,e.id)),await Promise.all([G.from("project_settings").insert({project_id:v.id}),Uk(v.id,v.name,v.description)]))}await c(),l(!1)})()},[e,t,c]);const u=m.useCallback(async(g,y)=>{if(!e)return null;if(!t)return W.error("Verify your email first",{description:"Open the verification link we sent before creating projects or starting AI builds."}),null;const{data:b}=await G.from("projects").insert({user_id:e.id,name:g,description:y||null}).select().single();if(b){await Promise.all([G.from("project_settings").insert({project_id:b.id}),Uk(b.id,b.name,b.description)]);const v=Co(b,e.id);return n(v),await c(),v}return null},[e,t,c]),d=m.useCallback(async(g,y)=>{await G.from("projects").update({name:y}).eq("id",g),(r==null?void 0:r.id)===g&&n(b=>b&&{...b,name:y}),await c()},[r,c]),p=m.useCallback(async g=>{if(await G.from("projects").delete().eq("id",g),(r==null?void 0:r.id)===g){const{data:y}=await G.from("projects").select("*").eq("user_id",e.id).order("updated_at",{ascending:!1}).limit(1).single();if(y)n(Co(y,(e==null?void 0:e.id)||null));else{const b=await u("My Project");b&&n(b)}}await c()},[r,e,c,u]),h=m.useCallback(async g=>{try{const v=new URL(window.location.href);v.searchParams.get("project")!==g&&(v.searchParams.set("project",g),window.history.replaceState({},"",v.toString()))}catch{}const y=s.find(v=>v.id===g);if(y){n(y),Jb(g),await G.from("projects").update({name:y.name}).eq("id",g);return}const{data:b}=await G.from("projects").select("*").eq("id",g).single();b&&(n(Co(b,(e==null?void 0:e.id)||null)),Jb(g),await c())},[s,e==null?void 0:e.id,c]),f=m.useCallback(async(g,y)=>{await G.from("projects").update({thumbnail_url:y}).eq("id",g),i(b=>b.map(v=>v.id===g?{...v,thumbnail_url:y}:v)),(r==null?void 0:r.id)===g&&n(b=>b&&{...b,thumbnail_url:y})},[r]),x=m.useCallback(async g=>{const y=new Date().toISOString(),{error:b}=await G.from("projects").update({first_build_at:y}).eq("id",g).is("first_build_at",null);if(b){console.warn("[useProject] markFirstBuildAt failed:",b);return}i(v=>v.map(k=>k.id===g&&!k.first_build_at?{...k,first_build_at:y}:k)),n(v=>v&&v.id===g&&!v.first_build_at?{...v,first_build_at:y}:v)},[]);return{project:r,projects:s,loading:o,setProject:n,createProject:u,renameProject:d,deleteProject:p,switchProject:h,saveThumbn
1301ail:f,markFirstBuildAt:x}}function FF(e){const[t,r]=m.useState(_d),[n,s]=m.useState(!1);m.useEffect(()=>{let o=!1;return s(!1),r(_d),e?((async()=>{const{data:c}=await G.from("project_settings").select("*").eq("project_id",e).single();o||(c?r({buildMode:c.build_mode||"ai-guided",target:c.target||"web",architecture:c.architecture||_d.architecture,capabilities:c.capabilities||_d.capabilities,aiBehavior:c.ai_behavior||_d.aiBehavior,lifecycleStage:c.lifecycle_stage||"prototype",focusArea:c.focus_area||"general"}):await G.from("project_settings").insert({project_id:e}),o||s(!0))})(),()=>{o=!0}):(s(!0),()=>{o=!0})},[e]);const i=m.useCallback(async o=>{e&&r(l=>{const c={...l,...o};return G.from("project_settings").update({build_mode:c.buildMode,target:c.target,architecture:c.architecture,capabilities:c.capabilities,ai_behavior:c.aiBehavior,lifecycle_stage:c.lifecycleStage,focus_area:c.focusArea}).eq("project_id",e).then(),c})},[e]);return{settings:t,saveSettings:i,loaded:n}}function BF(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1),i=m.useRef([]),o=m.useRef(null);m.useEffect(()=>{let h=!1;const f=o.current;if(o.current=e,!e){r([]),i.current=[],s(!0);return}const x=f!==null&&f!==e;return x&&(r([]),i.current=[]),s(!1),(async()=>{const{data:y}=await G.from("project_messages").select("*").eq("project_id",e).order("created_at",{ascending:!0});if(!h){if(y){const b=y.map(v=>({id:v.id,role:v.role,content:v.content,createdAt:v.created_at?new Date(v.created_at).getTime():Date.now()}));r(v=>{if(x)return i.current=b,b;const k=new Set(b.map(w=>w.id)),N=v.filter(w=>!k.has(w.id)),j=[...b,...N];return i.current=j,j})}s(!0)}})(),()=>{h=!0}},[e]),m.useEffect(()=>{if(!e)return;const h=G.channel(`project_messages:${e}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"project_messages",filter:`project_id=eq.${e}`},f=>{const x=f.new;r(g=>{if(g.some(b=>b.id===x.id))return g;const y=[...g,{id:x.id,role:x.role,content:x.content}];return i.current=y,y})}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"project_messages",filter:`project_id=eq.${e}`},f=>{const x=f.new;r(g=>{const y=g.map(b=>b.id===x.id?{...b,content:x.content}:b);return i.current=y,y})}).subscribe();return()=>{G.removeChannel(h)}},[e]);const l=m.useRef(0),c=m.useCallback(async(h,f)=>{const x=`${Date.now()}-${++l.current}`,g=Date.now();if(r(y=>{const b=[...y,{id:x,role:h,content:f,createdAt:g}];return i.current=b,b}),e){const{data:y,error:b}=await G.from("project_messages").insert({project_id:e,role:h,content:f}).select().single();b?(console.error("[useProjectMessages] Failed to persist message:",{role:h,error:b}),W.error("Message not saved",{description:b.message.includes("row-level security")?"Permission denied — try refreshing the page.":`${b.message} — your message may disappear on refresh.`})):y&&r(v=>{const k=v.map(N=>N.id===x?{...N,id:y.id}:N);return i.current=k,k})}},[e]),u=m.useCallback(async h=>{r(f=>{const x=f[f.length-1];if((x==null?void 0:x.role)==="ai"){const y=f.map((b,v)=>v===f.length-1?{...b,content:h}:b);return i.current=y,y}const g=[...f,{id:Date.now().toString(),role:"ai",content:h,createdAt:Date.now()}];return i.current=g,g})},[]),d=m.useCallback(h=>{r(f=>{const x=f[f.length-1];if(!x||x.role!=="ai")return f;const g=f.map((y,b)=>b===f.length-1?{...y,...h}:y);return i.current=g,g})},[]),p=m.useCallback(async h=>{if(!e)return;const f=i.current,x=f[f.length-1],g=(b,v)=>{console.error(`[useProjectMessages] saveLastAiMessage ${b} failed:`,v),W.error("Reply not saved",{description:v.message.includes("row-level security")?"Permission denied — try refreshing the page.":`${v.message} — reply may disappear on refresh.`})},y=async()=>{const{data:b,error:v}=await G.from("project_messages").insert({project_id:e,role:"ai",content:h}).select().single();return v?(g("insert",v),null):b};if((x==null?void 0:x.role)==="ai")if(/^[0-9a-f]{8}-/.test(x.id)){const{error:v}=await G.from("project_messages").update({content:h}).eq("id",x.id);v&&g("update",v)}else{const v=await y();v&&r(k=>{const N=k.map(j=>j.id===x.id?{...j,id:v.id,content:h}:j);return i.current=N,N})}else{const b=await y();b&&r(v=>{const k=[...v,{id:b.id,role:"ai",content:h}];return i.current=k,k})}},[e,r]);return{messages:t,setMessages:r,addMessage:c,updateLastAiMessage:u,saveLastAiMessage:p,setLastAiMessageMeta:d,loaded:n}}function UF(e){const t=m.useCallback(async c=>{!e||c.length===0||await G.from("project_files").delete().eq("project_id",e).in("path",c)},[e]),r=m.useCallback(async c=>{if(!e||c.length===0)return;const u=c.map(d=>({project_id:e,name:d.name,path:d.path,content:d.content||null,language:d.language||null}));await G.from("project_files").upsert(u,{onConflict:"project_id,path"})},[e]),n=m.useCallback(async c=>{if(!e||(await G.from("project_apis").delete().eq("project_id",e),!Array.isArray(c)||c.length===0))return;const u=c.map(d=>({project_id:e,method:d.method,path:d.path,description:d.description||null,parameters:d.params||[],source_file:d.filename||null}));await G.from("project_apis").insert(u)},[e]),s=m.useCallback(async c=>{if(!e||(await G.from("project_schemas").delete().eq("project_id",e),!c||!Array.isArray(c.tables)||c.tables.length===0))return;const u=Array.isArray(c.relationships)?c.relationships:[],d=c.tables.map(p=>({project_id:e,table_name:p.name,columns:p.columns,relationships:u.filter(h=>h.fromTable===p.name||h.toTable===p.name),source_file:p.filename||null}));await G.from("project_schemas").insert(d)},[e]),i=m.useCallback(async()=>
1301{if(!e)return[];const{data:c}=await G.from("project_files").select("*").eq("project_id",e).order("path");return c?LF(c.map(u=>({name:u.name,path:u.path,content:u.content}))):[]},[e]),o=m.useCallback(async()=>{if(!e)return[];const{data:c}=await G.from("project_apis").select("*").eq("project_id",e);return c?c.map(u=>({id:u.id,method:u.method,path:u.path,description:u.description||"",params:u.parameters||[],filename:u.source_file||""})):[]},[e]),l=m.useCallback(async()=>{if(!e)return{tables:[],relationships:[]};const{data:c}=await G.from("project_schemas").select("*").eq("project_id",e);if(!c||c.length===0)return{tables:[],relationships:[]};const u=c.map((p,h)=>({id:p.id,name:p.table_name,columns:p.columns||[],filename:p.source_file||""})),d=c.flatMap(p=>p.relationships||[]);return{tables:u,relationships:d}},[e]);return{saveFiles:r,deleteFiles:t,saveApis:n,saveSchema:s,loadFiles:i,loadApis:o,loadSchema:l}}function FT(e,t=""){return e.flatMap(r=>{const n=t?`${t}/${r.name}`:r.name;if(r.type==="file"&&r.content){const s=n.includes(".")&&n.split(".").pop()||"text";return[{filename:n,language:s==="htm"?"html":s,content:r.content}]}return r.type==="folder"&&r.children?FT(r.children,n):[]})}const Ow=m.createContext(null);function zF({children:e}){const{project:t,projects:r,loading:n,createProject:s,renameProject:i,deleteProject:o,switchProject:l,saveThumbnail:c,markFirstBuildAt:u}=$F(),d=(t==null?void 0:t.id)||null,p=!!(t!=null&&t.first_build_at);m.useEffect(()=>{at.current=p},[p]);const h=m.useCallback(()=>{d&&u(d)},[d,u]),[f,x]=m.useState(null),g=f!==null,[y,b]=m.useState(null),[v,k]=m.useState(null),N=m.useCallback(()=>{x(Ye=>Ye??Date.now())},[]),{settings:j,saveSettings:w,loaded:S}=FF(d),{messages:T,addMessage:C,updateLastAiMessage:A,saveLastAiMessage:P,setLastAiMessageMeta:E,loaded:_}=BF(d),{saveFiles:I,deleteFiles:D,saveApis:M,saveSchema:B,loadFiles:$,loadApis:K,loadSchema:R}=UF(d),[Y,Z]=m.useState("app-builder"),[O,ne]=m.useState([]),[oe,he]=m.useState([]),[ae,ve]=m.useState(null),[re,se]=m.useState(!1),[le,te]=m.useState(!1);m.useEffect(()=>{if(!d)return;try{if(sessionStorage.getItem(`sj-defer-warmup:${d}`))return}catch{}if(re)return;const Ye=`sj-warmed:${d}`,pt=Number(sessionStorage.getItem(`${Ye}:at`)||0),Xe=4*60*1e3;pt&&Date.now()-pt<Xe||(sessionStorage.setItem(Ye,"1"),sessionStorage.setItem(`${Ye}:at`,String(Date.now())),(async()=>{try{const St=await Pr({action:"health",projectId:d});if((St==null?void 0:St.kind)==="healthy"&&(St!=null&&St.port_open))return;if((St==null?void 0:St.kind)==="vite_dead"||St!=null&&St.sandbox_alive&&(St==null?void 0:St.port_open)===!1){console.info("[studio] Vite down on reopen — silent restart"),await Pr({action:"restart",projectId:d,files:[]});return}((St==null?void 0:St.kind)==="sandbox_missing"||(St==null?void 0:St.kind)==="no_sandbox"||(St==null?void 0:St.sandbox_alive)===!1)&&(console.info("[studio] sandbox missing on reopen — silent respawn"),await Pr({action:"restart",projectId:d,files:[]}))}catch{}})(),G.functions.invoke("chat",{body:{action:"warmup"}}).catch(()=>null))},[d,re]);const[We,Me]=m.useState(null),[Te,Ee]=m.useState([]),[st,xt]=m.useState(null),[on,Yt]=m.useState(!1),[mt,ln]=m.useState(!1),at=m.useRef(!1),gt=m.useRef(null);m.useEffect(()=>{gt.current=st},[st]);const $t=m.useCallback(Ye=>{Ee(pt=>{const Xe=pt[pt.length-1];if(Xe&&Xe.label===Ye)return pt;const St=Date.now(),Mn=pt.map(Ir=>({...Ir,status:"done"}));return Mn.push({id:`${St}-${Math.random().toString(36).slice(2,7)}`,label:Ye,status:"running",agent:gt.current||void 0,startedAt:St}),Mn.length>60?Mn.slice(-60):Mn})},[]);m.useEffect(()=>{if(re)k(null),Yt(!1),at.current&&ln(!0);else{Me(null),Ee(pt=>pt.some(Xe=>Xe.status==="running")?pt.map(Xe=>Xe.status==="running"?{...Xe,status:"done"}:Xe):pt),xt(null),k(Date.now());const Ye=window.setTimeout(()=>ln(!1),500);return()=>window.clearTimeout(Ye)}},[re]),m.useEffect(()=>{if(!mt||re)return;const Ye=window.setTimeout(()=>ln(!1),9e4);return()=>window.clearTimeout(Ye)},[mt,re]),m.useEffect(()=>{if(p||!d||!v||!f)return;const Ye=Math.max(v,f),pt=3e3,Xe=Ye-pt;if(y&&y>Xe)return;const St=Date.now()-Ye,Mn=Math.max(0,pt-St),Ir=window.setTimeout(()=>{(!y||y<=Xe)&&h()},Mn);return()=>window.clearTimeout(Ir)},[p,d,v,f,y,h]),m.useEffect(()=>{x(null),b(null),k(null),je([]),Ee([]),U([]),se(!1),ln(!1)},[d]);const[ue,je]=m.useState([]),ct=m.useCallback(Ye=>{const pt=Ye.trim();pt&&je(Xe=>[...Xe,pt])},[]),it=m.useCallback(Ye=>{je(pt=>pt.filter((Xe,St)=>St!==Ye))},[]),q=m.useCallback(()=>{let Ye=null;return je(pt=>pt.length===0?pt:(Ye=pt[0],pt.slice(1))),Ye},[]),[Nt,U]=m.useState([]),Ne=m.useCallback(Ye=>{U(pt=>{const Xe=Ye.trim();if(!Xe||pt[pt.length-1]===Xe)return pt;const St=[...pt,Xe];return St.length>50?St.slice(-50):St}),b(Date.now())},[]),Ft=m.useCallback(()=>U([]),[]),[Zt,Ke]=m.useState([]),[ie,we]=m.useState(()=>{try{return localStorage.getItem("sj_useApplyOnAccept")==="1"}catch{return!1}});m.useEffect(()=>{try{localStorage.setItem("sj_useApplyOnAccept",ie?"1":"0")}catch{}},[ie]);const Je=m.useRef(0),ot=m.useCallback(Ye=>{Ke(pt=>{const Xe=`pc-${Date.now()}-${++Je.current}`;return[...pt.filter(Mn=>Mn.path!==Ye.path),{...Ye,id:Xe,timestamp:Date.now()}]})},[]),V=m.useRef(()=>{}),ye=m.useRef(()=>{}),me=m.useRef(()=>{}),_e=m.useRef(()=>{}),dt=m.useCallback(Ye=>V.current(Ye),[]),kt=m.useCallback(Ye=>ye.current(Ye),[]),wn=m.useCallback(()=>me.current(),[]),kn=m.useCallback(()=>_e.current(),[]),Ae=m.useCallback((Ye,pt)=>{const Xe=gr=>gr.map(vr=>({...vr,children:vr.children?Xe(vr.children):void 0})),St=Xe(Ye),Mn=(gr,vr)=>{let ws=St;for(let Jr=0;Jr<gr.length-1;Jr++){const cr=gr[Jr];let qa=ws.find(Oc=>Oc.name===cr&&Oc.type==="folder");qa||(qa={name:cr,type:"folder",children:[]},ws.push(qa)),qa.children||(qa.children=[]),ws=qa.children}const Ps=gr[gr.length-1],ca=ws.find(Jr=>Jr.name===Ps&&Jr.type==="file");ca?ca.content=vr:ws.push({name:Ps,type:"file",content:vr})},Ir=gr=>{const vr=(ws,Ps)=>{if(Ps===gr.length-1){const Jr=ws.findIndex(cr=>cr.name===gr[Ps]&&cr.type==="file");Jr>=0&&ws.splice(Jr,1);return}const ca=ws.find(Jr=>Jr.name===gr[Ps]&&Jr.type==="folder");ca!=null&&ca.children&&vr(ca.children,Ps+1)};vr(St,0)};
1301for(const gr of pt){const vr=gr.path.split("/").filter(Boolean);vr.length!==0&&(gr.kind==="delete"?Ir(vr):Mn(vr,gr.newContent))}return St},[]);m.useEffect(()=>{V.current=Ye=>{const pt=Zt.find(Xe=>Xe.id===Ye);pt&&(he(Xe=>Ae(Xe,[pt])),pt.kind==="delete"?D([pt.path]):I([{name:pt.path.split("/").pop()||pt.path,path:pt.path,content:pt.newContent}]),Ke(Xe=>Xe.filter(St=>St.id!==Ye)))},ye.current=Ye=>{Ke(pt=>pt.filter(Xe=>Xe.id!==Ye))},me.current=()=>{if(Zt.length===0)return;he(Xe=>Ae(Xe,Zt));const Ye=Zt.filter(Xe=>Xe.kind==="delete").map(Xe=>Xe.path),pt=Zt.filter(Xe=>Xe.kind!=="delete");pt.length>0&&I(pt.map(Xe=>({name:Xe.path.split("/").pop()||Xe.path,path:Xe.path,content:Xe.newContent}))),Ye.length>0&&D(Ye),Ke([])},_e.current=()=>Ke([])},[Zt,I,D,Ae]);const[rt,fe]=m.useState("preview"),[lt,yt]=m.useState(null),[zt,Fe]=m.useState(null),[qt,fr]=m.useState(0),[Jt,_t]=m.useState([]),[z,ee]=m.useState(null),[de,ge]=m.useState(0),[Se,Ie]=m.useState([]),[De,Ce]=m.useState({tables:[],relationships:[]}),xn=m.useRef(null),et=m.useRef(null),[wt,At]=m.useState(null),[Fn,mr]=m.useState(null),[ts,zi]=m.useState(null),[Tc,Qs]=m.useState(!1),[qr,xd]=m.useState(null),[vs,fi]=m.useState([]),gl=m.useCallback((Ye,pt)=>{fi(Xe=>[...Xe,{toolId:Ye,timestamp:Date.now(),context:pt}])},[]),[mi,xl]=m.useState(Rk),[Er,Ec]=m.useState(null);m.useEffect(()=>{if(!d||et.current===d)return;et.current=d,ne([]),ve(null),se(!1),fe("preview"),yt(null),ge(0),At(null),mr(null),zi(null),Qs(!1),xd(null),xl(Rk()),Ec(null),_t([]),Fe(null),ee(null),Ie([]),Ce({tables:[],relationships:[]}),he([]),fr(0),(async()=>{if(et.current!==d)return;const[pt,Xe,St]=await Promise.all([$(),K(),R()]);if(et.current!==d)return;const{tree:Mn,created:Ir}=Z6(pt,{projectName:t==null?void 0:t.name,projectDescription:t==null?void 0:t.description}),{tree:gr,repaired:vr}=TF(Mn),ws=vr.length>0?gr:Mn;he(ws),Ie(Xe),Ce(St),Ir.length>0&&I(Ir.map(cr=>({name:cr.path.split("/").pop()||cr.path,path:cr.path,content:cr.content,language:"md"}))),vr.length>0&&d&&(console.info("[studio] legacy main.tsx basename repair",{projectId:d,paths:vr.map(cr=>cr.path)}),I(vr.map(cr=>({name:cr.path.split("/").pop()||cr.path,path:cr.path,content:cr.content,language:cr.path.endsWith(".tsx")?"tsx":"jsx"}))),Pr({action:"apply",projectId:d,files:vr}).catch(cr=>console.warn("[studio] legacy repair apply failed:",cr==null?void 0:cr.message)));const Ps=FT(ws),ca=Ps.filter(cr=>["html","tsx","jsx","css"].includes(cr.language)),Jr=id(ca);_t(Jr),fr(Ps.length),Jr.length>0?(ee(Jr[0].id),Fe(Jr[0].html)):(ee(null),Fe(null),_t([]),Ps.length===0&&fr(0))})()},[d,t==null?void 0:t.name,t==null?void 0:t.description,$,K,R,I]);const Hs=m.useCallback(Ye=>w({buildMode:Ye}),[w]),yl=m.useCallback(Ye=>w({target:Ye}),[w]),Ic=m.useCallback(Ye=>w({architecture:Ye}),[w]),Ue=m.useCallback(Ye=>w({capabilities:Ye}),[w]),Bt=m.useCallback(Ye=>w({aiBehavior:Ye}),[w]),ut=m.useCallback(Ye=>w({lifecycleStage:Ye}),[w]),cn=m.useCallback(Ye=>w({focusArea:Ye}),[w]),Qn=m.useCallback((Ye,pt)=>{C(Ye,pt)},[C]);return a.jsx(Ow.Provider,{value:{project:t,projects:r,projectLoading:n,firstBuildDone:p,previewReady:g,markFirstBuildDone:h,notifyVitePreviewReady:N,queuedPrompts:ue,enqueuePrompt:ct,removeQueuedPrompt:it,dequeueNextPrompt:q,createProject:s,renameProject:i,deleteProject:o,switchProject:l,saveThumbnail:c,mode:Y,setMode:Z,target:j.target,setTarget:yl,messages:T,addMessage:Qn,updateLastAiMessage:A,saveLastAiMessage:P,setLastAiMessageMeta:E,planSteps:O,setPlanSteps:ne,files:oe,setFiles:he,selectedFile:ae,setSelectedFile:ve,isBuilding:re,setIsBuilding:se,isMultiAgentRun:le,setIsMultiAgentRun:te,liveStatus:We,setLiveStatus:Me,toolCallHistory:Te,pushToolCall:$t,currentAgent:st,setCurrentAgent:xt,buildHalted:on,setBuildHalted:Yt,previewSyncing:mt,setPreviewSyncing:ln,activeWorkspaceTab:rt,setActiveWorkspaceTab:fe,activeModel:lt,setActiveModel:yt,previewHtml:zt,setPreviewHtml:Fe,lastBuildErrors:Nt,setLastBuildErrors:U,appendBuildError:Ne,clearBuildErrors:Ft,pendingFileChanges:Zt,addPendingChange:ot,acceptPendingChange:dt,rejectPendingChange:kt,acceptAllPendingChanges:wn,rejectAllPendingChanges:kn,useApplyOnAccept:ie,setUseApplyOnAccept:we,generatedBlockCount:qt,setGeneratedBlockCount:fr,generatedPages:Jt,setGeneratedPages:_t,activePageId:z,setActivePageId:ee,buildProgress:de,setBuildProgress:ge,apis:Se,setApis:Ie,schema:De,setSchema:Ce,buildMode:j.buildMode,setBuildMode:Hs,architecture:j.architecture,setArchitecture:Ic,capabilities:j.capabilities,setCapabilities:Ue,aiBehavior:j.aiBehavior,setAIBehavior:
vendor: 9,255 bytes, line 1301
1301Bt,lifecycleStage:j.lifecycleStage,setLifecycleStage:ut,focusArea:j.focusArea,setFocusArea:cn,saveProjectFiles:I,saveProjectApis:M,saveProjectSchema:B,triggerBuildRef:xn,copilotData:wt,setCopilotData:At,copilotSql:Fn,setCopilotSql:mr,copilotError:ts,setCopilotError:zi,copilotLoading:Tc,setCopilotLoading:Qs,currentWorkflow:qr,setCurrentWorkflow:xd,toolUsageHistory:vs,addToolUsage:gl,orchestration:mi,setOrchestration:xl,currentAgentRunId:Er,setCurrentAgentRunId:Ec},children:e})}function gn(){const e=m.useContext(Ow);if(!e)throw new Error("useStudio must be used within StudioProvider");return e}function il(){return m.useContext(Ow)}function Xb(e,[t,r]){return Math.min(r,Math.max(t,e))}function qF(e,t){return m.useReducer((r,n)=>t[r][n]??r,e)}var Rw="ScrollArea",[BT,vve]=sl(Rw),[HF,Ba]=BT(Rw),UT=m.forwardRef((e,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:s,scrollHideDelay:i=600,...o}=e,[l,c]=m.useState(null),[u,d]=m.useState(null),[p,h]=m.useState(null),[f,x]=m.useState(null),[g,y]=m.useState(null),[b,v]=m.useState(0),[k,N]=m.useState(0),[j,w]=m.useState(!1),[S,T]=m.useState(!1),C=Tr(t,P=>c(P)),A=fw(s);return a.jsx(HF,{scope:r,type:n,dir:A,scrollHideDelay:i,scrollArea:l,viewport:u,onViewportChange:d,content:p,onContentChange:h,scrollbarX:f,onScrollbarXChange:x,scrollbarXEnabled:j,onScrollbarXEnabledChange:w,scrollbarY:g,onScrollbarYChange:y,scrollbarYEnabled:S,onScrollbarYEnabledChange:T,onCornerWidthChange:v,onCornerHeightChange:N,children:a.jsx(En.div,{dir:A,...o,ref:C,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":k+"px",...e.style}})})});UT.displayName=Rw;var zT="ScrollAreaViewport",qT=m.forwardRef((e,t)=>{const{__scopeScrollArea:r,children:n,nonce:s,...i}=e,o=Ba(zT,r),l=m.useRef(null),c=Tr(t,l,o.onViewportChange);return a.jsxs(a.Fragment,{children:[a.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),a.jsx(En.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...e.style},children:a.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});qT.displayName=zT;var $i="ScrollAreaScrollbar",Dw=m.forwardRef((e,t)=>{const{forceMount:r,...n}=e,s=Ba($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:o}=s,l=e.orientation==="horizontal";return m.useEffect(()=>(l?i(!0):o(!0),()=>{l?i(!1):o(!1)}),[l,i,o]),s.type==="hover"?a.jsx(WF,{...n,ref:t,forceMount:r}):s.type==="scroll"?a.jsx(VF,{...n,ref:t,forceMount:r}):s.type==="auto"?a.jsx(HT,{...n,ref:t,forceMount:r}):s.type==="always"?a.jsx(Mw,{...n,ref:t}):null});Dw.displayName=$i;var WF=m.forwardRef((e,t)=>{const{forceMount:r,...n}=e,s=Ba($i,e.__scopeScrollArea),[i,o]=m.useState(!1);return m.useEffect(()=>{const l=s.scrollArea;let c=0;if(l){const u=()=>{window.clearTimeout(c),o(!0)},d=()=>{c=window.setTimeout(()=>o(!1),s.scrollHideDelay)};return l.addEventListener("pointerenter",u),l.addEventListener("pointerleave",d),()=>{window.clearTimeout(c),l.removeEventListener("pointerenter",u),l.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),a.jsx(Fa,{present:r||i,children:a.jsx(HT,{"data-state":i?"visible":"hidden",...n,ref:t})})}),VF=m.forwardRef((e,t)=>{const{forceMount:r,...n}=e,s=Ba($i,e.__scopeScrollArea),i=e.orientation==="horizontal",o=Xg(()=>c("SCROLL_END"),100),[l,c]=qF("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return m.useEffect(()=>{if(l==="idle"){const u=window.setTimeout(()=>c("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(u)}},[l,s.scrollHideDelay,c]),m.useEffect(()=>{const u=s.viewport,d=i?"scrollLeft":"scrollTop";if(u){let p=u[d];const h=()=>{const f=u[d];p!==f&&(c("SCROLL"),o()),p=f};return u.addEventListener("scroll",h),()=>u.removeEventListener("scroll",h)}},[s.viewport,i,c,o]),a.jsx(Fa,{present:r||l!=="hidden",children:a.jsx(Mw,{"data-state":l==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:vn(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:vn(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),HT=m.forwardRef((e,t)=>{const r=Ba($i,e.__scopeScrollArea),{forceMount:n,...s}=e,[i,o]=m.useState(!1),l=e.orientation==="horizontal",c=Xg(()=>{if(r.viewport){const u=r.viewport.offsetWidth<r.viewport.scrollWidth,d=r.viewport.offsetHeight<r.viewport.scrollHeight;o(l?u:d)}},10);return Su(r.viewport,c),Su(r.content,c),a.jsx(Fa,{present:n||i,children:a.jsx(Mw,{"data-state":i?"visible":"hidden",...s,ref:t})})}),Mw=m.forwardRef((e,t)=>{const{orientation:r="vertical",...n}=e,s=Ba($i,e.__scopeScrollArea),i=m.useRef(null),o=m.useRef(0),[l,c]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=YT(l.viewport,l.content),d={...n,sizes:l,onSizesChange:c,hasThumb:u>0&&u<1,onThumbChange:h=>i.current=h,onThumbPointerUp:()=>o.current=0,onThumbPointerDown:h=>o.current=h};function p(h,f){return ZF(h,o.current,l,f)}return r==="horizontal"?a.jsx(GF,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&i.current){const h=s.viewport.scrollLeft,f=zk(h,l,s.dir);i.current.style.transform=`translate3d(${f}px, 0, 0)`}},onWheelScroll:h=>{s.viewport&&(s.viewport.scrollLeft=h)},onDragScroll:h=>{s.viewport&&(s.viewport.scrollLeft=p(h,s.dir))}}):r==="vertical"?a.jsx(KF,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&i.current){const h=s.viewport.scrollTop,f=zk(h,l);i.current.style.transform=`translate3d(0, ${f}px, 0)`}},onWheelScroll:h=>{s.viewport&&(s.viewport.scrollTop=h)},onDragScroll:h=>{s.viewport&&(s.viewport.scrollTop=p(h))}}):null}),GF=m.forwardRef((e,t)=>{const{sizes:r,onSizesChange:n,...s}=e,i=Ba($i,e.__scopeScrollArea),[o,l]=m.useState(),c=m.useRef(null),u=Tr(t,c,i.onScrollbarXChange);return m.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),a.jsx(VT,{"data-orientation":"horizontal",...s,ref:u,sizes:r,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Jg(r)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,p)=>{if(i.viewport){const h=i.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),XT(h,p)&&d.preventDefault()}},onResize:()=>{c.current&&i.viewport&&o&&n({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:wm(o.paddingLeft),paddingEnd:wm(o.paddingRight)}})}})}),KF=m.forwardRef((e,t)=>{const{sizes:r,onSizesChange:n,...s}=e,i=Ba($i,e.__scopeScrollArea),[o,l]=m.useState(),c=m.useRef(null),u=Tr(t,c,i.onScrollbarYChange);return m.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),a.jsx(VT,{"data-orientation":"vertical",...s,ref:u,sizes:r,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Jg(r)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,p)=>{if(i.viewport){const h=i.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),XT(h,p)&&d.preventDefault()}},onResize:()=>{c.current&&i.viewport&&o&&n({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:wm(o.paddingTop),paddingEnd:wm(o.paddingBottom)}})}})}),[YF,WT]=BT($i),VT=m.forwardRef((e,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:s,onThumbChange:i,onThumbPointerUp:o,onThumbPointerDown:l,onThumbPositionChange:c,onDragScroll:u,onWheelScroll:d,onResize:p,...h}=e,f=Ba($i,r),[x,g]=m.useState(null),y=Tr(t,C=>g(C)),b=m.useRef(null),v=m.useRef(""),k=f.viewport,N=n.content-n.viewport,j=Uo(d),w=Uo(c),S=Xg(p,10);function T(C){if(b.current){const A=C.clientX-b.current.left,P=C.clientY-b.current.top;u({x:A,y:P})}}return m.useEffect(()=>{const C=A=>{const P=A.target;(x==null?void 0:x.contains(P))&&j(A,N)};return document.addEventListener("wheel",C,{passive:!1}),()=>document.removeEventListener("wheel",C,{passive:!1})},[k,x,N,j]),m.useEffect(w,[n,w]),Su(x,S),Su(f.content,S),a.jsx(YF,{scope:r,scrollbar:x,hasThumb:s,onThumbChange:Uo(i),onThumbPointerUp:Uo(o),onThumbPositionChange:w,onThumbPointerDown:Uo(l),children:a.jsx(En.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:vn(e.onPointerDown,C=>{C.button===0&&(C.target.setPointerCapture(C.pointerId),b.current=x.getBoundingClientRect(),v.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",f.viewport&&(f.viewport.style.scrollBehavior="auto"),T(C))}),onPointerMove:vn(e.onPointerMove,T),onPointerUp:vn(e.onPointerUp,C=>{const A=C.target;A.hasPointerCapture(C.pointerId)&&A.releasePointerCapture(C.pointerId),document.body.style.webkitUserSelect=v.current,f.viewport&&(f.viewport.style.scrollBehavior=""),b.current=null})})})}),vm="ScrollAreaThumb",GT=m.forwardRef((e,t)=>
1301{const{forceMount:r,...n}=e,s=WT(vm,e.__scopeScrollArea);return a.jsx(Fa,{present:r||s.hasThumb,children:a.jsx(JF,{ref:t,...n})})}),JF=m.forwardRef((e,t)=>{const{__scopeScrollArea:r,style:n,...s}=e,i=Ba(vm,r),o=WT(vm,r),{onThumbPositionChange:l}=o,c=Tr(t,p=>o.onThumbChange(p)),u=m.useRef(void 0),d=Xg(()=>{u.current&&(u.current(),u.current=void 0)},100);return m.useEffect(()=>{const p=i.viewport;if(p){const h=()=>{if(d(),!u.current){const f=QF(p,l);u.current=f,l()}};return l(),p.addEventListener("scroll",h),()=>p.removeEventListener("scroll",h)}},[i.viewport,d,l]),a.jsx(En.div,{"data-state":o.hasThumb?"visible":"hidden",...s,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:vn(e.onPointerDownCapture,p=>{const f=p.target.getBoundingClientRect(),x=p.clientX-f.left,g=p.clientY-f.top;o.onThumbPointerDown({x,y:g})}),onPointerUp:vn(e.onPointerUp,o.onThumbPointerUp)})});GT.displayName=vm;var Lw="ScrollAreaCorner",KT=m.forwardRef((e,t)=>{const r=Ba(Lw,e.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?a.jsx(XF,{...e,ref:t}):null});KT.displayName=Lw;var XF=m.forwardRef((e,t)=>{const{__scopeScrollArea:r,...n}=e,s=Ba(Lw,r),[i,o]=m.useState(0),[l,c]=m.useState(0),u=!!(i&&l);return Su(s.scrollbarX,()=>{var p;const d=((p=s.scrollbarX)==null?void 0:p.offsetHeight)||0;s.onCornerHeightChange(d),c(d)}),Su(s.scrollbarY,()=>{var p;const d=((p=s.scrollbarY)==null?void 0:p.offsetWidth)||0;s.onCornerWidthChange(d),o(d)}),u?a.jsx(En.div,{...n,ref:t,style:{width:i,height:l,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function wm(e){return e?parseInt(e,10):0}function YT(e,t){const r=e/t;return isNaN(r)?0:r}function Jg(e){const t=YT(e.viewport,e.content),r=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,n=(e.scrollbar.size-r)*t;return Math.max(n,18)}function ZF(e,t,r,n="ltr"){const s=Jg(r),i=s/2,o=t||i,l=s-o,c=r.scrollbar.paddingStart+o,u=r.scrollbar.size-r.scrollbar.paddingEnd-l,d=r.content-r.viewport,p=n==="ltr"?[0,d]:[d*-1,0];return JT([c,u],p)(e)}function zk(e,t,r="ltr"){const n=Jg(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-s,o=t.content-t.viewport,l=i-n,c=r==="ltr"?[0,o]:[o*-1,0],u=Xb(e,c);return JT([0,o],[0,l])(u)}function JT(e,t){return r=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(e[1]-e[0]);return t[0]+n*(r-e[0])}}function XT(e,t){return e>0&&e<t}var QF=(e,t=()=>{})=>{let r={left:e.scrollLeft,top:e.scrollTop},n=0;return function s(){const i={left:e.scrollLeft,top:e.scrollTop},o=r.left!==i.left,l=r.top!==i.top;(o||l)&&t(),r=i,n=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(n)};function Xg(e,t){const r=Uo(e),n=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(n.current),[]),m.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,t)},[r,t])}function Su(e,t){const r=Uo(t);Ii(()=>{let n=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return s.observe(e),()=>{window.cancelAnimationFrame(n),s.unobserve(e)}}},[e,r])}var ZT=UT,eB=qT,tB=KT;const $r=m.forwardRef(({className:e,children:t,...r},n)=>a.jsxs(ZT,{ref:n,className:L("relative overflow-hidden",e),...r,children:[a.jsx(eB,{className:"h-full w-full rounded-[inherit]",children:t}),a.jsx(QT,{}),a.jsx(tB,{})]}));$r.displayName=ZT.displayName;const QT=m.forwardRef(({className:e,orientation:t="vertical",...r},n)=>a.jsx(Dw,{ref:n,orientation:t,className:L("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...r,children:a.jsx(GT,{className:"relative flex-1 rounded-full bg-border"})}));QT.displayName=Dw.displayName;function e5(){const[e,t]=m.useState(0),r=m.useRef(Date.now());m.useEffect(()=>{const i=setInterval(()=>{t(Math.floor((Date.now()-r.current)/1e3))},1e3);return()=>clearInterval(i)},[]);const n=Math.floor(e/60),s=e%60;return a.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-mono text-muted-foreground",children:[a.jsx(Lr,{className:"w-3 h-3"}),n>0?`${n}m ${s.toString().padStart(2,"0")}s`:`${s}s`]})}function t5(){const[e,t]=m.useState(15);return m.useEffect(()=>{const r=setInterval(()=>{t(n=>{const s=Math.max(.3,(90-n)*.04);return Math.min(n+s,92)})},600);return()=>clearInterval(r)},[]),a.jsxs("div",{className:"mt-2.5 ml-8 space-y-1.5",children:[a.jsx(qL,{value:e,className:"h-1.5 bg-primary/10"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground animate-pulse",children:"Processing…"}),a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground
1301/60",children:[Math.round(e),"%"]})]})]})}function n5(){const[e,t]=m.useState("");return m.useEffect(()=>{const r=setInterval(()=>{t(n=>n.length>=3?"":n+".")},500);return()=>clearInterval(r)},[]),a.jsx("span",{className:"text-muted-foreground",children:e})}const Zb={pending:{icon:U_,className:"text-muted-foreground",label:"Pending"},running:{icon:ze,className:"text-primary animate-spin",label:"Running"},done:{icon:mn,className:"text-success",label:"Done"},error:{icon:is,className:"text-destructive",label:"Error"}};function nB({result:e}){const[t,r]=m.useState(!1),n=e.status==="success",s=e.sql.length>80?e.sql.slice(0,80)+"...":e.sql;return a.jsxs("div",{className:L("rounded-md border p-2 cursor-pointer transition-colors text-xs",n?"border-success/30 bg-success/5 hover:bg-success/10":"border-destructive/30 bg-destructive/5 hover:bg-destructive/10"),onClick:()=>r(!t),children:[a.jsxs("div",{className:"flex items-center gap-2",children:[n?a.jsx(mn,{className:"w-3.5 h-3.5 text-success shrink-0"}):a.jsx(is,{className:"w-3.5 h-3.5 text-destructive shrink-0"}),a.jsx("span",{className:"font-mono truncate flex-1",children:s}),n&&e.rowCount!==void 0&&a.jsxs(Ge,{variant:"outline",className:"text-[9px] shrink-0 bg-success/10 text-success border-success/20",children:[e.rowCount," row",e.rowCount!==1?"s":""]})]}),t&&a.jsxs("div",{className:"mt-2 space-y-1.5",children:[a.jsx("pre",{className:"font-mono text-[10px] bg-foreground
1301/5 rounded p-2 whitespace-pre-wrap break-all text-muted-foreground",children:e.sql}),e.error&&a.jsx("div",{className:"text-destructive text-[10px] bg-destructive/5 rounded p-1.5",children:e.error})]})]})}function rB({phases:e}){return a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Dn,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs font-bold text-foreground uppercase tracking-wider",children:"Build Pipeline"})]}),e.map((t,r)=>{const n=Zb[t.status]||Zb.pending,s=n.icon,i=t.status==="running",o=t.status==="done",l=t.status==="error";return a.jsxs("div",{className:"relative",children:[r<e.length-1&&a.jsx("div",{className:L("absolute left-[15px] top-10 w-px h-[calc(100%-8px)]",o?"bg-success/30":i?"bg-primary/30":"bg-border")}),a.jsxs("div",{className:L("rounded-lg border p-3 transition-all",i&&"border-primary/30 bg-primary/5 shadow-sm shadow-primary/5",o&&"border-success/20 bg-success/5",l&&"border-destructive/20 bg-destructive/5"),children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(s,{className:L("w-5 h-5 mt-0.5 shrink-0",n.className)}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("div",{className:"flex items-center gap-2 min-w-0",children:a.jsxs("span",{className:L("text-sm font-medium truncate",i&&"text-primary"),children:[t.name,i&&a.jsx(n5,{})]})}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[i&&a.jsx(e5,{}),o&&t.durationMs!==void 0&&a.jsx("span",{className:"text-[10px] font-mono text-muted-foreground",children:t.durationMs<1e3?`${t.durationMs}ms`:`${(t.durationMs/1e3).toFixed(1)}s`}),a.jsx("span",{className:L("text-xs px-2 py-0.5 rounded-full font-medium",{"bg-muted text-muted-foreground":t.status==="pending","bg-primary/10 text-primary":i,"bg-success/10 text-success":o,"bg-destructive/10 text-destructive":l}),children:n.label})]})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground truncate mt-1",children:t.description}),l&&t.error&&a.jsx("p",{className:"text-[10px] text-destructive mt-1",children:t.error})]})]}),i&&a.jsx(t5,{})]})]},t.id)})]})}function sB(){const{planSteps:e,orchestration:t}=gn(),[r,n]=m.useState(new Set(["3","sql-exec"])),s=i=>{n(o=>{const l=new Set(o);return l.has(i)?l.delete(i):l.add(i),l})};return a.jsx($r,{className:"h-full",children:a.jsxs("div",{className:"p-5 space-y-4",children:[a.jsx("h3",{className:"text-sm font-semibold text-muted-foreground mb-4 uppercase tracking-wider",children:"Execution Plan"}),t.active&&t.phases.length>0&&a.jsx(rB,{phases:t.phases}),t.active&&t.phases.length>0&&e.length>0&&a.jsx("div",{className:"border-t pt-3 mt-3",children:a.jsx("span",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Build Steps"})}),a.jsx("div",{className:"space-y-2",children:e.map((i,o)=>{const l=Zb[i.status],c=l.icon,u=r.has(i.id),d=i.logs&&i.logs.length>0,p=i.sqlResults&&i.sqlResults.length>0,h=i.id==="sql-exec",f=i.id==="db-followup",x=d||p,g=i.status==="running";return a.jsxs("div",{className:"relative",children:[o<e.length-1&&a.jsx("div",{className:"absolute left-[15px] top-10 w-px h-[calc(100%-16px)] bg-border"}),a.jsxs("div",{className:L("rounded-lg border p-3 cursor-pointer transition-colors hover:bg-secondary/50",g&&"border-primary/30 bg-primary/5",g&&f&&"plan-step-glow border-transparent",h&&i.status==="done"&&"border-success/30 bg-success/5",h&&i.status==="error"&&"border-destructive/30 bg-destructive/5"),onClick:()=>x&&s(i.id),children:[a.jsxs("div",{className:"flex items-start gap-3",children:[h?g?a.jsx(ze,{className:"w-5 h-5 mt-0.5 shrink-0 text-primary animate-spin"}):a.jsx(Hn,{className:L("w-5 h-5 mt-0.5 shrink-0",i.status==="done"?"text-success":"text-destructive")}
1301):a.jsx(c,{className:L("w-5 h-5 mt-0.5 shrink-0",l.className)}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:L("text-sm font-medium",g&&f&&"text-primary"),children:[i.title,g&&f&&a.jsx(n5,{})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[g&&a.jsx(e5,{}),p&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs(Ge,{variant:"outline",className:"text-[9px] bg-success/10 text-success border-success/20",children:[i.sqlResults.filter(y=>y.status==="success").length," ✓"]}),i.sqlResults.some(y=>y.status==="error")&&a.jsxs(Ge,{variant:"outline",className:"text-[9px] bg-destructive/10 text-destructive border-destructive/20",children:[i.sqlResults.filter(y=>y.status==="error").length," ✗"]})]}),a.jsx("span",{className:L("text-xs px-2 py-0.5 rounded-full font-medium",{"bg-muted text-muted-foreground":i.status==="pending","bg-primary/10 text-primary":g,"bg-success/10 text-success":i.status==="done","bg-destructive/10 text-destructive":i.status==="error"}),children:l.label}),x&&(u?a.jsx(Yr,{className:"w-4 h-4 text-muted-foreground"}):a.jsx(ia,{className:"w-4 h-4 text-muted-foreground"}))]})]}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:i.description}),i.action&&i.status==="pending"&&a.jsx("div",{className:"mt-2.5",children:a.jsx("button",{onClick:y=>{var b;y.stopPropagation(),(b=i.action)==null||b.onClick()},className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors",children:i.action.label})})]})]}),g&&f&&a.jsx(t5,{}),u&&p&&a.jsx("div",{className:"mt-3 ml-8 space-y-1.5",children:i.sqlResults.map((y,b)=>a.jsx(nB,{result:y},b))}),u&&d&&!p&&a.jsx("div",{className:"mt-3 ml-8 rounded-md bg-foreground
1301/[0.03] border p-2.5 space-y-1",children:i.logs.map((y,b)=>a.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted-foreground",children:[a.jsx(Yg,{className:"w-3 h-3 text-muted-foreground/50 shrink-0"}),a.jsx("span",{children:y})]},b))})]})]},i.id)})})]})})}var Zg="Dialog",[r5,s5]=sl(Zg),[aB,pi]=r5(Zg),a5=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:s,onOpenChange:i,modal:o=!0}=e,l=m.useRef(null),c=m.useRef(null),[u,d]=ac({prop:n,defaultProp:s??!1,onChange:i,caller:Zg});return a.jsx(aB,{scope:t,triggerRef:l,contentRef:c,contentId:io(),titleId:io(),descriptionId:io(),open:u,onOpenChange:d,onOpenToggle:m.useCallback(()=>d(p=>!p),[d]),modal:o,children:r})};a5.displayName=Zg;var i5="DialogTrigger",o5=m.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,s=pi(i5,r),i=Tr(t,s.triggerRef);return a.jsx(En.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":Bw(s.open),...n,ref:i,onClick:vn(e.onClick,s.onOpenToggle)})});o5.displayName=i5;var $w="DialogPortal",[iB,l5]=r5($w,{forceMount:void 0}),c5=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:s}=e,i=pi($w,t);return a.jsx(iB,{scope:t,forceMount:r,children:m.Children.map(n,o=>a.jsx(Fa,{present:r||i.open,children:a.jsx(dw,{asChild:!0,container:s,children:o})}))})};c5.displayName=$w;var jm="DialogOverlay",u5=m.forwardRef((e,t)=>{const r=l5(jm,e.__scopeDialog),{forceMount:n=r.forceMount,...s}=e,i=pi(jm,e.__scopeDialog);return i.modal?a.jsx(Fa,{present:n||i.open,children:a.jsx(lB,{...s,ref:t})}):null});u5.displayName=jm;var oB=pw("DialogOverlay.RemoveScroll"),lB=m.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,s=pi(jm,r);return a.jsx(mw,{as:oB,allowPinchZoom:!0,shards:[s.contentRef],children:a.jsx(En.div,{"data-state":Bw(s.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),dc="DialogContent",d5=m.forwardRef((e,t)=>{const r=l5(dc,e.__scopeDialog),{forceMount:n=r.forceMount,...s}=e,i=pi(dc,e.__scopeDialog);return a.jsx(Fa,{present:n||i.open,children:i.modal?a.jsx(cB,{...s,ref:t}):a.jsx(uB,{...s,ref:t})})});d5.displayName=dc;var cB=m.forwardRef((e,t)=>{const r=pi(dc,e.__scopeDialog),n=m.useRef(null),s=Tr(t,r.contentRef,n);return m.useEffect(()=>{const i=n.current;if(i)return gw(i)},[]),a.jsx(p5,{...e,ref:s,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:vn(e.onCloseAutoFocus,i=>{var o;i.preventDefault(),(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:vn(e.onPointerDownOutside,i=>{const o=i.detail.originalEvent,l=o.button===0&&o.ctrlKey===!0;(o.button===2||l)&&i.preventDefault()}),onFocusOutside:vn(e.onFocusOutside,i=>i.preventDefault())})}),uB=m.forwardRef((e,t)=>{const r=pi(dc,e.__scopeDialog),n=m.useRef(!1),s=m.useRef(!1);return a.jsx(p5,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,i),i.defaultPrevented||(n.current||(l=r.triggerRef.current)==null||l.focus(),i.preventDefault()),n.current=!1,s.current=!1},onInteractOutside:i=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const o=i.target;((u=r.triggerRef.current)==null?void 0:u.contains(o))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),p5=m.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:i,...o}=e,l=pi(dc,r),c=m.useRef(null),u=Tr(t,c);return xw(),a.jsxs(a.Fragment,{children:[a.jsx(yw,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:i,children:a.jsx(u
vendor: 2,726 bytes, lines 1301-1305
1301w,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Bw(l.open),...o,ref:u,onDismiss:()=>l.onOpenChange(!1)})}),a.jsxs(a.Fragment,{children:[a.jsx(pB,{titleId:l.titleId}),a.jsx(fB,{contentRef:c,descriptionId:l.descriptionId})]})]})}),Fw="DialogTitle",h5=m.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,s=pi(Fw,r);return a.jsx(En.h2,{id:s.titleId,...n,ref:t})});h5.displayName=Fw;var f5="DialogDescription",m5=m.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,s=pi(f5,r);return a.jsx(En.p,{id:s.descriptionId,...n,ref:t})});m5.displayName=f5;var g5="DialogClose",x5=m.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,s=pi(g5,r);return a.jsx(En.button,{type:"button",...n,ref:t,onClick:vn(e.onClick,()=>s.onOpenChange(!1))})});x5.displayName=g5;function Bw(e){return e?"open":"closed"}var y5="DialogTitleWarning",[dB,b5]=RL(y5,{contentName:dc,titleName:Fw,docsSlug:"dialog"}),pB=({titleId:e})=>{const t=b5(y5),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
1302
1303If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
1304
1305For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return m.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},hB="DialogDescriptionWarning",fB=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${b5(hB).contentName}}.`;return m.useEffect(()=>{var i;const s=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},v5=a5,mB=o5,w5=c5,Uw=u5,zw=d5,qw=h5,Hw=m5,Ww=x5;const yo=v5,gB=w5,j5=m.forwardRef(({className:e,...t},r)=>a.jsx(Uw,{ref:r,className:L("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));j5.displayName=Uw.displayName;const Fi=m.forwardRef(({className:e,children:t,...r},n)=>a.jsxs(gB,{children:[a.jsx(j5,{}),a.jsxs(zw,{ref:n,className:L("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...r,children:[t,a.jsxs(Ww,{className:"absolute right-4 top-4 roun
1305ded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[a.jsx(qn,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fi.displayName=zw.displayName;const Bi=({className:e,...t})=>a.jsx("div",{className:L("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Bi.displayName="DialogHeader";const Ch=({className:e,...t})=>a.jsx("div",{className:L("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Ch.displayName="DialogFooter";const La=m.forwardRef(({className:e,...t},r)=>a.jsx(qw,{ref:r,className:L("text-lg font-semibold leading-none tracking-tight",e),...t}));La.displayName=qw.displayName;const ol=m.forwardRef(({className:e,...t},r)=>a.jsx(Hw,{ref:r,className:L("text-sm text-muted-foreground",e),...t}));ol.displayName=Hw.displayName;var xB="Separator",qk="horizontal",yB=["horizontal","vertical"],N5=m.forwardRef((e,t)=>{const{decorative:r,orientation:n=qk,...s}=e,i=bB(n)?n:qk,l=r?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return a.jsx(En.div,{"data-orientation":i,...l,...s,ref:t})});N5.displayName=xB;function bB(e){return yB.includes(e)}var k5=N5;const Ni=m.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...n},s)=>a.jsx(k5,{ref:s,decorative:r,orientation:t,className:L("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...n}));Ni.displayName=k5.displayName;var Qg="Tabs",[vB,wve]=sl(Qg,[z_]),S5=z_(),[wB,Vw]=vB(Qg),C5=m.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,onValueChange:s,defaultValue:i,orientation:o="horizontal",dir:l,activationMode:c="automatic",...u}=e,d=fw(l),[p,h]=ac({prop:n,onChange:s,defaultProp:i??"",caller:Qg});return a.jsx(wB,{scope:r,baseId:io(),value:p,onValueChange:h,orientation:o,dir:d,activationMode:c,children:a.jsx(En.div,{dir:d,"data-orientation":o,...u,ref:t})})});C5.displayName=Qg;var P5="TabsList",A5=m.forwardRef((e,t)=>{const{__scopeTabs:r,loop:n=!0,...s}=e,i=Vw(P5,r),o=S5(r);return a.jsx(UL,{asChild:!0,...o,orientation:i.orientation,dir:i.dir,loop:n,children:a.jsx(En.div,{role:"tablist","aria-orientation":i.orientation,...s,ref:t})})});A5.displayName=P5;var _5="TabsTrigger",T5=m.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,disabled:s=!1,...i}=e,o=Vw(_5,r),l=S5(r),c=O5(o.baseId,n),u=R5(o.baseId,n),d=n===o.value;return a.jsx(zL,{asChild:!0,...l,focusable:!s,active:d,children:a.jsx(En.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":u,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...i,ref:t,onMouseDown:vn(e.onMouseDown,p=>{!s&&p.button===0&&p.ctrlKey===!1?o.onValueChange(n):p.preventDefault()}),onKeyDown:vn(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&o.onValueChange(n)}),onFocus:vn(e.onFocus,()=>{const p=o.activationMode!=="manual";!d&&!s&&p&&o.onValueChange(n)})})})});T5.displayName=_5;var E5="TabsContent",I5=m.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,forceMount:s,children:i,...o}=e,l=Vw(E5,r),c=O5(l.baseId,n),u=R5(l.baseId,n),d=n===l.value,p=m.useRef(d);return m.useEffect(()=>{const h=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(h)},[]),a.jsx(Fa,{present:s||d,children:({present:h})=>a.jsx(En.div,{"data-state":d?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!h,id:u,tabIndex:0,...o,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:h&&i})})});I5.displayName=E5;function O5(e,t){return`${e}-trigger-${t}`}function R5(e,t){return`${e}-content-${t}`}var jB=C5,D5=A5,M5=T5,L5=I5;const $5=jB,Gw=m.forwardRef(({className:e,...t},r)=>a.jsx(D5,{ref:r,className:L("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));Gw.displayName=D5.displayName;const Wo=m.forwardRef(({className:e,...t},r)=>a.jsx(M5,{ref:r,className:L("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",e),...t}));Wo.displayName=M5.displayName;const Vo=m.forwardRef(({className:e,...t},r)=>a.jsx(L5,{ref:r,className:L("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));Vo.displayName=L5.displayName;var F5=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),NB="VisuallyHidden",kB=m.forwardRef((e,t)=>
vendor: 18,383 bytes, line 1305
1305a.jsx(En.span,{...e,ref:t,style:{...F5,...e.style}}));kB.displayName=NB;var SB=[" ","Enter","ArrowUp","ArrowDown"],CB=[" ","Enter"],pc="Select",[ex,tx,PB]=DL(pc),[od,jve]=sl(pc,[PB,qg]),nx=qg(),[AB,ll]=od(pc),[_B,TB]=od(pc),B5=e=>{const{__scopeSelect:t,children:r,open:n,defaultOpen:s,onOpenChange:i,value:o,defaultValue:l,onValueChange:c,dir:u,name:d,autoComplete:p,disabled:h,required:f,form:x}=e,g=nx(t),[y,b]=m.useState(null),[v,k]=m.useState(null),[N,j]=m.useState(!1),w=fw(u),[S,T]=ac({prop:n,defaultProp:s??!1,onChange:i,caller:pc}),[C,A]=ac({prop:o,defaultProp:l,onChange:c,caller:pc}),P=m.useRef(null),E=y?x||!!y.closest("form"):!0,[_,I]=m.useState(new Set),D=Array.from(_).map(M=>M.props.value).join(";");return a.jsx(F_,{...g,children:a.jsxs(AB,{required:f,scope:t,trigger:y,onTriggerChange:b,valueNode:v,onValueNodeChange:k,valueNodeHasChildren:N,onValueNodeHasChildrenChange:j,contentId:io(),value:C,onValueChange:A,open:S,onOpenChange:T,dir:w,triggerPointerDownPosRef:P,disabled:h,children:[a.jsx(ex.Provider,{scope:t,children:a.jsx(_B,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(M=>{I(B=>new Set(B).add(M))},[]),onNativeOptionRemove:m.useCallback(M=>{I(B=>{const $=new Set(B);return $.delete(M),$})},[]),children:r})}),E?a.jsxs(uE,{"aria-hidden":!0,required:f,tabIndex:-1,name:d,autoComplete:p,value:C,onChange:M=>A(M.target.value),disabled:h,form:x,children:[C===void 0?a.jsx("option",{value:""}):null,Array.from(_)]},D):null]})})};B5.displayName=pc;var U5="SelectTrigger",z5=m.forwardRef((e,t)=>{const{__scopeSelect:r,disabled:n=!1,...s}=e,i=nx(r),o=ll(U5,r),l=o.disabled||n,c=Tr(t,o.onTriggerChange),u=tx(r),d=m.useRef("touch"),[p,h,f]=pE(g=>{const y=u().filter(k=>!k.disabled),b=y.find(k=>k.value===o.value),v=hE(y,g,b);v!==void 0&&o.onValueChange(v.value)}),x=g=>{l||(o.onOpenChange(!0),f()),g&&(o.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return a.jsx(hw,{asChild:!0,...i,children:a.jsx(En.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":dE(o.value)?"":void 0,...s,ref:c,onClick:vn(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&x(g)}),onPointerDown:vn(s.onPointerDown,g=>{d.current=g.pointerType;const y=g.target;y.hasPointerCapture(g.pointerId)&&y.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(x(g),g.preventDefault())}),onKeyDown:vn(s.onKeyDown,g=>{const y=p.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(y&&g.key===" ")&&SB.includes(g.key)&&(x(),g.preventDefault())})})})});z5.displayName=U5;var q5="SelectValue",H5=m.forwardRef((e,t)=>{const{__scopeSelect:r,className:n,style:s,children:i,placeholder:o="",...l}=e,c=ll(q5,r),{onValueNodeHasChildrenChange:u}=c,d=i!==void 0,p=Tr(t,c.onValueNodeChange);return Ii(()=>{u(d)},[u,d]),a.jsx(En.span,{...l,ref:p,style:{pointerEvents:"none"},children:dE(c.value)?a.jsx(a.Fragment,{children:o}):i})});H5.displayName=q5;var EB="SelectIcon",W5=m.forwardRef((e,t)=>{const{__scopeSelect:r,children:n,...s}=e;return a.jsx(En.span,{"aria-hidden":!0,...s,ref:t,children:n||"▼"})});W5.displayName=EB;var IB="SelectPortal",V5=e=>a.jsx(dw,{asChild:!0,...e});V5.displayName=IB;var hc="SelectContent",G5=m.forwardRef((e,t)=>{const r=ll(hc,e.__scopeSelect),[n,s]=m.useState();if(Ii(()=>{s(new DocumentFragment)},[]),!r.open){const i=n;return i?bw.createPortal(a.jsx(K5,{scope:e.__scopeSelect,children:a.jsx(ex.Slot,{scope:e.__scopeSelect,children:a.jsx("div",{children:e.children})})}),i):null}return a.jsx(Y5,{...e,ref:t})});G5.displayName=hc;var Ya=10,[K5,cl]=od(hc),OB="SelectContentImpl",RB=pw("SelectContent.RemoveScroll"),Y5=m.forwardRef((e,t)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:i,onPointerDownOutside:o,side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:p,collisionBoundary:h,collisionPadding:f,sticky:x,hideWhenDetached:g,avoidCollisions:y,...b}=e,v=ll(hc,r),[k,N]=m.useState(null),[j,w]=m.useState(null),S=Tr(t,ae=>N(ae)),[T,C]=m.useState(null),[A,P]=m.useState(null),E=tx(r),[_,I]=m.useState(!1),D=m.useRef(!1);m.useEffect(()=>{if(k)return gw(k)},[k]),xw();const M=m.useCallback(ae=>{const[ve,...re]=E().map(te=>te.ref.current),[se]=re.slice(-1),le=document.activeElement;for(const te of ae)if(te===le||(te==null||te.scrollIntoView({block:"nearest"}),te===ve&&j&&(j.scrollTop=0),te===se&&j&&(j.scrollTop=j.scrollHeight),te==null||te.focus(),document.activeElement!==le))return},[E,j]),B=m.useCallback(()=>M([T,k]),[M,T,k]);m.useEffect(()=>{_&&B()},[_,B]);const{onOpenChange:$,triggerPointerDownPosRef:K}=v;m.useEffect(()=>{if(k){let ae={x:0,y:0};const ve=se=>{var le,te;ae={x:Math.abs(Math.round(se.pageX)-(((le=K.current)==null?void 0:le.x)??0)),y:Math.abs(Math.round(se.pageY)-(((te=K.current)==null?void 0:te.y)??0))}},re=se=>{ae.x<=10&&ae.y<=10?se.preventDefault():k.contains(se.target)||$(!1),document.removeEventListener("pointermove",ve),K.current=null};return K.current!==null&&(document.addEventListener("pointermove",ve),document.addEventListener("pointerup",re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ve),document.removeEventListener("pointerup",re,{capture:!0})}}},[k,$,K]),m.useEffect(()=>{const ae=()=>$(!1);return window.addEventListener("blur",ae),window.addEventListener("resize",ae),()=>{window.removeEventListener("blur",ae),window.removeEventListener("resize",ae)}},[$]);const[R,Y]=pE(ae=>{const ve=E().filter(le=>!le.disabled),re=ve.find(le=>le.ref.current===document.activeElement),se=hE(ve,ae,re);se&&setTimeout(()=>se.ref.current.focus())}),Z=m.useCallback((ae,ve,re)=>{const se=!D.current&&!re;(v.value!==void 0&&v.value===ve||se)&&(C(ae),se&&(D.current=!0))},[v.value]),O=m.useCallback(()=>k==null?void 0:k.focus(),[k]),ne=m.useCallback((ae,ve,re)=>{const se=!D.current&&!re;(v.value!==void 0&&v.value===ve||se)&&P(ae)},[v.value]),oe=n==="popper"?Qb:J5,he=oe===Qb?{side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:p,collisionBoundary:h,collisionPadding:f,sticky:x,hideWhenDetached:g,avoidCollisions:y}:{};return a.jsx(K5,{scope:r,content:k,viewport:j,onViewportChange:w,itemRefCallback:Z,selectedItem:T,onItemLeave:O,itemTextRefCallback:ne,focusSelectedItem:B,selectedItemText:A,position:n,isPositioned:_,searchRef:R,children:a.jsx(mw,{as:RB,allowPinchZoom:!0,children:a.jsx(yw,{asChild:!0,trapped:v.open,onMountAutoFocus:ae=>{ae.preventDefault()},onUnmountAutoFocus:vn(s,ae=>{var ve;(ve=v.trigger)==null||ve.focus({preventScroll:!0}),ae.preventDefault()}),children:a.jsx(uw,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:o,onFocusOutside:ae=>ae.preventDefault(),onDismiss:()=>v.onOpenChange(!1),children:a.jsx(oe,{role:"listbox",id:v.contentId,"data-state":v.open?"open":"closed",dir:v.dir,onContextMenu:ae=>ae.preventDefault(),...b,...he,onPlaced:()=>I(!0),ref:S,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:vn(b.onKeyDown,ae=>{const ve=ae.ctrlKey||ae.altKey||ae.metaKey;if(ae.key==="Tab"&&ae.preventDefault(),!ve&&ae.key.length===1&&Y(ae.key),["ArrowUp","ArrowDown","Home","End"].includes(ae.key)){let se=E().filter(le=>!le.disabled).map(le=>le.ref.current);if(["ArrowUp","End"].includes(ae.key)&&(se=se.slice().reverse()),["ArrowUp","ArrowDown"].includes(ae.key)){const le=ae.target,te=se.indexOf(le);se=se.slice(te+1)}setTimeout(()=>M(se)),ae.preventDefault()}})})})})})})});Y5.displayName=OB;var DB="SelectItemAlignedPosition",J5=m.forwardRef((e,t)=>{const{__scopeSelect:r,onPlaced:n,...s}=e,i=ll(hc,r),o=cl(hc,r),[l,c]=m.useState(null),[u,d]=m.useState(null),p=Tr(t,S=>d(S)),h=tx(r),f=m.useRef(!1),x=m.useRef(!0),{viewport:g,selectedItem:y,selectedItemText:b,focusSelectedItem:v}=o,k=m.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&u&&g&&y&&b){const S=i.trigger.getBoundingClientRect(),T=u.getBoundingClientRect(),C=i.valueNode.getBoundingClientRect(),A=b.getBoundingClientRect();if(i.dir!=="rtl"){const le=A.left-T.left,te=C.left-le,We=S.left-te,Me=S.width+We,Te=Math.max(Me,T.width),Ee=window.innerWidth-Ya,st=Xb(te,[Ya,Math.max(Ya,Ee-Te)]);l.style.minWidth=Me+"px",l.style.left=st+"px"}else{const le=T.right-A.right,te=window.innerWidth-C.right-le,We=window.innerWidth-S.right-te,Me=S.width+We,Te=Math.max(Me,T.width),Ee=window.innerWidth-Ya,st=Xb(te,[Ya,Math.max(Ya,Ee-Te)]);l.style.minWidth=Me+"px",l.style.right=st+"px"}const P=h(),E=window.innerHeight-Ya*2,_=g.scrollHeight,I=window.getComputedStyle(u),D=parseInt(I.borderTopWidth,10),M=parseInt(I.paddingTop,10),B=parseInt(I.borderBottomWidth,10),$=parseInt(I.paddingBottom,10),K=D+M+_+$+B,R=Math.min(y.offsetHeight*5,K),Y=window.getComputedStyle(g),Z=parseInt(Y.paddingTop,10),O=parseInt(Y.paddingBottom,10),ne=S.top+S.height/2-Ya,oe=E-ne,he=y.offsetHeight/2,ae=y.offsetTop+he,ve=D+M+ae,re=K-ve;if(ve<=ne){const le=P.length>0&&y===P[P.length-1].ref.current;l.style.bottom="0px";const te=u.clientHeight-g.offsetTop-g.offsetHeight,We=Math.max(oe,he+(le?O:0)+te+B),Me=ve+We;l.style.height=Me+"px"}else{const le=P.length>0&&y===P[0].ref.current;l.style.top="0px";const We=Math.max(ne,D+g.offsetTop+(le?Z:0)+he)+re;l.style.height=We+"px",g.scrollTop=ve-ne+g.offsetTop}l.style.margin=`${Ya}px 0`,l.style.minHeight=R+"px",l.style.maxHeight=E+"px",n==null||n(),requestAnimationFrame(()=>f.current=!0)}},[h,i.trigger,i.valueNode,l,u,g,y,b,i.dir,n]);Ii(()=>k(),[k]);const[N,j]=m.useState();Ii(()=>{u&&j(window.getComputedStyle(u).zIndex)},[u]);const w=m.useCallback(S=>{S&&x.current===!0&&(k(),v==null||v(),x.current=!1)},[k,v]);return a.jsx(LB,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:f,onScrollButtonChange:w,children:a.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:a.jsx(En.div,{...s,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});J5.displayName=DB;var MB="SelectPopperPosition",Qb=m.forwardRef((e,t)=>{const{__scopeSelect:r,align:n="start",collisionPadding:s=Ya,...i}=e,o=nx(r);return a.jsx(L_,{...o,...i,ref:t,align:n,collisionPadding:s,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Qb.displayName=MB;var[LB,Kw]=od(hc,{}),e0="SelectViewport",X5=m.forwardRef((e,t)=>{const{__scopeSelect:r,nonce:n,...s}=e,i=cl(e0,r),o=Kw(e0,r),l=Tr(t,i.onViewportChange),c=m.useRef(0);return a.jsxs(a.Fragment,{children:[a.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),a.jsx(ex.Slot,{scope:r,children:a.jsx(En.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:vn(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:h}=o;if(h!=null&&h.current&&p){const f=Math.abs(c.current-d.scrollTop);if(f>0){const x=window.innerHeight-Ya*2,g=parseFloat(p.style.minHeight),y=parseFloat(p.style.height),b=Math.max(g,y);if(b<x){const v=b+f,k=Math.min(x,v),N=v-k;p.style.height=k+"px",p.style.bottom==="0px"&&(d.scrollTop=N>0?N:0,p.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});X5.displayName=e0;var Z5="SelectGroup",[$B,FB]=od(Z5),BB=m.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e,s=io();return a.jsx($B,{scope:r,id:s,children:a.jsx(En.div,{role:"group","aria-labelledby":s,...n,ref:t})})});BB.displayName=Z5;var Q5="SelectLabel",eE=m.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e,s=FB(Q5,r);return a.jsx(En.div,{id:s.id,...n,ref:t})});eE.displayName=Q5;var Nm="SelectItem",[UB,tE]=od(Nm),nE=m.forwardRef((e,t)=>{const{__scopeSelect:r,value:n,disabled:s=!1,textValue:i,...o}=e,l=ll(Nm,r),c=cl(Nm,r),u=l.value===n,[d,p]=m.useState(i??""),[h,f]=m.useState(!1),x=Tr(t,v=>{var k;return(k=c.itemRefCallback)==null?void 0:k.call(c,v,n,s)}),g=io(),y=m.useRef("touch"),b=()=>{s||(l.onValueChange(n),l.onOpenChange(!1))};if(n==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return a.jsx(UB,{scope:r,value:n,disabled:s,textId:g,isSelected:u,onItemTextChange:m.useCallback(v=>{p(k=>k||((v==null?void 0:v.textContent)??"").trim())},[]),children:a.jsx(ex.ItemSlot,{scope:r,value:n,disabled:s,textValue:d,children:a.jsx(En.div,{role:"option","aria-labelledby":g,"data-highlighted":h?"":void 0,"aria-selected":u&&h,"data-state":u?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...o,ref:x,onFocus:vn(o.onFocus,()=>f(!0)),onBlur:vn(o.onBlur,()=>f(!1)),onClick:vn(o.onClick,()=>{y.current!=="mouse"&&b()}),onPointerUp:vn(o.onPointerUp,()=>{y.current==="mouse"&&b()}),onPointerDown:vn(o.onPointerDown,v=>{y.current=v.pointerType}),onPointerMove:vn(o.onPointerMove,v=>{var k;y.current=v.pointerType,s?(k=c.onItemLeave)==null||k.call(c):y.current==="mouse"&&v.currentTarget.focus({preventScroll:!0})}),onPointerLeave:vn(o.onPointerLeave,v=>{var k;v.currentTarget===document.activeElement&&((k=c.onItemLeave)==null||k.call(c))}),onKeyDown:vn(o.onKeyDown,v=>{var N;((N=c.searchRef)==null?void 0:N.current)!==""&&v.key===" "||(CB.includes(v.key)&&b(),v.key===" "&&v.preventDefault())})})})})});nE.displayName=Nm;var ep="SelectItemText",rE=m.forwardRef((e,t)=>{const{__scopeSelect:r,className:n,style:s,...i}=e,o=ll(ep,r),l=cl(ep,r),c=tE(ep,r),u=TB(ep,r),[d,p]=m.useState(null),h=Tr(t,b=>p(b),c.onItemTextChange,b=>{var v;return(v=l.itemTextRefCallback)==null?void 0:v.call(l,b,c.value,c.disabled)}),f=d==null?void 0:d.textContent,x=m.useMemo(()=>a.jsx("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:g,onNativeOptionRemove:y}=u;return Ii(()=>(g(x),()=>y(x)),[g,y,x]),a.jsxs(a.Fragment,{children:[a.jsx(En.span,{id:c.textId,...i,ref:h}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?bw.createPortal(i.children,o.valueNode):null]})});rE.displayName=ep;var sE="SelectItemIndicator",aE=m.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e;return tE(sE,r).isSelected?a.jsx(En.span,{"aria-hidden":!0,...n,ref:t}):null});aE.displayName=sE;var t0="SelectScrollUpButton",iE=m.forwardRef((e,t)=>{const r=cl(t0,e.__scopeSelect),n=Kw(t0,e.__scopeSelect),[s,i]=m.useState(!1),o=Tr(t,n.onScrollButtonChange);return Ii(()=>{if(r.viewport&&r.isPositioned){let l=function(){const u=c.scrollTop>0;i(u)};const c=r.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[r.viewport,r.isPositioned]),s?a.jsx(lE,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=r;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});iE.displayName=t0;var n0="SelectScrollDownButton",oE=m.forwardRef((e,t)=>{const r=cl(n0,e.__scopeSelect),n=Kw(n0,e.__scopeSelect),[s,i]=m.useState(!1),o=Tr(t,n.onScrollButtonChange);return Ii(()=>{if(r.viewport&&r.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<u;i(d)};const c=r.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[r.viewport,r.isPositioned]),s?a.jsx(lE,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=r;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});oE.displayName=n0;var lE=m.forwardRef((e,t)=>{const{__scopeSelect:r,onAutoScroll:n,...s}=e,i=cl("SelectScrollButton",r),o=m.useRef(null),l=tx(r),c=m.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return m.useEffect(()=>()=>c(),[c]),Ii(()=>{var d;const u=l().find(p=>p.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[l]),a.jsx(En.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:vn(s.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(n,50))}),onPointerMove:vn(s.onPointerMove,()=>{var u;(u=i.onItemLeave)==null||u.call(i),o.current===null&&(o.current=window.setInterval(n,50))}),onPointerLeave:vn(s.onPointerLeave,()=>{c()})})}),zB="SelectSeparator",cE=m.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e;return a.jsx(En.div,{"aria-hidden":!0,...n,ref:t})});cE.displayName=zB;var r0="SelectArrow",qB=m.forwardRef((e,t)=>{const{__scopeSelect:r,...n}=e,s=nx(r),i=ll(r0,r),o=cl(r0,r);return i.open&&o.position==="popper"?a.jsx($_,{...s,...n,ref:t}):null});qB.displayName=r0;var HB="SelectBubbleInput",uE=m.forwardRef(({__scopeSelect:e,value:t,...r},n)=>{const s=m.useRef(null),i=Tr(n,s),o=q_(t);return m.useEffect(()=>{const l=s.current;if(!l)return;const c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==t&&d){const p=new Event("change",{bubbles:!0});d.call(l,t),l.dispatchEvent(p)}},[o,t]),a.jsx(En.select,{...r,style:{...F5,...r.style},ref:i,defaultValue:t})});uE.displayName=HB;function dE(e){return e===""||e===void 0}function pE(e){const t=Uo(e),r=m.useRef(""),n=m.useRef(0),s=m.useCallback(o=>{const l=r.current+o;t(l),function c(u){r.current=u,window.clearTimeout(n.current),u!==""&&(n.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),i=m.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,s,i]}function hE(e,t,r){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=r?e.indexOf(r):-1;let o=WB(e,Math.max(i,0));s.length===1&&(o=o.filter(u=>u!==r));const c=o.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==r?c:void 0}function WB(e,t){return e.map((r,n)=>e[(t+n)%e.length])}var VB=B5,fE=z5,GB=H5,KB=W5,YB=V5,mE=G5,JB=X5,gE=eE,xE=nE,XB=rE,ZB=aE,yE=iE,bE=oE,vE=cE;const Ns=VB,ks=GB,hs=m.forwardRef(({className:e,children:t,...r},n)=>a.jsxs(fE,{ref:n,className:L("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm r
1305ing-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...r,children:[t,a.jsx(KB,{asChild:!0,children:a.jsx(Yr,{className:"h-4 w-4 opacity-50"})})]}));hs.displayName=fE.displayName;const wE=m.forwardRef(({className:e,...t},r)=>a.jsx(yE,{ref:r,className:L("flex cursor-default items-center justify-center py-1",e),...t,children:a.jsx(Nw,{className:"h-4 w-4"})}));wE.displayName=yE.displayName;const jE=m.forwardRef(({className:e,...t},r)=>a.jsx(bE,{ref:r,className:L("flex cursor-default items-center justify-center py-1",e),...t,children:a.jsx(Yr,{className:"h-4 w-4"})}));jE.displayName=bE.displayName;const fs=m.forwardRef(({className:e,children:t,position:r="popper",...n},s)=>a.jsx(YB,{children:a.jsxs(mE,{ref:s,className:L("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...n,children:[a.jsx(wE,{}),a.jsx(JB,{className:L("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),a.jsx(jE,{})]})}));fs.displayName=mE.displayName;const QB=m.forwardRef(({className:e,...t},r)=>a.jsx(gE,{ref:r,className:L("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));QB.displayName=gE.displayName;const Dt=m.forwardRef(({className:e,children:t,...r},n)=>a.jsxs(xE,{ref:n,className:L("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",e),...r,children:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(ZB,{children:a.jsx(Wn,{className:"h-4 w-4"})})}),a.jsx(XB,{children:t})]}));Dt.displayName=xE.displayName;const e8=m.forwardRef(({className:e,...t},r)=>a.jsx(vE,{ref:r,className:L("-mx-1 my-1 h-px bg-muted",e),...t}));e8.displayName=vE.displayName;const t8={visual:{},voice:{},components:{},rules:{}};function NE(e,t){const{user:r}=Us(),[n,s]=m.useState([]),[i,o]=m.useState(null),[l,c]=m.useState(!0),u=m.useCallback(async()=>{if(!r)return;c(!0);const f=t&&t!==r.id?t:r.id,{data:x}=await G.from("brand_guidelines").select("*").eq("user_id",f).order("updated_at",{ascending:!1});if(x){const g=x.map(v=>({...v,guidelines:v.guidelines||t8}));s(g);const y=g.find(v=>v.project_id===e),b=g.find(v=>!v.project_id&&v.is_default);o(y||b||null)}c(!1)},[r,e,t]);m.useEffect(()=>{u()},[u]);const d=m.useCallback(async(f,x)=>{if(!r)return null;if(x.id){const{data:y}=await G.from("brand_guidelines").update({name:x.name||"Brand Guidelines",guidelines:f,source_type:x.sourceType||"form",is_default:x.isDefault??!1}).eq("id",x.id).select().single();return await u(),y}const{data:g}=await G.from("brand_guidelines").insert({user_id:r.id,project_id:x.projectId??null,name:x.name||"Brand Guidelines",guidelines:f,source_type:x.sourceType||"form",is_default:x.isDefault??!1}).select().single();return await u(),g},[r,u]),p=m.useCallback(async f=>{await G.from("brand_guidelines").delete().eq("id",f),await u()},[u]),h=m.useCallback(f=>{var N,j,w,S,T;if(!f)return"";const x=f.guidelines,g=[`
1306
1307--- BRAND GUIDELINES (follow these strictly) ---`],y=x.visual;(y.primaryColor||y.secondaryColor||y.accentColor)&&g.push(`COLORS: Primary: ${y.primaryColor||"N/A"}, Secondary: ${y.secondaryColor||"N/A"}, Accent: ${y.accentColor||"N/A"}
1307, Background: ${y.backgroundColor||"N/A"}, Text: ${y.textColor||"N/A"}`),(y.headingFont||y.bodyFont)&&g.push(`TYPOGRAPHY: Heading font: ${y.headingFont||"inherit"}, Body font: ${y.bodyFont||"inherit"}`),y.imageryStyle&&g.push(`IMAGERY STYLE: ${y.imageryStyle}`),y.borderRadius&&g.push(`BORDER RADIUS: ${y.borderRadius}`),y.spacing&&g.push(`SPACING: ${y.spacing}`),y.logoUrl&&g.push(`LOGO URL: ${y.logoUrl}`);const b=x.voice;b.tone&&g.push(`BRAND TONE: ${b.tone}`),b.formality&&g.push(`FORMALITY: ${b.formality}`),b.writingStyle&&g.push(`WRITING STYLE: ${b.writingStyle}`),b.tagline&&g.push(`TAGLINE: "${b.tagline}"`),(N=b.vocabulary)!=null&&N.length&&g.push(`PREFERRED VOCABULARY: ${b.vocabulary.join(", ")}`);const v=x.components;v.buttonStyle&&g.push(`BUTTON STYLE: ${v.buttonStyle}`),v.cardStyle&&g.push(`CARD STYLE: ${v.cardStyle}`),v.navPattern&&g.push(`NAV PATTERN: ${v.navPattern}`),v.iconStyle&&g.push(`ICON STYLE: ${v.iconStyle}`);const k=x.rules;return(j=k.dos)!=null&&j.length&&g.push(`DO: ${k.dos.join("; ")}`),(w=k.donts)!=null&&w.length&&g.push(`DON'T: ${k.donts.join("; ")}`),(S=k.bannedWords)!=null&&S.length&&g.push(`BANNED WORDS: ${k.bannedWords.join(", ")}`),(T=k.disclaimers)!=null&&T.length&&g.push(`REQUIRED DISCLAIMERS: ${k.disclaimers.join("; ")}`),g.length>1?g.join(`
1308`):""},[]);return{guidelines:n,activeGuideline:i,loading:l,save:d,remove:p,toPromptContext:h,reload:u}}function Td({value:e,onChange:t,placeholder:r}){const[n,s]=m.useState(""),i=()=>{const o=n.trim();o&&!e.includes(o)&&(t([...e,o]),s(""))};return a.jsxs("div",{children:[a.jsx("div",{className:"flex gap-1.5 flex-wrap mb-1.5",children:e.map((o,l)=>a.jsxs(Ge,{variant:"secondary",className:"gap-1 text-xs cursor-pointer",onClick:()=>t(e.filter((c,u)=>u!==l)),children:[o," ",a.jsx("span",{className:"text-muted-foreground",children:"×"})]},l))}),a.jsxs("div",{className:"flex gap-1.5",children:[a.jsx(Cn,{value:n,onChange:o=>s(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),i()),placeholder:r,className:"h-8 text-xs"}),a.jsx(Q,{size:"sm",variant:"outline",onClick:i,className:"h-8 text-xs shrink-0",children:"Add"})]})]})}function Ed({label:e,value:t,onChange:r}){return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"color",value:t||"#000000",onChange:n=>r(n.target.value),className:"w-8 h-8 rounded border border-input cursor-pointer"}),a.jsxs("div",{className:"flex-1",children:[a.jsx($n,{className:"text-xs text-muted-foreground",children:e}),a.jsx(Cn,{value:t||"",onChange:n=>r(n.target.value),placeholder:"#000000",className:"h-7 text-xs mt-0.5"})]})]})}function n8({data:e,name:t}){const r=e.visual,n=r.primaryColor||"#0f3d2e",s=r.accentColor||r.secondaryColor||"#a7e8c5",i=r.backgroundColor||"#ffffff",o=r.textColor||"#0a0a0a",l=r.headingFont||"system-ui, sans-serif",c=r.bodyFont||"system-ui, sans-serif",u=e.voice.tagline||"Your tagline shows up here.",d=r.borderRadius||"10px";return a.jsxs("div",{className:"rounded-xl border bg-secondary/20 p-3",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:"Live preview"}),a.jsxs("div",{className:"rounded-lg p-4 ring-1 ring-border/40",style:{background:i,color:o,borderRadius:d},children:[a.jsx("p",{className:"text-[10px] uppercase tracking-[0.18em] font-semibold opacity-70 mb-2",style:{color:n},children:t||"Brand"}),a.jsx("h3",{className:"text-lg font-bold leading-tight",style:{fontFamily:l,color:o},children:"The quick brown fox jumps."}),a.jsx("p",{className:"text-[12.5px] mt-1.5 leading-snug opacity-90",style:{fontFamily:c,color:o},children:u}),a.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[a.jsx("span",{className:"px-2.5 py-1 rounded text-[11px] font-medium",style:{background:n,color:i,borderRadius:d},children:"Primary"}),a.jsx("span",{className:"px-2.5 py-1 rounded text-[11px] font-medium",style:{background:s,color:o,borderRadius:d},children:"Accent"})]})]}),a.jsx("div",{className:"flex items-center gap-1 mt-2.5",children:[r.primaryColor,r.secondaryColor,r.accentColor,r.backgroundColor,r.textColor].map((p,h)=>p?a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-3 h-3 rounded-full ring-1 ring-border/60",
1308style:{background:p}}),a.jsx("span",{className:"text-[9px] font-mono text-muted-foreground",children:p})]},h):null)})]})}function kE({hideOwnHeader:e}={}){const{project:t}=gn(),r=(t==null?void 0:t.id)||null,{guidelines:n,activeGuideline:s,loading:i,save:o,remove:l,reload:c}=NE(r,t==null?void 0:t.ownerUserId),[u,d]=m.useState(null),[p,h]=m.useState("Brand Guidelines"),[f,x]=m.useState(r?"project":"account"),[g,y]=m.useState(!r),[b,v]=m.useState({visual:{},voice:{},components:{},rules:{}}),[k,N]=m.useState(!1),[j,w]=m.useState(!1),[S,T]=m.useState(""),[C,A]=m.useState(!1);m.useEffect(()=>{u&&(h(u.name),x(u.project_id?"project":"account"),y(u.is_default),v(u.guidelines))},[u]);const P=async()=>{N(!0),await o(b,{name:p,projectId:f==="project"?r:null,sourceType:"form",isDefault:g,id:u==null?void 0:u.id}),W.success("Brand guidelines saved"),N(!1),d(null)},E=async O=>{if(O){w(!0);try{const ne=new FormData;ne.append("file",O);const oe=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/parse-brand-guidelines",{method:"POST",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"},body:ne});if(!oe.ok)throw new Error("Parse failed");const he=await oe.json();he.guidelines&&(v(he.guidelines),h(he.name||O.name.replace(/\.[^.]+$/,"")),W.success("Brand guidelines extracted from document"))}catch{W.error("Failed to parse document")}w(!1)}},_=async()=>{if(S.trim()){w(!0);try{const O=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/parse-brand-guidelines",{method:"POST",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo","Content-Type":"application/json"},body:JSON.stringify({url:S.trim()})});if(!O.ok)throw new Error("Parse failed");const ne=await O.json();ne.guidelines&&(v(ne.guidelines),h(ne.name||"Imported Brand Guidelines"),W.success("Brand guidelines extracted from URL"))}catch{W.error("Failed to parse URL")}w(!1),T("")}},I=async()=>{A(!0);try{const O=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/parse-brand-guidelines",{method:"POST",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo","Content-Type":"application/json"},body:JSON.stringify({mode:"interview",existingData:b})});if(!O.ok)throw new Error("Failed");(await O.json()).questions&&W.info("AI interview coming soon — use the form to fill in details")}catch{W.error("AI interview unavailable")}A(!1)},D=()=>{d(null),h("Brand Guidelines"),x("project"),y(!1),v({visual:{},voice:{},components:{},rules:{}})},M=(O,ne)=>v(oe=>({...oe,visual:{...oe.visual,[O]:ne}})),B=(O,ne)=>v(oe=>({...oe,voice:{...oe.voice,[O]:ne}})),$=(O,ne)=>v(oe=>({...oe,components:{...oe.components,[O]:ne}})),K=(O,ne)=>v(oe=>({...oe,rules:{...oe.rules,[O]:ne}}));if(i)return a.jsx("div",{className:"h-full flex items-center justify-center text-muted-foreground text-sm",children:"Loading..."});const R=u!==null||n.length===0,Y=!!r&&!!s&&!s.project_id,Z=!s;return a.jsx($r,{className:"h-full",children:a.jsxs("div",{className:"p-4 space-y-4",children:[r&&Y&&a.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/[0.04] px-3 py-2.5 flex items-start gap-2.5",children:[a.jsx(Ai,{className:"w-3.5 h-3.5 text-primary mt-0.5 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0 text-[12px] leading-snug",children:[a.jsx("p",{className:"font-medium text-foreground",children:"Using your Common Brand"}),a.jsxs("p",{className:"text-muted-foreground mt-0.5",children:["This project doesn't have its own brand yet, so the AI is using ",a.jsx("span",{className:"font-medium text-foreground",children:(s==null?void 0:s.name)||"your default"}),". Click ",a.jsx("span",{className:"font-medium text-foreground",children:"New"})," to override it for this project only."]})]})]}),r&&Z&&!R&&a.jsx("div",{className:"rounded-lg border border-dashed bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground leading-snug",children:a.jsxs("p",{children:["No brand set for this project or your account. The AI will use generic defaults. Set a ",a.jsx("span",{className:"font-medium text-foreground",children:"Common Brand"})," on the home page to apply across all projects."]})}),!e&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Brand Guidelines"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:r?"Set a project-specific brand or fall back to your Common Brand.":"Define your default brand identity for AI-powered builds across all projects."})]}),!R&&a.jsxs(Q,{size:"sm",variant:"outline",onClick:D,className:"gap-1.5 text-xs",children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," New"]})]}),e&&!R&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Q,{size:"sm",variant:"outline",onClick:D,className:"gap-1.5 text-xs",children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," New brand"]})}),!R&&n.length>0&&a.jsx("div",{className:"space-y-2",children:n.map(O=>a.jsxs(f$,{className:L("cursor-pointer transition-colors",(s==null?void 0:s.id)===O.id&&"ring-2 ring-primary/50"),children:[a.jsx(m$,{className:"p-3 pb-1",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(g$,{className:"text-xs font-medium flex items-center gap-1.5",children:[a.jsx(Ai,{className:"w-3.5 h-3.5 text-primary"}),O.name,O.is_default&&a.jsx(Ge,{variant:"secondary",className:"text-[9px] px-1.5",children:"Default"})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:O.project_id?"Project":"Account"}),a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:O.source_type})]})]})}),a.jsxs(x$,{className:"p-3 pt-1",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[O.guidelines.visual.primaryColor&&a.jsx("div",{className:"flex gap-1",children:[O.guidelines.visual.primaryColor,O.guidelines.visual.secondaryColor,O.guidelines.visual.accentColor].filter(
1308Boolean).map((ne,oe)=>a.jsx("div",{className:"w-5 h-5 rounded-full border border-input",style:{backgroundColor:ne}},oe))}),O.guidelines.voice.tone&&a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Tone: ",O.guidelines.voice.tone]})]}),a.jsxs("div",{className:"flex gap-1.5",children:[a.jsx(Q,{size:"sm",variant:"outline",onClick:()=>d(O),className:"h-7 text-[10px] gap-1",children:"Edit"}),a.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>{l(O.id),W.success("Deleted")},className:"h-7 text-[10px] gap-1 text-destructive hover:text-destructive",children:a.jsx(oa,{className:"w-3 h-3"})})]})]})]},O.id))}),(R||u)&&a.jsxs("div",{className:"space-y-4",children:[a.jsx(n8,{data:b,name:p}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11.5px]",children:[a.jsx("span",{className:"text-muted-foreground font-medium mr-1",children:"Quick import:"}),a.jsxs("label",{className:"cursor-pointer",children:[a.jsx("input",{type:"file",accept:".pdf,.docx,.doc,.txt,.md",className:"hidden",onChange:O=>{var ne;return((ne=O.target.files)==null?void 0:ne[0])&&E(O.target.files[0])}}),a.jsxs("span",{className:L("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md border bg-card hover:bg-secondary/60 transition-colors",j&&"opacity-50 pointer-events-none"),children:[a.jsx(X_,{className:"w-3 h-3 text-muted-foreground"}),j?"Parsing…":"Upload doc"]})]}),a.jsxs(Q,{variant:"outline",size:"sm",onClick:I,disabled:C,className:"h-7 px-2.5 gap-1.5 text-[11.5px] font-normal",children:[a.jsx(ri,{className:"h-4 w-4"}),C?"Loading…":"Studio Jungle AI interview"]}),a.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-[200px]",children:[a.jsx(Cn,{value:S,onChange:O=>T(O.target.value),placeholder:"https://brand.example.com",className:"h-7 text-[11.5px] flex-1"}),a.jsxs(Q,{size:"sm",variant:"outline",onClick:_,disabled:!S.trim()||j,className:"h-7 text-[11.5px] shrink-0 gap-1 px-2",children:[a.jsx(Br,{className:"w-3 h-3"})," URL"]})]})]}),a.jsxs("div",{className:L("grid gap-2",r?"grid-cols-2":"grid-cols-1"),children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Name"}),a.jsx(Cn,{value:p,onChange:O=>h(O.target.value),className:"h-8 text-xs mt-1"})]}),r&&a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Scope"}),a.jsxs(Ns,{value:f,onValueChange:O=>x(O),children:[a.jsx(hs,{className:"h-8 text-xs mt-1",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"project",className:"text-xs",children:"This Project"}),a.jsx(Dt,{value:"account",className:"text-xs",children:"All Projects (Common Brand)"})]})]})]})]}),a.jsxs($5,{defaultValue:"visual",className:"w-full",children:[a.jsxs(Gw,{className:"w-full h-8 grid grid-cols-4",children:[a.jsxs(Wo,{value:"visual",className:"text-[10px] gap-1",children:[a.jsx(Ai,{className:"w-3 h-3"})," Visual"]}),a.jsxs(Wo,{value:"voice",className:"text-[10px] gap-1",children:[a.jsx(Tp,{className:"w-3 h-3"})," Voice"]}),a.jsxs(Wo,{value:"components",className:"text-[10px] gap-1",children:[a.jsx(kT,{className:"w-3 h-3"})," Components"]}),a.jsxs(Wo,{value:"rules",className:"text-[10px] gap-1",children:[a.jsx(el,{className:"w-3 h-3"})," Rules"]})]}),a.jsxs(Vo,{value:"visual",className:"space-y-3 mt-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsx(Ed,{label:"Primary",value:b.visual.primaryColor,onChange:O=>M("primaryColor",O)}),a.jsx(Ed,{label:"Secondary",value:b.visual.secondaryColor,onChange:O=>M("secondaryColor",O)}),a.jsx(Ed,{label:"Accent",value:b.visual.accentColor,onChange:O=>M("accentColor",O)}),a.jsx(Ed,{label:"Background",value:b.visual.backgroundColor,onChange:O=>M("backgroundColor",O)}),a.jsx(Ed,{label:"Text",value:b.visual.textColor,onChange:O=>M("textColor",O)})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Heading Font"}),a.jsx(Cn,{value:b.visual.headingFont||"",onChange:O=>M("headingFont",O.target.value),placeholder:"e.g. Playfair Display",className:"h-8 text-xs mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Body Font"}),a.jsx(Cn,{value:b.visual.bodyFont||"",onChange:O=>M("bodyFont",O.target.value),placeholder:"e.g. Source Sans Pro",className:"h-8 text-xs mt-1"})]})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Logo URL"}),a.jsx(Cn,{value:b.visual.logoUrl||"",onChange:O=>M("logoUrl",O.target.value),placeholder:"https://...",className:"h-8 text-xs mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Imagery Style"}),a.jsx(Cd,{value:b.visual.imageryStyle||"",onChange:O=>M("imageryStyle",O.target.value),placeholder:"e.g. Minimalist photography, warm tones, natural light",className:"text-xs min-h-[60
1308px]"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Border Radius"}),a.jsxs(Ns,{value:b.visual.borderRadius||"",onValueChange:O=>M("borderRadius",O),children:[a.jsx(hs,{className:"h-8 text-xs mt-1",children:a.jsx(ks,{placeholder:"Choose..."})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"none",className:"text-xs",children:"Sharp (0px)"}),a.jsx(Dt,{value:"sm",className:"text-xs",children:"Small (4px)"}),a.jsx(Dt,{value:"md",className:"text-xs",children:"Medium (8px)"}),a.jsx(Dt,{value:"lg",className:"text-xs",children:"Large (12px)"}),a.jsx(Dt,{value:"xl",className:"text-xs",children:"XL (16px)"}),a.jsx(Dt,{value:"full",className:"text-xs",children:"Full/Pill"})]})]})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Spacing"}),a.jsxs(Ns,{value:b.visual.spacing||"",onValueChange:O=>M("spacing",O),children:[a.jsx(hs,{className:"h-8 text-xs mt-1",children:a.jsx(ks,{placeholder:"Choose..."})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"compact",className:"text-xs",children:"Compact"}),a.jsx(Dt,{value:"comfortable",className:"text-xs",children:"Comfortable"}),a.jsx(Dt,{value:"spacious",className:"text-xs",children:"Spacious"})]})]})]})]})]}),a.jsxs(Vo,{value:"voice",className:"space-y-3 mt-3",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Brand Tone"}),a.jsx(Cd,{value:b.voice.tone||"",onChange:O=>B("tone",O.target.value),placeholder:"e.g. Warm, approachable, empowering",className:"text-xs min-h-[60px] mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Formality"}),a.jsxs(Ns,{value:b.voice.formality||"",onValueChange:O=>B("formality",O),children:[a.jsx(hs,{className:"h-8 text-xs mt-1",children:a.jsx(ks,{placeholder:"Choose..."})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"casual",className:"text-xs",children:"Casual"}),a.jsx(Dt,{value:"neutral",className:"text-xs",children:"Neutral"}),a.jsx(Dt,{value:"formal",className:"text-xs",children:"Formal"}),a.jsx(Dt,{value:"professional",className:"text-xs",children:"Professional"})]})]})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Writing Style"}),a.jsx(Cd,{value:b.voice.writingStyle||"",onChange:O=>B("writingStyle",O.target.value),placeholder:"e.g. Short sentences, active voice, benefit-focused",className:"text-xs min-h-[60px] mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Tagline"}),a.jsx(Cn,{value:b.voice.tagline||"",onChange:O=>B("tagline",O.target.value),placeholder:"e.g. Build faster, ship smarter",className:"h-8 text-xs mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Preferred Vocabulary"}),a.jsx(Td,{value:b.voice.vocabulary||[],onChange:O=>B("vocabulary",O),placeholder:"Add a word..."})]})]}),a.jsxs(Vo,{value:"components",className:"space-y-3 mt-3",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Button Style"}),a.jsx(Cd,{value:b.components.buttonStyle||"",onChange:O=>$("buttonStyle",O.target.value),placeholder:"e.g. Rounded, filled primary color, bold text, subtle shadow",className:"text-xs min-h-[60px] mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Card Style"}),a.jsx(Cd,{value:b.components.cardStyle||"",onChange:O=>$("cardStyle",O.target.value),placeholder:"e.g. White background, thin border, soft shadow, rounded-xl",className:"text-xs min-h-[60px] mt-1"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Navigation Pattern"}),a.jsxs(Ns,{value:b.components.navPattern||"",onValueChange:O=>$("navPattern",O),children:[a.jsx(hs,{className:"h-8 text-xs mt-1",children:a.jsx(ks,{placeholder:"Choose..."})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"top-bar",className:"text-xs",children:"Top Navigation Bar"}),a.jsx(Dt,{value:"sidebar",className:"text-xs",children:"Side Navigation"}),a.jsx(Dt,{value:"hamburger",className:"text-xs",children:"Hamburger Menu"}),a.jsx(Dt,{value:"bottom-tabs",className:"text-xs",children:"Bottom Tab Bar"})]})]})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Icon Style"}),a.jsxs(Ns,{value:b.components.iconStyle||"",onValueChange:O=>$("iconStyle",O),children:[a.jsx(hs,{className:"h-8 text-xs mt-1",children:a.jsx(ks,{placeholder:"Choose..."})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"outline",className:"text-xs",children:"Outline (Lucide-style)"}),a.jsx(Dt,{value:"filled",className:"text-xs",children:"Filled / Solid"}),a.jsx(Dt,{value:"duotone",className:"text-xs",children:"Duotone"}),a.jsx(Dt,{value:"minimal",className:"text-xs",children:"Minimal / Line"})]})]})]})]}),a.jsxs(Vo,{value:"rules",className:"space-y-3 mt-3",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs font-medium text-green-600",children:"Do's"}),a.jsx(Td,{value:b.rules.dos||[],onChange:O=>K("dos",O),placeholder:"e.g. Always use brand colors"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs font-medium text-destructive",children:"Don'ts"}),a.jsx(Td,{value:b.rules.donts||[],onChange:O=>K("donts",O),placeholder:"e.g. Never use comic sans"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs font-medium text-orange-600",children:"Banned Words"}),a.jsx(Td,{value:b.rules.bannedWords||[],onChange:O=>K("bannedWords",O),placeholder:"e.g. cheap, basic"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs font-medium",children:"Required Disclaimers"}),a.jsx(Td,{value:b.rules.disclaimers||[],onChange:O=>K("disclaimers",O),placeholder:"e.g. © 2024 Company Name"})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[a.jsxs(Q,{onClick:P,disabled:k,className:"gap-1.5 text-xs flex-1",children:[a.jsx(Kg,{className:"w-3.5 h-3.5"}),k?"Saving...":u?"Update":"Save Guidelines"]}),a.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>y(!g),className:L("gap-1 text-xs",g&&"text-yellow-600"),children:[g?a.jsx(jT,{className:"w-3.5 h-3.5 fill-current"}):a.jsx(N6,{className:"w-3.5 h-3.5"}),"Default"]}),u&&a.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{d(null),D()},className:"text-xs",children:"Cancel"})]})]})]})})}function r8(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function s8(e){const t=new TextEncoder().encode(e);let r="";return t.forEach(n=>{r+=String.fromCharCode(n)}),`data:image/svg+xml;base64,${btoa(r)}`}
1308function a8(e){const t=(e||"A").trim(),r=t.split(/\s+/).slice(0,2).map(d=>{var p;return((p=d[0])==null?void 0:p.toUpperCase())||""}).join("")||"A";let n=0;for(let d=0;d<t.length;d++)n=(n<<5)-n+t.charCodeAt(d)|0;const s=[{bg:"#0f3d2e",fg:"#d7f7c2",accent:"#f2c94c"},{bg:"#173b31",fg:"#b8ead5",accent:"#8ee3a4"},{bg:"#273f24",fg:"#fce8b2",accent:"#ffb86b"},{bg:"#102f3a",fg:"#b8f2e6",accent:"#7cc7ff"},{bg:"#2e294e",fg:"#f5e7ff",accent:"#9bf6c5"},{bg:"#3a241f",fg:"#fff1cf",accent:"#f4a261"}],i=s[Math.abs(n)%s.length],o=Math.abs(n)%4,l=[`<path d="M14 47C23 24 41 20 50 13" fill="none" stroke="${i.accent}" stroke-width="3.5" stroke-linecap="round"/><circle cx="48" cy="15" r="4" fill="${i.accent}"/>`,`<rect x="9" y="42" width="46" height="4" rx="2" fill="${i.accent}" opacity=".9"/><circle cx="18" cy="20" r="3" fill="${i.accent}"/><circle cx="46" cy="24" r="3" fill="${i.accent}"/>`,`<path d="M15 18h34v28H15z" fill="none" stroke="${i.accent}" stroke-width="3" rx="8"/><path d="M22 26h20M22 36h12" stroke="${i.accent}" stroke-width="3" stroke-linecap="round"/>`,`<path d="M32 9l5.4 13.7L52 28l-14.6 5.3L32 47l-5.4-13.7L12 28l14.6-5.3L32 9Z" fill="none" stroke="${i.accent}" stroke-width="3" stroke-linejoin="round"/>`][o],c=r.length>1?28:36,u=`<?xml version="1.0" encoding="UTF-8"?>
1309<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
1310  <rect width="64" height="64" rx="14" fill="${i.bg}"/>
1311  <circle cx="52" cy="12" r="14" fill="${i.accent}" opacity=".16"/>
1312  ${l}
1313  <text x="32" y="42" text-anchor="middle" font-family="-apple-system, system-ui, sans-serif" font-weight="800" font-size="${c}" fill="${i.fg}">${r8(r)}</text>
1314</svg>`;return s8(u)}function i8({open:e,onOpenChange:t,projectId:r,projectName:n}){const s=nd(),i=kw(),[o,l]=m.useState({showBadge:!0,faviconUrl:null}),[c,u]=m.useState(!1),[d,p]=m.useState(""),h=m.useRef(null);m.useEffect(()=>{if(!r||!e)return;(async()=>{const{data:_}=await G.from("project_settings").select("*").eq("project_id",r).single();if(_!=null&&_.branding){const I=_.branding;l({showBadge:I.showBadge??!0,faviconUrl:I.faviconUrl??null}),p(I.faviconUrl||"")}x(!!(_!=null&&_.auto_apply_approved_builds))})()},[r,e]);const[f,x]=m.useState(!1),g=async E=>{r&&(x(E),u(!0),await G.from("project_settings").update({auto_apply_approved_builds:E}).eq("project_id",r),u(!1),Mt({title:E?"Auto-apply enabled for this project":"Auto-apply disabled — approved builds wait for review"}))},y=async E=>{if(!r)return;u(!0),l(E);const{error:_}=await G.from("project_settings").upsert({project_id:r,branding:E},{onConflict:"project_id"});if(u(!1),_){Mt({title:"Settings save failed",description:_.message,variant:"destructive"});return}Mt({title:"✅ Settings saved"})},b=()=>{const E=d.trim()||null;y({...o,faviconUrl:E})},v=()=>{p(""),y({...o,faviconUrl:null})},k=E=>{if(!E)return;if(!E.type.startsWith("image/")){Mt({title:"Choose an image file",description:"PNG, SVG, JPG, or WebP works best.",variant:"destructive"});return}if(E.size>512*1024){Mt({title:"Favicon is too large",description:"Please upload an image under 512 KB.",variant:"destructive"});return}const _=new FileReader;_.onload=()=>{const I=String(_.result||"");I&&(p(I),y({...o,faviconUrl:I}))},_.readAsDataURL(E)},[N,j]=m.useState([]),[w,S]=m.useState(!1),[T,C]=m.useState(null),A=async()=>{if(!r)return;S(!0),C(null);const{data:E,error:_}=await G.from("encrypted_project_secrets").select("id, name, detected_kind, created_at, last_used_at").eq("project_id",r).order("created_at",{ascending:!1});_?C(_.message):j(E||[]),S(!1)};m.useEffect(()=>{e&&r&&A()},[e,r]);const P=async(E,_)=>{if(!confirm(`Delete ${_}? Anything that depends on it will stop working until re-pasted.`))return;const{error:I}=await G.from("encrypted_project_secrets").delete().eq("id",E);if(I){Mt({title:"Delete failed",description:I.message,variant:"destructive"});return}j(D=>D.filter(M=>M.id!==E)),Mt({title:`${_} removed`})};return a.jsx(yo,{open:e,onOpenChange:t,children:a.jsxs(Fi,{className:"sm:max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[a.jsxs(Bi,{children:[a.jsxs(La,{className:"flex items-center gap-2",children:[a.jsx(ni,{className:"w-5 h-5 text-primary"}),"Project Settings"]}),a.jsxs(ol,{children:["Configure settings for ",a.jsx("span",{className:"font-semibold text-foreground",children:n})]})]}),a.jsxs($5,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[a.jsxs(Gw,{className:"w-full grid grid-cols-3 shrink-0",children:[a.jsxs(Wo,{value:"general",className:"text-xs gap-1.5",children:[a.jsx(ni,{className:"w-3.5 h-3.5"})," General"]}),a.jsxs(Wo,{value:"brand",className:"text-xs gap-1.5",children:[a.jsx(Ai,{className:"w-3.5 h-3.5"})," Brand"]}),a.jsxs(Wo,{value:"secrets",className:"text-xs gap-1.5",children:[a.jsx(Ep,{className:"w-3.5 h-3.5"})," Secrets",N.length>0&&a.jsx("span",{className:"ml-0.5 inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-semibold bg-primary/15 text-primary",children:N.length})]})]}),a.jsx(Vo,{value:"general",className:"flex-1 overflow-y-auto mt-0 pt-4",children:a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-3",children:[a.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Branding"}),a.jsxs("div",{className:L("flex items-center justify-between p-3 rounded-lg border bg-secondary/30",!i.features.removeBadge&&"opacity-95"),children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx("div",{className:"w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx("span",{className:"text-sm font-bold text-primary",children:"SJ"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:'"Powered by Studiojungle" badge'}),!i.features.removeBadge&&a.jsxs("span",{className:"inline-flex items-center gap-1 text-[9px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-700",children:[a.jsx(Bs,{className:"w-2.5 h-2.5"})," Pro"]})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:i.features.removeBadge?"Toggle off to hide the badge on published sites.":"Upgrade to Pro to remove the badge from published sites."})]})]}),i.features.removeBadge?a.jsx(Xl,{checked:o.showBadge,onCheckedChange:E=>y({...o,showBadge:E})}):a.jsxs(Q,{size:"sm",variant:"outline",onClick:()=>{t(!1),s("/studio/billing")},className:"gap-1.5 shrink-0",children:[a.jsx(Dn,{className:"w-3.5 h-3.5"})," Upgrade"]})]})]}),a.jsx(Ni,{}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Favicon"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("input",{ref:h,type:"file",accept:"image/png,image/jpeg,image/webp,image/svg+xml,image/x-icon",className:"hidden",onChange:E=>{var _;k((_=E.target.files)==null?void 0:_[0]),E.target.value=""}}),a.jsxs(Q,{size:"sm",variant:"ghost",onClick:()=>{var E;
1314return(E=h.current)==null?void 0:E.click()},className:"h-7 gap-1.5 text-[11.5px]",title:"Upload a favicon image",children:[a.jsx(X_,{className:"w-3 h-3"})," Upload"]}),a.jsxs(Q,{size:"sm",variant:"ghost",onClick:()=>{const E=a8(n);p(E),y({...o,faviconUrl:E})},className:"h-7 gap-1.5 text-[11.5px] text-primary hover:text-primary hover:bg-primary/10",title:"Generate a favicon from this project",children:[a.jsx(Dn,{className:"w-3 h-3"})," Generate"]})]})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Default: Studiojungle favicon. Upload your own, generate one from this project, or paste a URL."}),a.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-secondary/30",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border bg-background flex items-center justify-center overflow-hidden",children:o.faviconUrl?a.jsx("img",{src:o.faviconUrl,alt:"Favicon preview",className:"w-8 h-8 object-contain",onError:E=>{E.target.style.display="none"}}):a.jsx("img",{src:"/favicon.png",alt:"Default favicon",className:"w-8 h-8 object-contain"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs font-medium text-foreground truncate",children:o.faviconUrl?o.faviconUrl.startsWith("data:image/svg+xml")?"Generated for this project":o.faviconUrl.startsWith("data:image/")?"Uploaded image":"Custom favicon":"Studiojungle (default)"}),o.faviconUrl&&!o.faviconUrl.startsWith("data:")&&a.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:o.faviconUrl})]}),o.faviconUrl&&a.jsxs(Q,{size:"sm",variant:"ghost",onClick:v,className:"gap-1.5 text-muted-foreground hover:text-foreground",children:[a.jsx(Ri,{className:"w-3.5 h-3.5"}),"Default"]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Cn,{value:d.startsWith("data:")?"":d,onChange:E=>p(E.target.value),placeholder:"https://example.com/favicon.png",className:"text-xs h-9"}),a.jsx(Q,{size:"sm",onClick:b,disabled:c||d===(o.faviconUrl||""),className:"h-9 px-4",children:"Save"})]})]}),a.jsx(Ni,{}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Pipeline builds"}),a.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-secondary/30",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx("div",{className:"w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx("span",{className:"text-sm",children:"⚡"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Auto-apply approved builds"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"When ON, multi-agent (Pipeline) builds commit changes immediately after the Reviewer approves — no manual review step. When OFF (default), every Pipeline build waits for your review in the diff panel."})]})]}),a.jsx(Xl,{checked:f,onCheckedChange:g})]})]})]})}),a.jsx(Vo,{value:"brand",className:"flex-1 overflow-hidden mt-0",children:a.jsx("div",{className:"h-[50vh]",children:a.jsx(kE,{})})}),a.jsx(Vo,{value:"secrets",className:"flex-1 overflow-y-auto mt-0 pt-4",children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("h4",{className:"text-sm font-semibold text-foreground flex items-center gap-2",children:[a.jsx(Ep,{className:"w-3.5 h-3.5 text-primary"})," Encrypted secrets"]}),a.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["API keys you paste in chat are detected automatically, encrypted, and stored here. The AI sees only a placeholder reference (",a.jsx("code",{className:"text-[11px] px-1 py-0.5 rounded bg-foreground
1314/[0.06]",children:"[[SECRET:NAME]]"}),") — never the value. To rotate a key, delete it here and paste the new one in chat."]})]}),w&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-6",children:[a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"})," Loading…"]}),T&&a.jsx("div",{className:"text-xs text-destructive p-3 rounded-md border border-destructive/30 bg-destructive/5",children:T}),!w&&!T&&N.length===0&&a.jsx("div",{className:"text-xs text-muted-foreground p-6 rounded-md border border-dashed text-center",children:"No secrets stored yet. Paste an API key in chat to add one."}),!w&&N.length>0&&a.jsx("ul",{className:"space-y-1.5",children:N.map(E=>a.jsxs("li",{className:"flex items-center gap-3 p-3 rounded-lg border bg-secondary/20",children:[a.jsx("div",{className:"w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx(Bs,{className:"w-3.5 h-3.5 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-foreground font-mono truncate",children:E.name}),a.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[E.detected_kind&&a.jsx("span",{className:"capitalize",children:E.detected_kind.replace(/_/g," ")}),E.detected_kind&&" · ","Added ",new Date(E.created_at).toLocaleDateString(),E.last_used_at&&` · Used ${new Date(E.last_used_at).toLocaleDateString()}`]})]}),a.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>P(E.id,E.name),className:"text-destructive hover:text-destructive h-8 w-8 p-0 shrink-0",title:`Delete ${E.name}`,children:a.jsx(oa,{className:"w-3.5 h-3.5"})})]},E.id))})]})})]})]})})}function o8({projectId:e,projectName:t,open:r,onOpenChange:n}){const[s,i]=m.useState([]),[o,l]=m.useState(!1),[c,u]=m.useState(""),[d,p]=m.useState("editor"),[h,f]=m.useState(!1),[x,g]=m.useState(null),[y,b]=m.useState(!1);async function v(){l(!0);try{const{data:S,error:T}=await G.from("project_collaborators_safe").select("*").eq("project_id",e).order("invited_at",{ascending:!1});if(T)throw T;i(S||[])}catch(S){W.error("Failed to load collaborators",{description:S.message})}finally{l(!1)}}m.useEffect(()=>{r&&v()},[r,e]);async function k(){var T,C,A;const S=c.trim().toLowerCase();if(S){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S)){W.error("Invalid email");return}f(!0),g(null);try{const{data:P,error:E}=await G.functions.invoke("invite-collaborator",{body:{projectId:e,email:S,role:d}});if(E)throw E;const _=P;if(_.error)throw new Error(_.error);const I=!!((T=_.invite)!=null&&T.emailDelivered),D=((C=_.invite)==null?void 0:C.acceptUrl)||"",M=((A=_.invite)==null?void 0:A.emailError)||null;I?W.success("Invite emailed",{description:S}):W.message("Invite created — email not sent",{description:M||"Copy the accept link below to share manually."}),u(""),D&&g({url:D,emailDelivered:I,emailError:M}),v()}catch(P){W.error("Invite failed",{description:P.message})}finally{f(!1)}}}async function N(S){if(confirm("Remove this collaborator?"))try{const{error:T}=await G.from("project_collaborators").delete().eq("id",S);if(T)throw T;W.success("Removed"),v()}catch(T){W.error("Failed to remove",{description:T.message})}}function j(){x!=null&&x.url&&(navigator.clipboard.writeText(x.url),b(!0),setTimeout(()=>b(!1),1500))}function w(S){return S==="accepted"?a.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-700 dark:text-green-400",children:[a.jsx(mn,{className:"w-2.5 h-2.5"})," Accepted"]}):S==="pending"?a.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-700 dark:text-amber-400",children:[a.jsx(Lr,{className:"w-2.5 h-2.5"})," Pending"]}):a.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-red-500/15 text-red-700 dark:text-red-400",children:[a.jsx(Ar,{className:"w-2.5 h-2.5"})," Expired"]})}return a.jsx(yo,{open:r,onOpenChange:n,children:a.jsxs(Fi,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[a.jsxs(Bi,{className:"space-y-1.5",children:[a.jsxs(La,{className:"flex items-center gap-2 text-base",children:[a.jsx(tT,{className:"w-4 h-4 text-primary shrink-0"}
1314),"Share project"]}),a.jsx("p",{className:"text-[12.5px] text-foreground/70 truncate",title:t,children:t}),a.jsxs(ol,{className:"text-[11.5px] leading-snug text-muted-foreground !mt-2",children:["Collaborators get their own login. AI credits debit",a.jsx("strong",{className:"text-foreground",children:" your "}),"account, not theirs."]})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx("label",{className:"text-[10px] uppercase tracking-wider font-mono text-muted-foreground block",children:"Invite by email"}),a.jsx(Cn,{type:"email",value:c,onChange:S=>u(S.target.value),placeholder:"[email protected]",onKeyDown:S=>{S.key==="Enter"&&k()},className:"w-full"}),a.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"text-[11px] text-muted-foreground mr-1",children:"Role"}),["editor","viewer"].map(S=>{const T=S==="editor"?uc:ys,C=d===S;return a.jsxs("button",{type:"button",onClick:()=>p(S),className:L("flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium transition-colors border",C?"bg-primary/10 text-primary border-primary/30":"bg-background text-muted-foreground border-border hover:text-foreground"),children:[a.jsx(T,{className:"w-3 h-3"}),S==="editor"?"Can edit":"View only"]},S)})]}),a.jsxs("button",{onClick:k,disabled:!c.trim()||h,className:L("flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[12.5px] font-semibold transition-colors shrink-0",!c.trim()||h?"bg-muted text-muted-foreground cursor-not-allowed":"bg-primary text-primary-foreground hover:bg-primary/90"),children:[h?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(nT,{className:"w-3.5 h-3.5"}),"Send invite"]})]})]}),x&&a.jsxs("div",{className:"rounded-md border bg-muted/30 p-2.5 space-y-2 overflow-hidden",children:[a.jsx("div",{className:"flex items-start gap-1.5 text-[11.5px]",children:x.emailDelivered?a.jsxs(a.Fragment,{children:[a.jsx(mn,{className:"w-3.5 h-3.5 text-green-600 dark:text-green-400 shrink-0 mt-0.5"}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("strong",{className:"text-foreground",children:"Email sent."})," ",a.jsx("span",{className:"text-muted-foreground",children:"They can also use this link:"})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ar,{className:"w-3.5 h-3.5 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("strong",{className:"text-foreground",children:"Email didn't send."})," ",a.jsx("span",{className:"text-muted-foreground",children:"Copy this link and share it manually:"})]})]})}),a.jsxs("div",{className:"flex items-stretch gap-1.5 min-w-0",children:[a.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:a.jsx("code",{className:"block w-full font-mono text-[10.5px] bg-background rounded px-2 py-1.5 border truncate",children:x.url})}),a.jsxs("button",{onClick:j,className:"flex items-center gap-1 px-2 rounded text-[11px] font-medium bg-primary/10 text-primary hover:bg-primary/20 shrink-0",children:[y?a.jsx(Wn,{className:"w-3 h-3"}):a.jsx(gs,{className:"w-3 h-3"}),y?"Copied":"Copy"]})]})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("h4",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-mono",children:["People with access ",s.length>0&&a.jsxs("span",{className:"text-muted-foreground/70",children:["(",s.length+1,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2.5 py-2 px-2.5 rounded-md bg-muted/20",children:[a.jsx("div",{className:"w-7 h-7 rounded-full bg-primary/15 text-primary flex items-center justify-center text-[11px] font-semibold",children:"You"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-[13px]",children:"You"}),a.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Owner · pays AI credits for everyone"})]})]}),o?a.jsx("div",{className:"py-6 flex justify-center text-muted-foreground",children:a.jsx(ze,{className:"w-4 h-4 animate-spin"})}):s.length===0?a.jsx("p",{className:"text-[12px] text-muted-foreground
1314/80 py-2 px-2.5",children:"No collaborators yet. Invite someone above."}):s.map(S=>{const T=S.invited_email.slice(0,2).toUpperCase();return a.jsxs("div",{className:"flex items-center gap-2.5 py-2 px-2.5 rounded-md hover:bg-muted/30 group",children:[a.jsx("div",{className:"w-7 h-7 rounded-full bg-muted text-foreground/70 flex items-center justify-center text-[10px] font-semibold uppercase",children:T}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-[13px] truncate",children:S.invited_email}),a.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center gap-2 mt-0.5",children:[a.jsxs("span",{className:"inline-flex items-center gap-1",children:[S.role==="editor"?a.jsx(uc,{className:"w-2.5 h-2.5"}):a.jsx(ys,{className:"w-2.5 h-2.5"}),S.role==="editor"?"Can edit":"View only"]}),w(S.status)]})]}),a.jsx("button",{onClick:()=>N(S.id),className:"w-6 h-6 rounded hover:bg-destructive/10 hover:text-destructive flex items-center justify-center text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity",title:"Remove",children:a.jsx(oa,{className:"w-3 h-3"})})]},S.id)})]})]})]})})}function sr(e){const t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function fo(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function l8(e,t){const r=sr(e);return isNaN(t)?fo(e,NaN):(r.setDate(r.getDate()+t),r)}const SE=6048e5,c8=864e5,CE=6e4,PE=36e5,lf=43200,Hk=1440;let u8={};function Ph(){return u8}function fc(e,t){var l,c,u,d;const r=Ph(),n=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((d=(u=r.locale)==null?void 0:u.options)==null?void 0:d.weekStartsOn)??0,s=sr(e),i=s.getDay(),o=(i<n?7:0)+i-n;return s.setDate(s.getDate()-o),s.setHours(0,0,0,0),s}function km(e){return fc(e,{weekStartsOn:1})}function AE(e){const t=sr(e),r=t.getFullYear(),n=fo(e,0);n.setFullYear(r+1,0,4),n.setHours(0,0,0,0);const s=km(n),i=fo(e,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const o=km(i);return t.getTime()>=s.getTime()?r+1:t.getTime()>=o.getTime()?r:r-1}function Sm(e){const t=sr(e);return t.setHours(0,0,0,0),t}function Cm(e){const t=sr(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function d8(e,t){const r=Sm(e),n=Sm(t),s=+r-Cm(r),i=+n-Cm(n);return Math.round((s-i)/c8)}function p8(e){const t=AE(e),r=fo(e,0);return r.setFullYear(t,0,4),r.setHours(0,0,0,0),km(r)}function Zf(e,t){const r=sr(e),n=sr(t),s=r.getTime()-n.getTime();return s<0?-1:s>0?1:s}function Ah(e){return fo(e,Date.now())}function _E(e,t){const r=Sm(e),n=Sm(t);return+r==+n}function h8(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}
1314function f8(e){if(!h8(e)&&typeof e!="number")return!1;const t=sr(e);return!isNaN(Number(t))}function m8(e,t){const r=sr(e),n=sr(t),s=r.getFullYear()-n.getFullYear(),i=r.getMonth()-n.getMonth();return s*12+i}function g8(e){return t=>{const n=(e?Math[e]:Math.trunc)(t);return n===0?0:n}}function x8(e,t){return+sr(e)-+sr(t)}function y8(e){const t=sr(e);return t.setHours(23,59,59,999),t}function b8(e){const t=sr(e),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}function v8(e){const t=sr(e);return+y8(t)==+b8(t)}function w8(e,t){const r=sr(e),n=sr(t),s=Zf(r,n),i=Math.abs(m8(r,n));let o;if(i<1)o=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-s*i);let l=Zf(r,n)===-s;v8(sr(e))&&i===1&&Zf(e,n)===1&&(l=!1),o=s*(i-Number(l))}return o===0?0:o}function j8(e,t,r){const n=x8(e,t)/1e3;return g8(r==null?void 0:r.roundingMethod)(n)}function N8(e){const t=sr(e),r=fo(e,0);return r.setFullYear(t.getFullYear(),0,1),r.setHours(0,0,0,0),r}const k8={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},S8=(e,t,r)=>{let n;const s=k8[e];return typeof s=="string"?n=s:t===1?n=s.one:n=s.other.replace("{{count}}",t.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function Py(e){return(t={})=>{const r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}const C8={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},P8={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},A8={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},_8={date:Py({formats:C8,defaultWidth:"full"}),time:Py({formats:P8,defaultWidth:"full"}),dateTime:Py({formats:A8,defaultWidth:"full"})},T8={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},E8=(e,t,r,n)=>T8[e];function Id(e){return(t,r)=>{const n=r!=null&&r.context?String(r.context):"standalone";let s;if(n==="formatting"&&e.formattingValues){const o=e.defaultFormattingWidth||e.defaultWidth,l=r!=null&&r.width?String(r.width):o;s=e.formattingValues[l]||e.formattingValues[o]}else{const o=e.defaultWidth,l=r!=null&&r.width?String(r.width):e.defaultWidth;s=e.values[l]||e.values[o]}const i=e.argumentCallback?e.argumentCallback(t):t;return s[i]}}const I8={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},O8={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},R8={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},D8={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},M8={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},L8={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},$8=(e,t)=>
vendor: 4,458 bytes, line 1314
1314{const r=Number(e),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},F8={ordinalNumber:$8,era:Id({values:I8,defaultWidth:"wide"}),quarter:Id({values:O8,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Id({values:R8,defaultWidth:"wide"}),day:Id({values:D8,defaultWidth:"wide"}),dayPeriod:Id({values:M8,defaultWidth:"wide",formattingValues:L8,defaultFormattingWidth:"wide"})};function Od(e){return(t,r={})=>{const n=r.width,s=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],i=t.match(s);if(!i)return null;const o=i[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?U8(l,p=>p.test(o)):B8(l,p=>p.test(o));let u;u=e.valueCallback?e.valueCallback(c):c,u=r.valueCallback?r.valueCallback(u):u;const d=t.slice(o.length);return{value:u,rest:d}}}function B8(e,t){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function U8(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function z8(e){return(t,r={})=>{const n=t.match(e.matchPattern);if(!n)return null;const s=n[0],i=t.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=r.valueCallback?r.valueCallback(o):o;const l=t.slice(s.length);return{value:o,rest:l}}}const q8=/^(\d+)(th|st|nd|rd)?/i,H8=/\d+/i,W8={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},V8={any:[/^b/i,/^(a|c)/i]},G8={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},K8={any:[/1/i,/2/i,/3/i,/4/i]},Y8={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},J8={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},X8={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Z8={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Q8={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},e9={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},t9={ordinalNumber:z8({matchPattern:q8,parsePattern:H8,valueCallback:e=>parseInt(e,10)}),era:Od({matchPatterns:W8,defaultMatchWidth:"wide",parsePatterns:V8,defaultParseWidth:"any"}),quarter:Od({matchPatterns:G8,defaultMatchWidth:"wide",parsePatterns:K8,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Od({matchPatterns:Y8,defaultMatchWidth:"wide",parsePatterns:J8,defaultParseWidth:"any"}),day:Od({matchPatterns:X8,defaultMatchWidth:"wide",parsePatterns:Z8,defaultParseWidth:"any"}),dayPeriod:Od({matchPatterns:Q8,defaultMatchWidth:"any",parsePatterns:e9,defaultParseWidth:"any"})},TE={code:"en-US",formatDistance:S8,formatLong:_8,formatRelative:E8,localize:F8,match:t9,options:{weekStartsOn:0,firstWeekContainsDate:1}};function n9(e){const t=sr(e);return d8(t,N8(t))+1}function r9(e){const t=sr(e),r=+km(t)-+p8(t);return Math.round(r/SE)+1}function EE(e,t){var d,p,h,f;const r=sr(e),n=r.getFullYear(),s=Ph(),i=(t==null?void 0:t.firstWeekContainsDate)??((p=(d=t==null?void 0:t.locale)==null?void 0:d.options)==null?void 0:p.firstWeekContainsDate)??s.firstWeekContainsDate??((f=(h=s.locale)==null?void 0:h.options)==null?void 0:f.firstWeekContainsDate)??1,o=fo(e,0);o.setFullYear(n+1,0,i),o.setHours(0,0,0,0);const l=fc(o,t),c=fo(e,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const u=fc(c,t);return r.getTime()>=l.getTime()?n+1:r.getTime()>=u.getTime()?n:n-1}function s9(e,t){var l,c,u,d;const r=Ph(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??r.firstWeekContainsDate??((d=(u=r.locale)==null?void 0:u.options)==null?void 0:d.firstWeekContainsDate)??1,s=EE(e,t),i=fo(e,0);return i.setFullYear(s,0,n),i.setHours(0,0,0,0),fc(i,t)}function a9(e,t){const r=sr(e),n=+fc(r,t)-+s9(r,t);return Math.round(n/SE)+1}function ir(e,t){const r=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return r+n}
vendor: 5,448 bytes, line 1314
1314const Po={y(e,t){const r=e.getFullYear(),n=r>0?r:1-r;return ir(t==="yy"?n%100:n,t.length)},M(e,t){const r=e.getMonth();return t==="M"?String(r+1):ir(r+1,2)},d(e,t){return ir(e.getDate(),t.length)},a(e,t){const r=e.getHours()/12>=1?"pm":"am";switch(t){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(e,t){return ir(e.getHours()%12||12,t.length)},H(e,t){return ir(e.getHours(),t.length)},m(e,t){return ir(e.getMinutes(),t.length)},s(e,t){return ir(e.getSeconds(),t.length)},S(e,t){const r=t.length,n=e.getMilliseconds(),s=Math.trunc(n*Math.pow(10,r-3));return ir(s,t.length)}},Uc={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Wk={G:function(e,t,r){const n=e.getFullYear()>0?1:0;switch(t){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(e,t,r){if(t==="yo"){const n=e.getFullYear(),s=n>0?n:1-n;return r.ordinalNumber(s,{unit:"year"})}return Po.y(e,t)},Y:function(e,t,r,n){const s=EE(e,n),i=s>0?s:1-s;if(t==="YY"){const o=i%100;return ir(o,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):ir(i,t.length)},R:function(e,t){const r=AE(e);return ir(r,t.length)},u:function(e,t){const r=e.getFullYear();return ir(r,t.length)},Q:function(e,t,r){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return ir(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(e,t,r){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return ir(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(e,t,r){const n=e.getMonth();switch(t){case"M":case"MM":return Po.M(e,t);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(e,t,r){const n=e.getMonth();switch(t){case"L":return String(n+1);case"LL":return ir(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(e,t,r,n){const s=a9(e,n);return t==="wo"?r.ordinalNumber(s,{unit:"week"}):ir(s,t.length)},I:function(e,t,r){const n=r9(e);return t==="Io"?r.ordinalNumber(n,{unit:"week"}):ir(n,t.length)},d:function(e,t,r){return t==="do"?r.ordinalNumber(e.getDate(),{unit:"date"}):Po.d(e,t)},D:function(e,t,r){const n=n9(e);return t==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):ir(n,t.length)},E:function(e,t,r){const n=e.getDay();switch(t){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(e,t,r,n){const s=e.getDay(),i=(s-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return ir(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(e,t,r,n){const s=e.getDay(),i=(s-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return ir(i,t.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(e,t,r){const n=e.getDay(),s=n===0?7:n;switch(t){case"i":return String(s);case"ii":return ir(s,t.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(e,t,r){const s=e.getHours()/12>=1?"pm":"am";switch(t){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(e,t,r){const n=e.getHours();let s;switch(n===12?s=Uc.noon:n===0?s=Uc.midnight:s=n/12>
vendor: 4,269 bytes, line 1314
1314=1?"pm":"am",t){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(e,t,r){const n=e.getHours();let s;switch(n>=17?s=Uc.evening:n>=12?s=Uc.afternoon:n>=4?s=Uc.morning:s=Uc.night,t){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(e,t,r){if(t==="ho"){let n=e.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return Po.h(e,t)},H:function(e,t,r){return t==="Ho"?r.ordinalNumber(e.getHours(),{unit:"hour"}):Po.H(e,t)},K:function(e,t,r){const n=e.getHours()%12;return t==="Ko"?r.ordinalNumber(n,{unit:"hour"}):ir(n,t.length)},k:function(e,t,r){let n=e.getHours();return n===0&&(n=24),t==="ko"?r.ordinalNumber(n,{unit:"hour"}):ir(n,t.length)},m:function(e,t,r){return t==="mo"?r.ordinalNumber(e.getMinutes(),{unit:"minute"}):Po.m(e,t)},s:function(e,t,r){return t==="so"?r.ordinalNumber(e.getSeconds(),{unit:"second"}):Po.s(e,t)},S:function(e,t){return Po.S(e,t)},X:function(e,t,r){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Gk(n);case"XXXX":case"XX":return Rl(n);case"XXXXX":case"XXX":default:return Rl(n,":")}},x:function(e,t,r){const n=e.getTimezoneOffset();switch(t){case"x":return Gk(n);case"xxxx":case"xx":return Rl(n);case"xxxxx":case"xxx":default:return Rl(n,":")}},O:function(e,t,r){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Vk(n,":");case"OOOO":default:return"GMT"+Rl(n,":")}},z:function(e,t,r){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Vk(n,":");case"zzzz":default:return"GMT"+Rl(n,":")}},t:function(e,t,r){const n=Math.trunc(e.getTime()/1e3);return ir(n,t.length)},T:function(e,t,r){const n=e.getTime();return ir(n,t.length)}};function Vk(e,t=""){const r=e>0?"-":"+",n=Math.abs(e),s=Math.trunc(n/60),i=n%60;return i===0?r+String(s):r+String(s)+t+ir(i,2)}function Gk(e,t){return e%60===0?(e>0?"-":"+")+ir(Math.abs(e)/60,2):Rl(e,t)}function Rl(e,t=""){const r=e>0?"-":"+",n=Math.abs(e),s=ir(Math.trunc(n/60),2),i=ir(n%60,2);return r+s+t+i}const Kk=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},IE=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},i9=(e,t)=>{const r=e.match(/(P+)(p+)?/)||[],n=r[1],s=r[2];if(!s)return Kk(e,t);let i;switch(n){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",Kk(n,t)).replace("{{time}}",IE(s,t))},o9={p:IE,P:i9},l9=/^D+$/,c9=/^Y+$/,u9=["D","DD","YY","YYYY"];function d9(e){return l9.test(e)}function p9(e){return c9.test(e)}function h9(e,t,r){const n=f9(e,t,r);if(console.warn(n),u9.includes(e))throw new RangeError(n)}function f9(e,t,r){const n=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const m9=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,g9=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,x9=/^'([^]*?)'?$/,y9=/''/g,b9=/[a-zA-Z]/;function OE(e,t,r){var d,p,h,f;const n=Ph(),s=n.locale??TE,i=n.firstWeekContainsDate??((p=(d=n.locale)==null?void 0:d.options)==null?void 0:p.firstWeekContainsDate)??1,o=n.weekStartsOn??((f=(h=n.locale)==null?void 0:h.options)==null?void 0:f.weekStartsOn)??0,l=sr(e);if(!f8(l))throw new RangeError("Invalid time value");let c=t.match(g9).map(x=>{const g=x[0];if(g==="p"||g==="P"){const y=o9[g];return y(x,s.formatLong)}return x}).join("").match(m9).map(x=>
1314{if(x==="''")return{isToken:!1,value:"'"};const g=x[0];if(g==="'")return{isToken:!1,value:v9(x)};if(Wk[g])return{isToken:!0,value:x};if(g.match(b9))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:x}});s.localize.preprocessor&&(c=s.localize.preprocessor(l,c));const u={firstWeekContainsDate:i,weekStartsOn:o,locale:s};return c.map(x=>{if(!x.isToken)return x.value;const g=x.value;(p9(g)||d9(g))&&h9(g,t,String(e));const y=Wk[g[0]];return y(l,g,s.localize,u)}).join("")}function v9(e){const t=e.match(x9);return t?t[1].replace(y9,"'"):e}function w9(e,t,r){const n=Ph(),s=(r==null?void 0:r.locale)??n.locale??TE,i=2520,o=Zf(e,t);if(isNaN(o))throw new RangeError("Invalid time value");const l=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:o});let c,u;o>0?(c=sr(t),u=sr(e)):(c=sr(e),u=sr(t));const d=j8(u,c),p=(Cm(u)-Cm(c))/1e3,h=Math.round((d-p)/60);let f;if(h<2)return r!=null&&r.includeSeconds?d<5?s.formatDistance("lessThanXSeconds",5,l):d<10?s.formatDistance("lessThanXSeconds",10,l):d<20?s.formatDistance("lessThanXSeconds",20,l):d<40?s.formatDistance("halfAMinute",0,l):d<60?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",1,l):h===0?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",h,l);if(h<45)return s.formatDistance("xMinutes",h,l);if(h<90)return s.formatDistance("aboutXHours",1,l);if(h<Hk){const x=Math.round(h/60);return s.formatDistance("aboutXHours",x,l)}else{if(h<i)return s.formatDistance("xDays",1,l);if(h<lf){const x=Math.round(h/Hk);return s.formatDistance("xDays",x,l)}else if(h<lf*2)return f=Math.round(h/lf),s.formatDistance("aboutXMonths",f,l)}if(f=w8(u,c),f<12){const x=Math.round(h/lf);return s.formatDistance("xMonths",x,l)}else{const x=f%12,g=Math.trunc(f/12);return x<3?s.formatDistance("aboutXYears",g,l):x<9?s.formatDistance("overXYears",g,l):s.formatDistance("almostXYears",g+1,l)}}function $s(e,t){return w9(e,Ah(e),t)}function j9(e,t,r){const n=fc(e,r),s=fc(t,r);return+n==+s}function N9(e,t){const r=sr(e),n=sr(t);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()}function k9(e){return N9(e,Ah(e))}function RE(e,t){return j9(e,Ah(e),t)}function DE(e){return _E(e,Ah(e))}function S9(e,t){return l8(e,-t)}function C9(e){return _E(e,S9(Ah(e),1))}function rx(e,t){const n=T9(e);let s;if(n.date){const c=E9(n.date,2);s=I9(c.restDateString,c.year)}if(!s||isNaN(s.getTime()))return new Date(NaN);const i=s.getTime();let o=0,l;if(n.time&&(o=O9(n.time),isNaN(o)))return new Date(NaN);if(n.timezone){if(l=R9(n.timezone),isNaN(l))return new Date(NaN)}else{const c=new Date(i+o),u=new Date(0);return u.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),u.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),u}return new Date(i+o+l)}const cf={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},P9=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,A9=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,_9=/^([+-])(\d{2})(?::?(\d{2}))?$/;function T9(e){const t={},r=e.split(cf.dateTimeDelimiter);let n;if(r.length>2)return t;if(/:/.test(r[0])?n=r[0]:(t.date=r[0],n=r[1],cf.timeZoneDelimiter.test(t.date)&&(t.date=e.split(cf.timeZoneDelimiter)[0],n=e.substr(t.date.length,e.length))),n){const s=cf.timezone.exec(n);s?(t.time=n.replace(s[1],""),t.timezone=s[1]):t.time=n}return t}function E9(e,t){const r=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),n=e.match(r);if(!n)return{year:NaN,restDateString:""};const s=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?s:i*100,restDateString:e.slice((n[1]||n[2]).length)}}function I9(e,t){if(t===null)return new Date(NaN);const r=e.match(P9);if(!r)return new Date(NaN);const n=!!r[4],s=Rd(r[1]),i=Rd(r[2])-1,o=Rd(r[3]),l=Rd(r[4]),c=Rd(r[5])-1;if(n)return F9(t,l,c)?D9(t,l,c):new Date(NaN);{const u=new Date(0);return!L9(t,i,o)||!$9(t,s)?new Date(NaN):(u.setUTCFullYear(t,i,Math.max(s,o)),u)}}function Rd(e){return e?parseInt(e):1}function O9(e){const t=e.match(A9);if(!t)return NaN;const r=Ay(t[1]),n=Ay(t[2]),s=Ay(t[3]);return B9(r,n,s)?r*PE+n*CE+s*1e3:NaN}function Ay(e){return e&&parseFloat(e.replace(",","."))||0}function R9(e){if(e==="Z")return 0;const t=e.match(_9);if(!t)return 0;
1314const r=t[1]==="+"?-1:1,n=parseInt(t[2]),s=t[3]&&parseInt(t[3])||0;return U9(n,s)?r*(n*PE+s*CE):NaN}function D9(e,t,r){const n=new Date(0);n.setUTCFullYear(e,0,4);const s=n.getUTCDay()||7,i=(t-1)*7+r+1-s;return n.setUTCDate(n.getUTCDate()+i),n}const M9=[31,null,31,30,31,30,31,31,30,31,30,31];function ME(e){return e%400===0||e%4===0&&e%100!==0}function L9(e,t,r){return t>=0&&t<=11&&r>=1&&r<=(M9[t]||(ME(e)?29:28))}function $9(e,t){return t>=1&&t<=(ME(e)?366:365)}function F9(e,t,r){return t>=1&&t<=53&&r>=0&&r<=6}function B9(e,t,r){return e===24?t===0&&r===0:r>=0&&r<60&&t>=0&&t<60&&e>=0&&e<25}function U9(e,t){return t>=0&&t<=59}function Yw(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1),[i,o]=m.useState(new Set),l=m.useCallback(async()=>{if(!e)return;s(!0);const{data:h}=await G.from("build_logs").select("*").eq("project_id",e).order("started_at",{ascending:!1}).limit(100),f=h||[];if(r(f),f.length>0)try{const x=f.map(b=>b.id),{data:g}=await G.from("build_snapshots").select("build_log_id").in("build_log_id",x),y=new Set((g||[]).map(b=>b.build_log_id));o(y)}catch(x){console.warn("[useBuildLogs] could not fetch snapshot index:",x)}else o(new Set);s(!1)},[e]),c=m.useCallback(async h=>{if(!e)return null;const{data:f}=await G.auth.getUser();if(!(f!=null&&f.user))return null;const{data:x,error:g}=await G.from("build_logs").insert({project_id:e,user_id:f.user.id,prompt:h.prompt,model_used:h.model_used||null,provider:h.provider||null,mode:h.mode||"app-builder",use_orchestration:h.use_orchestration||!1,status:"running",started_at:new Date().toISOString()}).select().single();return g?(console.error("Failed to create build log:",g),null):x||null},[e]),u=m.useCallback(async(h,f)=>{const x=new Date().toISOString(),{error:g}=await G.from("build_logs").update({status:f.status,files_generated:f.files_generated||0,file_names:f.file_names||[],plan_steps:f.plan_steps||[],error_message:f.error_message||null,ai_response_preview:f.ai_response_preview||null,model_used:f.model_used||null,orchestration_phases:f.orchestration_phases||null,duration_ms:f.duration_ms||null,completed_at:x}).eq("id",h);g&&console.error("Failed to complete build log:",g)},[]),d=m.useCallback(async(h,f)=>{if(!e)return;const x=LE(f.files),{error:g}=await G.from("build_snapshots").insert({build_log_id:h,project_id:e,files:x,apis:f.apis||[],schema_data:f.schema||{}});g&&console.error("Failed to save build snapshot:",g)},[e]),p=m.useCallback(async h=>{try{const f=G.from("build_snapshots").select("*").eq("build_log_id",h).maybeSingle(),x=await Promise.race([f,new Promise((g,y)=>setTimeout(()=>y(new Error("loadSnapshot timed out after 10s")),1e4))]);return x!=null&&x.error?(console.error("[loadSnapshot] supabase error:",x.error),null):(x==null?void 0:x.data)||null}catch(f){return console.error("[loadSnapshot] threw:",f),null}},[]);return{logs:t,loading:n,loadLogs:l,createLog:c,completeLog:u,saveSnapshot:d,loadSnapshot:p,snapshotIds:i}}function LE(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"?r.push({name:n.name,path:s,content:n.content||null}):n.type==="folder"&&n.children&&r.push(...LE(n.children,s))}return r}function z9(e){const t=[];for(const r of e){const n=(r.path||r.name).split("/").filter(Boolean);let s=t;for(let i=0;i<n.length;i++){const o=n[i];if(i===n.length-1){const l=s.find(c=>c.type==="file"&&c.name===o);l?l.content=r.content||void 0:s.push({name:o,type:"file",content:r.content||void 0})}else{let l=s.find(c=>c.type==="folder"&&c.name===o);l||(l={name:o,type:"folder",children:[]},s.push(l)),s=l.children||[]}}}return t}function q9({projectId:e,onClose:t}){const{logs:r,loading:n,loadLogs:s,loadSnapshot:i,snapshotIds:o}=Yw(e),{setFiles:l,setPreviewHtml:c,setGeneratedPages:u,setGeneratedBlockCount:d,setActivePageId:p,setApis:h,setSchema:f,saveProjectApis:x,saveProjectSchema:g}=gn(),[y,b]=m.useState(null),[v,k]=m.useState(null),[N,j]=m.useState({});m.useEffect(()=>{s()},[s]);const w=m.useCallback(async C=>{if(y===C){b(null);return}if(b(C),!N[C]){const A=await i(C);A&&j(P=>({...P,[C]:A.files||[]}))}},[y,N,i]),S=m.useCallback(async C=>{var A,P;if(C.status==="running"){W.error("Build still running",{description:"Wait for the build to finish, then restore."});return}if(!o.has(C.id)){W.error("No snapshot for this version",{description:"Older builds + failed/incomplete builds don’t have a snapshot. Pick a green-check version."});return}k(C.id);try{const E=await i(C.id);if(!E||!E.files||E.files.length===0){W.error("Snapshot returned empty",{description:"The snapshot exists but has no files. Try a different version."}),k(null);return}const _=z9(E.files),I=E.files.map(R=>{var O;const Y=R.path||R.name||"",Z=Y.includes(".")&&((O=Y.split(".").pop())==null?void 0:O.toLowerCase())||"text";return{name:Y.split("/").pop()||Y,path:Y,content:R.content||"",language:R.language||(Z==="htm"?"html":Z)}}).filter(R=>R.path);if(e&&(await G.from("project_files").delete().eq("project_id",e),I.length>0)){const{error:R}=await G.from("project_files").insert(I.map(Y=>({project_id:e,name:Y.name,path:Y.path,content:Y.content||null,language:Y.language||null})));if(R)throw R}const D=I.filter(R=>["html","tsx","jsx","css"].includes(String(R.language||"").toLowerCase())).map(R=>({filename:R.path,language:String(R.language||"text").toLowerCase(),content:R.content})),M=id(D);
1314l(_),d(I.length),u(M),p(((A=M[0])==null?void 0:A.id)||null),c(((P=M[0])==null?void 0:P.html)||null);const B=Array.isArray(E.apis)?E.apis:[],$=E.schema_data,K=$&&Array.isArray($.tables)?{tables:$.tables,relationships:Array.isArray($.relationships)?$.relationships:[]}:{tables:[],relationships:[]};if(h(B),f(K),await x(B),await g(K),e&&I.length>0)try{await Pr({action:"apply",projectId:e,files:I.map(R=>({path:R.path,content:R.content})),manifest:I.map(R=>R.path)})}catch(R){console.warn("[restore] explicit sandbox sync failed (watcher will retry):",R)}W.success(`Restored to v${r.indexOf(C)>=0?r.length-r.indexOf(C):"?"}`,{description:`Restored ${E.files.length} files from "${C.prompt.slice(0,50)}..."`}),t()}catch(E){W.error("Restore failed",{description:E.message})}finally{k(null)}},[i,r,e,x,g,p,h,l,d,u,c,f,t,o]),T=C=>{switch(C){case"completed":return{icon:mn,color:"text-emerald-500",bg:"bg-emerald-500/10",label:"Success"};case"failed":return{icon:Ar,color:"text-destructive",bg:"bg-destructive/10",label:"Failed"};case"running":return{icon:ze,color:"text-primary",bg:"bg-primary/10",label:"Running",animate:!0};case"empty":return{icon:Ar,color:"text-amber-500",bg:"bg-amber-500/10",label:"Empty Response"};default:return{icon:Lr,color:"text-muted-foreground",bg:"bg-muted",label:C}}};return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6",children:[a.jsx("div",{className:"absolute inset-0 bg-background/60 backdrop-blur-sm",onClick:t}),a.jsxs("div",{className:"relative w-full max-w-2xl h-[calc(100vh-2rem)] sm:h-[calc(100vh-3rem)] max-h-[860px] bg-card border rounded-2xl shadow-2xl overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between px-6 py-4 border-b bg-card",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center",children:a.jsx(_p,{className:"w-4.5 h-4.5 text-primary"})}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-base font-semibold",children:"Version History"}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.length," build",r.length!==1?"s":""," recorded"]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Q,{variant:"ghost",size:"sm",onClick:s,disabled:n,className:"h-8",children:[a.jsx(zr,{className:L("w-3.5 h-3.5 mr-1.5",n&&"animate-spin")}),"Refresh"]}),a.jsx("button",{onClick:t,className:"p-1.5 rounded-lg hover:bg-secondary text-muted-foreground hover:text-foreground transition-colors",children:a.jsx(qn,{className:"w-4.5 h-4.5"})})]})]}),a.jsx($r,{className:"flex-1 min-h-0",children:n&&r.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[a.jsx(ze,{className:"w-6 h-6 animate-spin text-muted-foreground mb-3"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading build history..."})]}):r.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[a.jsx("div",{className:"w-12 h-12 rounded-full bg-muted flex items-center justify-center mb-3",children:a.jsx(_p,{className:"w-6 h-6 text-muted-foreground/40"})}),a.jsx("p",{className:"text-sm font-medium",children:"No builds yet"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send a prompt to start building. Your version history will appear here."})]}):a.jsx("div",{className:"py-2",children:r.map((C,A)=>{const P=r.length-A,E=T(C.status),_=E.icon,I=y===C.id,D=v===C.id,M=N[C.id],B=C.status!=="running"&&o.has(C.id);return a.jsx("div",{className:"px-3",children:a.jsxs("div",{className:L("rounded-xl border transition-all",I?"bg-secondary/30 border-border mb-2":"border-transparent hover:bg-secondary/20 mb-0.5"),children:[a.jsxs("button",{onClick:()=>w(C.id),className:"w-full flex items-start gap-3 px-4 py-3 text-left",children:[a.jsx("div",{className:L("mt-0.5 shrink-0 w-7 h-7 rounded-lg flex items-center justify-center",E.bg),children:a.jsx(_,{className:L("w-3.5 h-3.5",E.color,E.animate&&"animate-spin")})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("span",{className:"text-sm font-medium text-foreground line-clamp-2 flex-1",children:C.prompt}),a.jsxs("span",{className:"text-xs font-mono text-muted-foreground
1314/50 shrink-0",children:["v",P]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("span",{className:"text-[11px] text-muted-foreground",children:$s(new Date(C.started_at),{addSuffix:!0})}),C.files_generated>0&&a.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5",children:[a.jsx(Nu,{className:"w-3 h-3"}),C.files_generated," files"]}),C.duration_ms&&a.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[(C.duration_ms/1e3).toFixed(1),"s"]}),C.use_orchestration&&a.jsxs(Ge,{variant:"secondary",className:"text-[9px] px-1.5 py-0 h-4",children:[a.jsx(tl,{className:"w-2.5 h-2.5 mr-0.5"}),"Pipeline"]})]}),C.status==="failed"&&C.error_message&&a.jsxs("p",{className:"text-[11px] text-destructive mt-1.5 line-clamp-1",children:["⚠️ ",C.error_message]})]}),a.jsxs("div",{className:"mt-1 shrink-0 flex items-center gap-0.5",children:[a.jsx("span",{role:"button",tabIndex:0,onClick:$=>{$.stopPropagation(),B&&!D&&S(C)},onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),$.stopPropagation(),B&&!D&&S(C))},className:L("p-1 rounded hover:bg-secondary text-muted-foreground hover:text-primary transition-colors cursor-pointer",(!B||D)&&"opacity-30 pointer-events-none"),title:B?`Restore v${P} — replaces current files with this snapshot`:C.status==="running"?"Build still running":"No snapshot — older build",children:D?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(Ri,{className:"w-3.5 h-3.5"})}),I?a.jsx(Yr,{className:"w-4 h-4 text-muted-foreground"}):a.jsx(ia,{className:"w-4 h-4 text-muted-foreground"})]})]}),I&&a.jsxs("div",{className:"px-4 pb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:"Status"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(_,{className:L("w-3.5 h-3.5",E.color)}),a.jsx("span",{className:"text-sm font-medium",children:E.label})]})]}),a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:"Duration"}),a.jsx("p",{className:"text-sm font-medium",children:C.duration_ms?`${(C.duration_ms/1e3).toFixed(1)}s`:"—"})]})]}),a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:"Timestamp"}),a.jsx("p",{className:"text-xs text-foreground",children:OE(new Date(C.started_at),"MMM d, yyyy h:mm:ss a")})]}),C.error_message&&a.jsxs("div",{className:"bg-destructive/5 border border-destructive/20 rounded-lg p-3",children:[a.jsxs("p",{className:"text-[10px] text-destructive uppercase tracking-wider mb-1 flex items-center gap-1",children:[a.jsx(Ar,{className:"w-3 h-3"}),"Error Details"]}),a.jsx("p",{className:"text-xs text-destructive/90 whitespace-pre-wrap",children:C.error_message})]}),C.orchestration_phases&&C.orchestration_phases.length>0&&a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsxs("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2 flex items-center gap-1",children:[a.jsx(Yg,{className:"w-3 h-3"}),"Build Phases"]}),a.jsx("div",{className:"space-y-1",children:C.orchestration_phases.map(($,K)=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("div",{className:L("w-1.5 h-1.5 rounded-full",$.status==="done"?"bg-emerald-500":$.status==="error"?"bg-destructive":"bg-muted-foreground/30")}),a.jsx("span",{className:"text-muted-foreground",children:$.label||$.title||`Phase ${K+1}`})]},K))})]}),C.plan_steps&&C.plan_steps.length>0&&a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2",children:"Build Plan"}),a.jsx("div",{className:"space-y-1",children:C.plan_steps.map(($,K)=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[$.status==="done"?a.jsx(mn,{className:"w-3 h-3 text-emerald-500"}):$.status==="error"?a.jsx(Ar,{className:"w-3 h-3 text-destructive"}
1314):a.jsx(Lr,{className:"w-3 h-3 text-muted-foreground/40"}),a.jsx("span",{className:"text-foreground",children:$.title})]},K))})]}),C.file_names&&C.file_names.length>0&&a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsxs("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2 flex items-center gap-1",children:[a.jsx(Nu,{className:"w-3 h-3"}),"Generated Files (",C.file_names.length,")"]}),a.jsx("div",{className:"grid grid-cols-2 gap-1",children:C.file_names.map(($,K)=>a.jsx("span",{className:"text-[11px] font-mono text-muted-foreground truncate",children:$},K))})]}),M&&M.length>0&&a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsxs("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-2 flex items-center gap-1",children:[a.jsx(tl,{className:"w-3 h-3"}),"Snapshot (",M.length," files)"]}),a.jsx("div",{className:"grid grid-cols-2 gap-1 max-h-32 overflow-y-auto",children:M.map(($,K)=>a.jsx("span",{className:"text-[11px] font-mono text-muted-foreground truncate",children:$.path||$.name},K))})]}),C.ai_response_preview&&a.jsxs("div",{className:"bg-card rounded-lg p-3 border",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:"AI Response Preview"}),a.jsx("p",{className:"text-xs text-muted-foreground line-clamp-4 whitespace-pre-wrap",children:C.ai_response_preview})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[a.jsxs(Q,{size:"sm",onClick:()=>S(C),disabled:D||!B,className:"h-8 text-xs",title:B?void 0:C.status==="running"?"Build still running":"No snapshot for this version",children:[D?a.jsx(ze,{className:"w-3.5 h-3.5 mr-1.5 animate-spin"}):a.jsx(Ri,{className:"w-3.5 h-3.5 mr-1.5"}),B?"Restore this version":C.status==="running"?"Build running…":"No snapshot"]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"h-8 text-xs",onClick:()=>{navigator.clipboard.writeText(C.prompt),W.success("Prompt copied")},children:[a.jsx(gs,{className:"w-3.5 h-3.5 mr-1.5"}),"Copy prompt"]})]})]})]})},C.id)})})})]})]})}const Jw="sj_system_status_window",s0="studio:status-changed",$E=10;function FE(){try{const e=localStorage.getItem(Jw);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const r=Date.now()-10*60*1e3;return t.filter(n=>n&&typeof n.ok=="boolean"&&n.ts>r)}catch{return[]}}function H9(e){try{localStorage.setItem(Jw,JSON.stringify(e.slice(-$E)))}catch{}}function BE(e){return e.length===0?"unknown":e.slice(-3).filter(s=>!s.ok).length===3?"down":e.filter(s=>!s.ok).length>=Math.ceil(e.length/2)?"degraded":"ok"}function W9(e,t){const r=FE();r.push({ok:e,ts:Date.now(),reason:t});const n=r.slice(-$E);H9(n);try{window.dispatchEvent(new CustomEvent(s0,{detail:BE(n)}))}catch{}}function UE(){return BE(FE())}function V9(e){const t=n=>{const s=n.detail;e(s)};window.addEventListener(s0,t);const r=n=>{n.key===Jw&&e(UE())};return window.addEventListener("storage",r),()=>{window.removeEventListener(s0,t),window.removeEventListener("storage",r)}}const Pm="<!--studio:error-->";function Ao(e){return e.startsWith(Pm)?e:`${Pm}
1315${e}`}function zE(e){return typeof e=="string"&&e.startsWith(Pm)}function G9(e){return zE(e)?e.slice(Pm.length).replace(/^\s*\n/,""):e}function K9(){const[e,t]=m.useState(()=>UE()),[r,n]=m.useState(!1);if(m.useEffect(()=>V9(t),[]),m.useEffect(()=>{n(!1)},[e]),e==="ok"||e==="unknown"||r)return null;const s=e==="down",i=s?"Builds are failing right now — the upstream AI service may be having an outage. Click Retry on any failed message; the studio keeps your work safe.":"Recent builds have been slow or returning empty. Try a simpler prompt, or just retry — most issues clear in a minute.";return a.jsxs("div",{role:"status",className:L("flex items-center justify-between px-4 py-1.5 text-[12px] font-medium border-b",s?"bg-destructive/10 text-destructive border-destructive/20":"bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/20"),children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(Ar,{className:"w-3.5 h-3.5 shrink-0"}),a.jsx("span",{className:"truncate",children:i})]}),a.jsx("button",{onClick:()=>n(!0),className:"shrink-0 p-1 rounded hover:bg-current/10 transition-colors","aria-label":"Dismiss status banner",children:a.jsx(qn,{
1315className:"w-3 h-3"})})]})}const Ts=5,Mp=0,mp=Number.isFinite(Mp)&&Mp>0;function qE(){return{balance:Mp,plan:"studio",monthlyGrant:Mp,trialEndsAt:null,loading:!1,error:null}}const uf=mp?qE():{balance:0,plan:null,monthlyGrant:0,trialEndsAt:null,loading:!1,error:null};function ld(){const{user:e}=Us(),[t,r]=m.useState(uf),n=m.useCallback(async()=>{if(mp){const p=qE();return r(p),p}if(!(e!=null&&e.id))return r(uf),uf;r(p=>({...p,loading:!0,error:null}));const{data:c,error:u}=await G.from("user_credits").select("balance, plan, monthly_grant, trial_ends_at").eq("user_id",e.id).maybeSingle();if(u){const p={...uf,error:u.message};return r(p),p}const d={balance:(c==null?void 0:c.balance)??0,plan:(c==null?void 0:c.plan)??null,monthlyGrant:(c==null?void 0:c.monthly_grant)??0,trialEndsAt:(c==null?void 0:c.trial_ends_at)??null,loading:!1,error:null};return r(d),d},[e==null?void 0:e.id]),s=m.useCallback(c=>{mp||r(u=>({...u,balance:c}))},[]);m.useEffect(()=>{if(n(),mp||!(e!=null&&e.id))return;const c=G.channel(`user_credits_${e.id}`).on("postgres_changes",{event:"*",schema:"public",table:"user_credits",filter:`user_id=eq.${e.id}`},d=>{const p=d.new;r(h=>({...h,balance:p.balance??h.balance,plan:p.plan??h.plan,monthlyGrant:p.monthly_grant??h.monthlyGrant,trialEndsAt:p.trial_ends_at??h.trialEndsAt}))}).subscribe(),u=setInterval(n,6e4);return()=>{clearInterval(u),G.removeChannel(c)}},[n,e==null?void 0:e.id]);const i=t.balance>=Ts&&t.balance<=20,o=t.balance<Ts,l=t.plan===null&&t.balance<Ts;return{...t,refresh:n,applyBalanceDelta:s,isLow:i,isOut:o,noPlan:l}}async function Am(e,t){if(mp)return{balance:Mp,plan:"studio"};const r=await e().catch(()=>null);let n=(r==null?void 0:r.balance)??t.balance,s=(r==null?void 0:r.plan)??t.plan;if(n<Ts&&t.balance>=Ts){await new Promise(o=>setTimeout(o,400));const i=await e().catch(()=>null);i&&(n=Math.max(n,i.balance),s=i.plan??s)}return{balance:n,plan:s}}const Yk=[{id:"app-builder",label:"App Builder",icon:oT}];function Y9({onClose:e,onOpenSettings:t,onOpenShare:r,onOpenHistory:n}){var Z;const{project:s,projects:i,createProject:o,renameProject:l,deleteProject:c,switchProject:u,files:d,setActiveWorkspaceTab:p}=gn(),h=nd(),{balance:f,monthlyGrant:x,plan:g,loading:y}=ld(),[b,v]=m.useState(null),[k,N]=m.useState(""),[j,w]=m.useState(!1),[S,T]=m.useState(""),[C,A]=m.useState(!1),P=m.useRef(null),E=m.useRef(null);m.useEffect(()=>{b&&P.current&&P.current.focus()},[b]),m.useEffect(()=>{j&&E.current&&E.current.focus()},[j]);const _=async O=>{k.trim()&&await l(O,k.trim()),v(null)},I=async()=>{S.trim()&&(await o(S.trim()),e()),w(!1),T("")},D=async O=>{i.length<=1||await c(O)},M=f,B=Math.max(0,x-f),$=x>0?Math.min(100,f/x*100):0,K=g?g.toUpperCase():"FREE";if(d.filter(O=>O.type==="file").length,d.filter(O=>O.type==="file"&&(O.name.endsWith(".html")||O.name.endsWith(".tsx")||O.name.endsWith(".jsx"))).length,C)return a.jsxs("div",{className:"absolute top-full left-0 mt-1 w-80 bg-card border rounded-xl shadow-xl z-50 overflow-hidden",children:[a.jsxs("div",{className:"px-3 py-2.5 border-b flex items-center gap-2",children:[a.jsx("button",{onClick:()=>A(!1),className:"p-1 rounded-md hover:bg-secondary text-muted-foreground hover:text-foreground",children:a.jsx(ei,{className:"w-3.5 h-3.5"})}),a.jsx("span",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"All Projects"}),a.jsx("div",{className:"flex-1"}),a.jsxs("button",{onClick:()=>w(!0),className:"flex items-center gap-1 text-xs text-primary hover:text-primary/80 font-medium",children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," New"]})]}),a.jsxs("div",{className:"max-h-72 overflow-y-auto py-1",children:[i.map(O=>a.jsx("div",{className:L("flex items-center gap-2 px-3 py-2 text-sm group transition-colors",O.id===(s==null?void 0:s.id)?"bg-primary/5":"hover:bg-secondary/50"),children:b===O.id?a.jsxs("form",{className:"flex-1 flex items-center gap-1.5",onSubmit:ne=>{ne.preventDefault(),_(O.id)},children:[a.jsx("input",{ref:P,value:k,onChange:ne=>N(ne.target.value),onBlur:()=>_(O.id),className:"flex-1 text-sm bg-secondary border rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-primary/30"}),a.jsx("button",{type:"submit",className:"text-primary hover:text-primary/80",children:a.jsx(Wn,{className:"w-3.5 h-3.5"})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:()=>{u(O.id),e()},className:"flex-1 text-left flex items-center gap-2 truncate min-w-0",children:[a.jsx(cc,{className:L("w-4 h-4 shrink-0",O.id===(s==null?void 0:s.id)?"text-primary":"text-muted-foreground")}),a.jsx("span",{className:L("truncate flex-1",O.id===(s==null?void 0:s.id)?"font-semibold text-primary":"text-foreground"),children:O.name}),!O.isOwner&&a.jsx("span",{className:"text-[9px] font-mono uppercase tracking-wider px-1.5 py-px rounded bg-accent/15 text-accent-foreground
1315/80 shrink-0",title:"Shared with you by another user",children:"Shared"})]}),a.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[O.isOwner&&a.jsx("button",{onClick:()=>{v(O.id),N(O.name)},className:"p-1 rounded hover:bg-secondary text-muted-foreground hover:text-foreground",children:a.jsx(uc,{className:"w-3.5 h-3.5"})}),O.isOwner&&i.length>1&&a.jsx("button",{onClick:()=>D(O.id),className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive",children:a.jsx(oa,{className:"w-3.5 h-3.5"})})]})]})},O.id)),j&&a.jsx("div",{className:"px-3 py-2",children:a.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:O=>{O.preventDefault(),I()},children:[a.jsx("input",{ref:E,value:S,onChange:O=>T(O.target.value),onBlur:()=>{S.trim()||w(!1)},placeholder:"Project name...",className:"flex-1 text-sm bg-secondary border rounded px-2 py-1 placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"}),a.jsx("button",{type:"submit",className:"text-primary hover:text-primary/80",children:a.jsx(Wn,{className:"w-3.5 h-3.5"})}),a.jsx("button",{type:"button",onClick:()=>w(!1),className:"text-muted-foreground hover:text-foreground",children:a.jsx(qn,{className:"w-3.5 h-3.5"})})]})})]})]});const R="w-full flex items-center gap-2.5 px-3 py-2 text-[13px] text-foreground hover:bg-secondary/60 rounded-md transition-colors",Y="w-4 h-4 text-muted-foreground";return a.jsxs("div",{className:"absolute top-full left-0 mt-1 w-[340px] bg-card border rounded-xl shadow-2xl z-50 overflow-hidden animate-in fade-in-0 zoom-in-95 duration-200",children:[a.jsxs("div",{className:"relative px-4 pt-4 pb-3 border-b bg-gradient-to-br from-primary/[0.05] via-transparent to-transparent",children:[a.jsx("span",{"aria-hidden":"true",className:"absolute right-2 top-2 text-primary/20 text-lg select-none",children:"🌿"}),a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/15 flex items-center justify-center text-primary text-sm font-bold shrink-0",children:((s==null?void 0:s.name)||"P").slice(0,1).toUpperCase()}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-[13px] font-semibold text-foreground truncate",children:(s==null?void 0:s.name)||"My Project"}),a.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[a.jsx("span",{className:L("inline-flex items-center text-[9px] px-1.5 py-0.5 rounded font-semibold tracking-wide uppercase",g?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:K}),a.jsxs("span",{className:"text-[10px] text-muted-foreground/70 font-mono truncate",children:["#",(Z=s==null?void 0:s.id)==null?void 0:Z.slice(0,6)]})]})]})]})]}),a.jsxs("div",{className:"px-4 py-3.5 border-b",children:[a.jsxs("div",{className:"flex items-end justify-between gap-3 mb-2",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-baseline gap-1.5",children:[a.jsx("span",{className:"text-[26px] font-semibold tabular-nums tracking-tight text-foreground leading-none",children:y?"…":M.toLocaleString(void 0,{maximumFractionDigits:1})}),a.jsx("span",{className:"text-[11px] text-muted-foreground",children:"credits"})]}),a.jsx("p",{className:"text-[10.5px] text-muted-foreground mt-1",children:x>0?a.jsxs(a.Fragment,{children:["of ",a.jsx("span",{className:"font-medium text-foreground/80",children:x.toLocaleString()})," · ",B.toLocaleString(void 0,{maximumFractionDigits:1})," used this cycle"]}):"Top up tokens or pick a plan to start."})]}),a.jsxs("button",{type:"button",onClick:()=>{e(),window.location.href="/studio/billing"},className:"shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-primary text-primary-foreground text-[11.5px] font-medium hover:bg-primary/90 transition-colors",children:[a.jsx(Kr,{className:"w-3 h-3"})," Add"]})]}),a.jsx("div",{className:"h-[3px] rounded-full bg-muted overflow-hidden",children:a.jsx("div",{className:L("h-full rounded-full transition-all",$<15?"bg-amber-500":"bg-primary"),style:{width:`${$}%`}})})]}),a.jsxs("div",{className:"p-1.5",children:[a.jsx("div",{className:"px-3 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Project"}),a.jsxs("button",{onClick:()=>{e(),t()},className:R,children:[a.jsx(ni,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Project settings"})]}),a.jsxs("button",{onClick:()=>{e(),r()},className:R,children:[a.jsx(_w,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Share"})]}),a.jsxs("button",{onClick:()=>{e(),n()},className:R,children:[a.jsx(_p,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Version history"})]}),a.jsxs("button",{onClick:()=>{e(),p("cloud")},className:R,children:[a.jsx(Br,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Cloud, domains & deploys"})]}),a.jsxs("button",{onClick:()=>{e(),p("github")},className:R,children:[a.jsx(Nu,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"GitHub sync"})]})]}),a.jsxs("div",{className:"border-t p-1.5",children:[a.jsx("div",{className:"px-3 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Worksp
1315ace"}),a.jsxs("button",{onClick:()=>A(!0),className:R,children:[a.jsx(cc,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Switch project"}),a.jsx("span",{className:"text-[11px] text-muted-foreground/70 tabular-nums",children:i.length})]}),a.jsxs("button",{onClick:()=>{w(!0),A(!0)},className:R,children:[a.jsx(Kr,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"New project"})]}),a.jsxs("button",{onClick:()=>{v((s==null?void 0:s.id)||""),N((s==null?void 0:s.name)||""),A(!0)},className:R,children:[a.jsx(uc,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Rename project"})]}),a.jsxs("button",{onClick:()=>{s!=null&&s.id&&(navigator.clipboard.writeText(s.id).catch(()=>{}),Mt({title:"Project ID copied",description:s.id}))},className:R,children:[a.jsx(gs,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Copy project ID"})]}),a.jsxs("button",{onClick:()=>{e(),h("/")},className:R+" text-muted-foreground",children:[a.jsx(ei,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Back to home"})]})]}),a.jsxs("div",{className:"border-t p-1.5",children:[a.jsxs("a",{href:"https://docs.studiojungle.ai/",target:"_blank",rel:"noopener noreferrer",onClick:e,className:R+" text-muted-foreground hover:text-foreground",children:[a.jsx(Wg,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Documentation"}),a.jsx(ei,{className:"w-3 h-3 rotate-[135deg] text-muted-foreground/60"})]}),a.jsxs("a",{href:"mailto:[email protected]?subject=Studio%20Jungle%20feedback",className:R+" text-muted-foreground hover:text-foreground",children:[a.jsx(v$,{className:Y})," ",a.jsx("span",{className:"flex-1 text-left",children:"Help & feedback"}),a.jsx(ei,{className:"w-3 h-3 rotate-[135deg] text-muted-foreground/60"})]})]})]})}function J9({onGoHome:e,chatCollapsed:t,onToggleChat:r}){var P,E,_;const{mode:n,setMode:s,planSteps:i,project:o}=gn(),{signOut:l,session:c}=Us(),u=nd(),[d,p]=m.useState(!1),[h,f]=m.useState(!1),[x,g]=m.useState(!1),[y,b]=m.useState(!1),[v,k]=m.useState(!1),[N,j]=m.useState(!1),w=((P=c==null?void 0:c.user)==null?void 0:P.email)||"",S=((_=(E=c==null?void 0:c.user)==null?void 0:E.user_metadata)==null?void 0:_.display_name)||w.split("@")[0]||"User",T=S.slice(0,2).toUpperCase(),C=i.filter(I=>I.status==="running").length,A=i.filter(I=>I.status==="done").length;return m.useEffect(()=>{let I=!1;async function D(){if(!(c!=null&&c.access_token)){j(!1);return}try{const M="https://xfmlsevleobdlnjqxmdi.supabase.co",B="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo",$=await fetch(`${M}/functions/v1/admin-build-ledger?probe=1`,{headers:{Authorization:`Bearer ${c.access_token}`,apikey:B}});if(!I)if($.ok){const K=await $.json().catch(()=>null);j((K==null?void 0:K.allowed)===!0)}else j(!1)}catch{I||j(!1)}}return D(),()=>{I=!0}},[c==null?void 0:c.access_token]),a.jsxs(a.Fragment,{children:[a.jsx(K9,{}),a.jsxs("header",{className:"h-14 border-b bg-card/80 backdrop-blur-xl flex items-center justify-between px-4 shrink-0 relative z-30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[e&&a.jsx("button",{onClick:e,className:"w-8 h-8 rounded-lg flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors",title:"Back to Home",children:a.jsx(xm,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",onClick:e,children:[a.jsx("img",{src:"/studio-jungle-mark.svg",alt:"",className:"h-8 w-8 rounded-xl object-contain"}),a.jsx("img",{src:"/logo.png",alt:"Studiojungle",className:"h-12 w-auto object-contain"})]}),a.jsx("div",{className:"h-6 w-px bg-border mx-1"}),a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>f(!h),className:L("flex items-center gap-1.5 text-sm transition-colors px-2 py-1.5 rounded-md hover:bg-secondary",h?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground"),title:"Project settings and actions",children:[a.jsx("span",{className:"font-medium",children:(o==null?void 0:o.name)||"My Project"}
1315),(o==null?void 0:o.id)&&a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground/60 ml-1",children:["#",o.id.slice(0,6)]}),a.jsx(ni,{className:"w-3.5 h-3.5"})]}),h&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>f(!1)}),a.jsx("div",{className:"z-50",children:a.jsx(Y9,{onClose:()=>f(!1),onOpenSettings:()=>g(!0),onOpenShare:()=>b(!0),onOpenHistory:()=>k(!0)})})]})]})]}),Yk.length>1&&a.jsx("div",{className:"flex items-center bg-secondary rounded-lg p-1 gap-0.5",children:Yk.map(I=>a.jsxs("button",{onClick:()=>s(I.id),className:L("flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all",n===I.id?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[a.jsx(I.icon,{className:"w-4 h-4"}),I.label]},I.id))}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("button",{onClick:()=>k(!v),className:L("w-9 h-9 rounded-lg flex items-center justify-center transition-colors border",v?"bg-primary/10 text-primary border-primary/20":"text-muted-foreground hover:text-foreground border-transparent hover:bg-secondary"),title:"Version History",children:a.jsx(_p,{className:"w-4 h-4"})}),r&&a.jsx("button",{onClick:r,className:L("w-8 h-8 rounded-md flex items-center justify-center transition-colors border",t?"bg-primary/10 text-primary border-primary/20":"text-muted-foreground hover:text-foreground border-transparent hover:bg-secondary"),title:t?"Show chat panel":"Hide chat panel",children:t?a.jsx(bT,{className:"w-3.5 h-3.5"}):a.jsx(yT,{className:"w-3.5 h-3.5"})}),a.jsx("div",{className:"h-6 w-px bg-border mx-0.5"}),a.jsxs("button",{onClick:()=>p(!d),className:L("flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium transition-all border",d?"bg-primary/10 text-primary border-primary/20":"text-muted-foreground hover:text-foreground border-transparent hover:bg-secondary"),children:[a.jsx(Ek,{className:"w-4 h-4"}),a.jsx("span",{children:"Plan"}),C>0&&a.jsxs("span",{className:"flex items-center gap-1 text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary animate-pulse-dot"}),C]}),C===0&&a.jsxs("span",{className:"text-xs bg-secondary text-muted-foreground px-1.5 py-0.5 rounded-full",children:[A,"/",i.length]})]}),a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,children:a.jsx("button",{className:"w-9 h-9 rounded-full bg-primary/10 flex items-center justify-center text-primary hover:bg-primary/20 transition-colors text-xs font-bold",title:S,children:T})}),a.jsxs(Jl,{align:"end",className:"w-56",children:[a.jsx(hu,{className:"font-normal",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary text-sm font-bold shrink-0",children:T}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:S}),a.jsx("p",{className:"text-xs text-muted-foreground truncate",children:w})]})]})}),a.jsx(ki,{}),a.jsxs(Qr,{onClick:()=>u("/"),children:[a.jsx(xm,{className:"w-4 h-4 mr-2"})," Home"]}),a.jsxs(Qr,{onClick:()=>u("/studio/account"),children:[a.jsx(ni,{className:"w-4 h-4 mr-2"})," Account settings"]}),N&&a.jsxs(a.Fragment,{children:[a.jsxs(Qr,{onClick:()=>u("/admin/build-ledger"),children:[a.jsx(si,{className:"w-4 h-4 mr-2"})," Build ledger"]}),a.jsxs(Qr,{onClick:()=>u("/admin/users"),children:[a.jsx(Zl,{className:"w-4 h-4 mr-2"})," Users"]})]}),a.jsx(ki,{}),a.jsxs(Qr,{onClick:()=>l(),className:"text-destructive focus:text-destructive",children:[a.jsx(zb,{className:"w-4 h-4 mr-2"})," Log Out"]})]})]})]})]}),d&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>p(!1)}),a.jsxs("div",{className:"fixed top-16 right-4 z-50 w-[480px] max-h-[70vh] bg-card border rounded-xl shadow-xl overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ek,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-sm font-semibold",children:"Execution Plan"})]}),a.jsx("button",{onClick:()=>p(!1),className:"text-muted-foreground hover:text-foreground transition-colors",children:a.jsx(qn,{
1315className:"w-4 h-4"})})]}),a.jsx("div",{className:"max-h-[calc(70vh-52px)] overflow-y-auto",children:a.jsx(sB,{})})]})]}),v&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>k(!1)}),a.jsx(q9,{projectId:(o==null?void 0:o.id)||null,onClose:()=>k(!1)})]}),a.jsx(i8,{open:x,onOpenChange:g,projectId:(o==null?void 0:o.id)||null,projectName:(o==null?void 0:o.name)||"My Project"}),(o==null?void 0:o.id)&&a.jsx(o8,{open:y,onOpenChange:b,projectId:o.id,projectName:o.name||"My Project"})]})}function X9({queue:e,onEdit:t,onDelete:r,isProcessing:n}){const[s,i]=m.useState(null),[o,l]=m.useState("");if(e.length===0)return null;const c=d=>{i(d.id),l(d.text)},u=()=>{s&&o.trim()&&t(s,o.trim()),i(null),l("")};return a.jsxs("div",{className:"border-t border-border/50 bg-muted/20 px-3 py-2 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[a.jsx(Lr,{className:"w-3 h-3 text-primary"}),a.jsxs("span",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:["Queued Prompts (",e.length,")"]}),n&&a.jsx(ze,{className:"w-3 h-3 text-primary animate-spin ml-auto"})]}),a.jsx("div",{className:"space-y-1",children:e.map((d,p)=>a.jsxs("div",{className:L("group flex items-start gap-1.5 rounded-lg px-2 py-1.5 text-xs transition-all",p===0&&n?"bg-primary/5 border border-primary/20":"bg-background/50 border border-border/30 hover:border-border"),children:[a.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground shrink-0 mt-0.5",children:[a.jsx(fT,{className:"w-3 h-3 opacity-30"}),a.jsx("span",{className:"text-[10px] font-mono w-4 text-center",children:p===0&&n?a.jsx(ze,{className:"w-3 h-3 animate-spin text-primary"}):`#${p+1}`})]}),s===d.id?a.jsxs("div",{className:"flex-1 flex items-center gap-1",children:[a.jsx("input",{value:o,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&u(),h.key==="Escape"&&i(null)},className:"flex-1 bg-background border rounded px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-primary/30",autoFocus:!0}),a.jsx("button",{onClick:u,className:"p-1 text-primary hover:bg-primary/10 rounded",children:a.jsx(Wn,{className:"w-3 h-3"})})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"flex-1 text-foreground/80 line-clamp-2 leading-relaxed",children:d.text}),a.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[a.jsx("button",{onClick:()=>c(d),className:"p-1 text-muted-foreground hover:text-foreground hover:bg-secondary rounded",title:"Edit prompt",children:a.jsx(uc,{className:"w-3 h-3"})}),a.jsx("button",{onClick:()=>r(d.id),className:"p-1 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded",title:"Remove from queue",children:a.jsx(qn,{className:"w-3 h-3"})})]})]})]},d.id))})]})}function Xw(e){return e.replace(/^(build|create|make|design)\s+(me\s+)?(a|an|the)?\s*/i,"").trim()}function Z9(e){const t=e.toLowerCase();return/\b(events?\s+(discovery|discover)|discover\s+events?|community\s+events?|event\s+(reviews?|feed|platform|discovery)|saved\s+events|personal\s+calendar|rsvp|neighborhood|itinerar|follow\s+interests|interest\s+(categor|topic)|meetup|conference|ticketing|attendee)\b/.test(t)||/\bevents?\b/.test(t)&&/\b(discover|calendar|review|rsvp|neighborhood|itinerary|interest|community|attendee|favorite)\b/.test(t)}function Zw(e){const t=e.toLowerCase();return/\b(audio|music|track|sound|podcast|stem|mastering|mixing|beat|producer|sonic|waveform)\b/.test(t)?"audio":Z9(e)?"events":/\b(social|friend|vote|voting|poll|community|feed|followers|connect)\b/.test(t)?"social":/\b(book|club|reading|novel|author|literature|library|bookshelf)\b/.test(t)?"bookclub":/\b(shop|store|ecommerce|e-commerce|cart|checkout|product catalog|marketplace|multi[\s-]*vendor|seller)\b/.test(t)?"ecommerce":/\b(course|learn|education|school|student|lesson|tutor|lms)\b/.test(t)?"education":/\b(fitness|workout|gym|health|step|calorie|run|yoga)\b/.test(t)?"fitness":/\b(food|recipe|restaurant|delivery|menu|cafe|coffee)\b/.test(t)?"food":/\b(medical|healthcare|clinic|patient|doctor|hospital|wellness)\b/.test(t)?"health":/\b(booking platform|reservation|appointment|scheduling|salon|spa|availab|time\s*slot)\b/.test(t)&&!/\b(flight|hotel|vacation|itinerary)\b/.test(t)?"booking":/\b(saas|software|platform|devtools|developer|api|multi[\s-]*user)\b/.test(t)?"saas":/\b(travel|trip|hotel|flight|booking|itinerary|vacation)\b/.test(t)?"travel":/\b(analytic|metric|funnel|retention|mixpanel|amplitude|kpi)\b/.test(t)||/\b(analytics?\s+dashboard|dashboard\s+with\s+event\s+tracking|event\s+tracking|product\s+analytics)\b/.test(t)?"analytics":/\b(conference|meetup|ticketing|event\s+plan|event\s+manag)\b/.test(t)?"events":/\b(crm|lead|sales|pipeline|deal|contact|customer)\b/.test(t)?"crm":/\b(project|task|kanban|sprint|ticket|pm|tracker)\b/.test(t)?"project":/\b(finance|fintech|bank|payment|invoice|billing|budget|money)\b/.test(t)?"finance":"generic"}const Q9={audio:"SonicForge",saas:"DevFlow",social:"CircleVote",bookclub:"BookCircle",ecommerce:"ShopLane",education:"LearnPath",fitness:"FitPulse",food:"TasteBox",health:"CareNest",finance:"Ledgerly",travel:"WanderKit",events:"Gatherly",crm:"PipelineHQ",analytics:"MetricPulse",project:"TaskFlow",booking:"SlotFlow",generic:null};function Qw(e,t){const r=Q9[e];
1315if(r)return r;const n=t.split(/\s+/).filter(s=>s.length>2&&!/^(the|and|for|with|page|landing|build|app|platform)$/i.test(s));return n.length>=2?n.slice(0,2).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(""):n[0]?n[0].charAt(0).toUpperCase()+n[0].slice(1):"YourBrand"}function e7(e,t,r){const n=e.length>8?e.charAt(0).toUpperCase()+e.slice(1):r,s=n.length>90?`${n.slice(0,87)}...`:n;return{social:"Where friends vote on what matters",bookclub:"Organize book clubs without the chaos",ecommerce:"Your storefront, ready to sell",education:"Learn faster with a clearer path",fitness:"Hit your goals every single day",food:"Great food, one tap away",health:"Care that fits your schedule",finance:"Money clarity for modern teams",travel:"Plan trips without the spreadsheet",events:"Events that actually fill seats"}[t]||s}function t7(e,t,r){return{audio:"Create, mix, and master tracks with AI — hear the difference in minutes.",saas:`${t} connects your workflow so your team always knows what's shipping.`,social:"Polls, groups, and reactions — built for real friend groups, not corporate feeds.",bookclub:"Pick books, schedule meetups, track votes, and keep every member in sync.",ecommerce:"Catalog, cart, and checkout flows with realistic product data out of the box.",education:"Courses, progress, and quizzes — a learning hub your students will actually use.",fitness:"Workouts, streaks, and progress charts designed for daily motivation.",food:"Browse menus, save favorites, and order with a thumb-friendly flow.",health:"Appointments, records, and reminders in one calm, trustworthy interface.",finance:"Invoices, balances, and cashflow — see the numbers that matter.",travel:"Search, compare, and book — itineraries that feel premium on mobile.",events:"Sell tickets, manage RSVPs, and fill your calendar with less admin.",crm:"Leads, deals, and follow-ups — your pipeline in one place.",analytics:"Events, funnels, and retention — product metrics at a glance.",project:"Tasks, boards, and sprints — ship without losing the thread.",generic:r.length>20?r.slice(0,160):`${t} — built around your idea, not a generic template.`}[e]}function n7(e){return{audio:[{title:"AI mastering",description:"Polish demos into release-ready audio in one pass.",icon:"sparkles"},{title:"Stem separation",description:"Isolate vocals and instruments for remixes.",icon:"cube"},{title:"Before / after",description:"Playable demos so visitors hear the magic.",icon:"zap"}],saas:[{title:"Team workspaces",description:"Shared projects with roles and permissions.",icon:"bolt"},{title:"Live analytics",description:"KPIs and charts that update as data flows in.",icon:"chart"},{title:"Integrations",description:"Connect Slack, GitHub, and your stack.",icon:"shield"}],social:[{title:"Group polls",description:"Let friends vote on plans, movies, or dinner spots.",icon:"zap"},{title:"Activity feed",description:"Reactions, comments, and mentions that feel alive.",icon:"bolt"},{title:"Private circles",description:"Invite-only groups — no algorithmic noise.",icon:"shield"}],bookclub:[{title:"Reading lists",description:"Nominate, vote, and lock the next book together.",icon:"book"},{title:"Meetup scheduler",description:"Find times that work and send reminders.",icon:"calendar"},{title:"Discussion threads",description:"Chapter notes and spoiler-safe chats per title.",icon:"chat"}],ecommerce:[{title:"Product grid",description:"Filters, badges, and quick-view cards.",icon:"cube"},{title:"Cart & checkout",description:"Multi-step flow with shipping and payment mocks.",icon:"cart"},{title:"Order tracking",description:"Status timeline customers can actually trust.",icon:"truck"}],education:[{title:"Course catalog",description:"Modules, lessons, and progress bars.",icon:"book"},{title:"Quizzes",description:"Instant feedback and completion certificates.",icon:"check"},{title:"Instructor dashboard",description:"Enrollment and engagement at a glance.",icon:"chart"}],fitness:[{title:"Workout plans",description:"Structured sessions with timers and reps.",icon:"bolt"},{title:"Progress charts",description:"Streaks, PRs, and weekly summaries.",icon:"chart"},{title:"Goal tracking",description:"Daily targets that adapt to your rhythm.",icon:"target"}],food:[{title:"Menu browsing",description:"Photos, dietary tags, and chef picks.",icon:"cube"},{title:"Fast ordering",description:"Cart, modifiers, and one-tap reorder.",icon:"cart"}
1315,{title:"Rewards",description:"Points, favorites, and personalized offers.",icon:"star"}],health:[{title:"Appointments",description:"Book, reschedule, and get reminders.",icon:"calendar"},{title:"Secure records",description:"Visit history and documents in one place.",icon:"shield"},{title:"Care team",description:"Message providers without phone tag.",icon:"chat"}],finance:[{title:"Cashflow view",description:"Income, expenses, and runway in real time.",icon:"chart"},{title:"Invoices",description:"Send, track, and mark paid in seconds.",icon:"doc"},{title:"Budgets",description:"Category limits with friendly alerts.",icon:"target"}],travel:[{title:"Trip planner",description:"Flights, stays, and activities in one itinerary.",icon:"map"},{title:"Price alerts",description:"Watch routes and book when fares drop.",icon:"bell"},{title:"Shared trips",description:"Collaborate on plans with travel mates.",icon:"users"}],events:[{title:"Ticketing",description:"Tiers, promo codes, and QR check-in.",icon:"ticket"},{title:"Agenda builder",description:"Sessions, speakers, and room assignments.",icon:"calendar"},{title:"Attendee hub",description:"RSVPs, reminders, and live updates.",icon:"bolt"}],crm:[{title:"Pipeline board",description:"Drag deals across stages with confidence.",icon:"chart"},{title:"Contact profiles",description:"History, notes, and next actions.",icon:"users"},{title:"Email sequences",description:"Follow-ups that don't fall through cracks.",icon:"mail"}],analytics:[{title:"Event stream",description:"See product usage as it happens.",icon:"bolt"},{title:"Funnels",description:"Drop-off points with actionable detail.",icon:"chart"},{title:"Cohorts",description:"Retention curves by signup week.",icon:"users"}],project:[{title:"Kanban boards",description:"Columns, WIP limits, and quick edits.",icon:"board"},{title:"Sprint planning",description:"Velocity, burndown, and standup notes.",icon:"calendar"},{title:"Dependencies",description:"Link tasks so blockers surface early.",icon:"link"}],generic:[{title:"Built for your idea",description:"Layouts and copy shaped by your prompt — not a one-size template.",icon:"sparkles"},{title:"Interactive flows",description:"Clickable UI with realistic seeded data.",icon:"bolt"},{title:"Ready to extend",description:"Add auth, database, or APIs in the next phase.",icon:"shield"}]}[e]}function r7(e){const t=["audio","saas","social","finance","analytics"],n={social:"139 92 246",bookclub:"180 83 9",ecommerce:"234 88 12",education:"37 99 235",fitness:"16 185 129",food:"245 158 11",health:"14 165 233",finance:"16 185 129",travel:"6 182 212",events:"236 72 153",audio:"139 92 246",saas:"16 185 129"}[e]||"59 130 246";return{theme:t.includes(e)?"dark":"light",accent:n,accentSoft:`${n} / 0.15`}}function s7(e){return e==="events"?"events":e==="social"||e==="bookclub"?"social":e==="ecommerce"?"marketplace":e==="analytics"?"analytics":e==="saas"?"saas":e==="booking"||e==="travel"||e==="food"?"booking":"crm"}function a7(e){const t=Xw(e),r=Zw(t),n=s7(r),s=Qw(r,t),i=s.slice(0,2).toUpperCase(),o={social:["#8b5cf6","#ede9fe"],marketplace:["#059669","#d1fae5"],analytics:["#0ea5e9","#e0f2fe"],booking:["#d97706","#fef3c7"],saas:["#6366f1","#eef2ff"],events:["#ec4899","#fce7f3"],crm:["#6366f1","#eef2ff"]},[l,c]=o[n],u=[{label:"Jan",value:28400,value2:54e3},{label:"Feb",value:31200,value2:61e3},{label:"Mar",value:29800,value2:58e3},{label:"Apr",value:34600,value2:67e3},{label:"May",value:38100,value2:72e3},{label:"Jun",value:36700,value2:69e3}];return n==="social"&&r==="bookclub"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:"#b45309",accentSoft:"#fef3c7",appTitle:`${s} — Book club hub`,userRole:"Club Organizer",navItems:[{id:"dashboard",label:"Overview",icon:"dashboard",path:"/dashboard"},{id:"books",label:"Books",icon:"projects",path:"/books",badge:4},{id:"members",label:"Members",icon:"users",path:"/members"},{id:"meetups",label:"Meetups",icon:"calendar",path:"/meetups"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"books",kpis:[{label:"Books read",value:24,change:12.4,changeType:"up",description:"this year"},{label:"Members",value:86,change:8.1,changeType:"up",description:"active"},{label:"Upcoming meetups",value:3,change:0,changeType:"up",description:"scheduled"},{label:"Avg rating",value:"4.6★",change:2.1,changeType:"up",description:"club picks"}],chart:{type:"area",title:"Reading activity",dataKey:"Pages",dataKey2:"Members",dataPoints:u},recentColumns:[{key:"name",label:"Book",type:"text"},{key:"company",label:"Votes",type:"number"},{key:"status",label:"Status",type:"badge"}],recentRows:[{name:"The Midnight Library",company:12,status:"Voting"},{name:"Project Hail Mary",company:8,status:"Reading"}
1315],routes:{books:{kind:"grid",title:"Book picks",description:"Vote on the next club read",columns:[{key:"title",label:"Title",type:"text"},{key:"author",label:"Author",type:"text"},{key:"votes",label:"Votes",type:"number"}],data:[{title:"Tomorrow, and Tomorrow",author:"Gabrielle Zevin",votes:14},{title:"Klara and the Sun",author:"Kazuo Ishiguro",votes:9}]}}}:n==="social"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s} — Social polls & groups`,userRole:"Community Lead",navItems:[{id:"dashboard",label:"Overview",icon:"dashboard",path:"/dashboard"},{id:"polls",label:"Polls",icon:"analytics",path:"/polls",badge:6},{id:"groups",label:"Groups",icon:"users",path:"/groups"},{id:"activity",label:"Activity",icon:"tasks",path:"/activity"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"polls",kpis:[{label:"Active polls",value:18,change:12.4,changeType:"up",description:"vs. last week"},{label:"Votes cast",value:"1.2K",change:8.1,changeType:"up",description:"live"},{label:"Groups",value:12,change:-3.2,changeType:"down",description:"needs invites"},{label:"Engagement",value:"68%",change:2.1,changeType:"up",description:"7-day avg"}],chart:{type:"bar",title:"Votes over time",dataKey:"Votes",dataKey2:"Polls",dataPoints:u},recentColumns:[{key:"name",label:"Poll",type:"text"},{key:"company",label:"Group",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"value",label:"Votes",type:"number"}],recentRows:[{name:"Weekend plans",company:"College crew",status:"Live",value:42},{name:"Movie night",company:"Roommates",status:"Closed",value:18},{name:"Lunch spot",company:"Work friends",status:"Live",value:31}],routes:{polls:{kind:"grid",title:"Active polls",description:"Vote cards with live tallies",searchable:!0,primaryAction:{label:"New poll",icon:"analytics"},columns:[{key:"title",label:"Poll",type:"text"},{key:"options",label:"Options",type:"text"},{key:"votes",label:"Votes",type:"number"},{key:"status",label:"Status",type:"badge"}],data:[{title:"Beach or mountains?",options:"Beach · Mountains",votes:24,status:"Live"},{title:"Friday dinner",options:"Thai · Pizza · Sushi",votes:18,status:"Live"},{title:"Game night",options:"Board · Video · Skip",votes:9,status:"Draft"}]},groups:{kind:"list",title:"Groups",description:"Friend circles running polls",searchable:!0,columns:[{key:"name",label:"Group",type:"avatar"},{key:"members",label:"Members",type:"number"},{key:"polls",label:"Polls",type:"number"},{key:"status",label:"Status",type:"badge"}],data:[{name:"Weekend crew",members:8,polls:4,status:"Active"},{name:"Book club",members:12,polls:2,status:"Active"}]}}}:n==="marketplace"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s} — Seller marketplace`,userRole:"Marketplace Admin",navItems:[{id:"dashboard",label:"Overview",icon:"dashboard",path:"/dashboard"},{id:"products",label:"Products",icon:"projects",path:"/products",badge:24},{id:"orders",label:"Orders",icon:"deals",path:"/orders",badge:8},{id:"sellers",label:"Sellers",icon:"users",path:"/sellers"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"products",kpis:[{label:"GMV",value:"$284K",change:14.2,changeType:"up",description:"this month"},{label:"Orders",value:1240,change:6.8,changeType:"up",description:"fulfilled"},{label:"Active sellers",value:86,change:4.1,changeType:"up",description:"verified"},{label:"Conversion",value:"3.2%",change:-.4,changeType:"down",description:"checkout"}],chart:{type:"area",title:"Order volume",dataKey:"Orders",dataKey2:"Revenue",dataPoints:u},recentColumns:[{key:"name",label:"Product",type:"text"},{key:"company",label:"Seller",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"value",label:"Price",type:"number"}],recentRows:[{name:"Ceramic mug set",company:"Artisan Co",status:"Live",value:42},{name:"Linen throw",company:"Home Studio",status:"Review",value:78}],routes:{products:{kind:"grid",title:"Product catalog",description:"Marketplace listings with seller badges",searchable:!0,primaryAction:{label:"Add product",icon:"projects"},columns:[{key:"name",label:"Product",type:"text"},{key:"seller",label:"Seller",type:"text"},{key:"price",label:"Price",type:"number"},{key:"status",label:"Status",type:"badge"}],data:[{name:"Handmade vase",seller:"Clay & Co",price:56,status:"Live"},{name:"Organic honey",seller:"Valley Farms",price:18,status:"Live"},{name:"Leather tote",seller:"Atelier",price:120,status:"Draft"}]},orders:{kind:"list",title:"Orders",description:"Fulfillment queue",searchable:!0,columns:[{key:"name",label:"Order",type:"text"},{key:"company",label:"Buyer",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"value",label:"Total",type:"number"}],data:[{name:"#1042",company:"Alex M.",status:"Shipped",value:89},{name:"#1041",company:"Sam K.",status:"Processing",value:42}]}}}:n==="analytics"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s} — Product analytics`,userRole:"Growth Lead",navItems:[{id:"dashboard",label:"Dashboard",icon:"dashboard",path:"/dashboard"},{id:"events",label:"Events",icon:"analytics",path:"/events"},{id:"funnels",label:"Funnels",icon:"funnel",path:"/funnels"},{id:"users",label:"Users",icon:"users",path:"/users"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"events",kpis:[{label:"Active users",value:"12.4K",change:9.2,changeType:"up",description:"DAU"},{label:"Events today",value:"8,920",change:11.1,changeType:"up",description:"tracked"},{label:"Conversion",value:"3.8%",change:-.6,changeType:"down",de
1315scription:"signup"},{label:"Retention",value:"42%",change:1.4,changeType:"up",description:"D30"}],chart:{type:"line",title:"Events over time",dataKey:"Events",dataKey2:"Signups",dataPoints:u},recentColumns:[{key:"name",label:"Event",type:"text"},{key:"company",label:"Source",type:"text"},{key:"status",label:"Trend",type:"badge"},{key:"value",label:"Count",type:"number"}],recentRows:[{name:"signup_completed",company:"Web",status:"Up",value:420},{name:"checkout_started",company:"Mobile",status:"Flat",value:188}],routes:{events:{kind:"list",title:"Event stream",description:"Tracked product events",searchable:!0,columns:[{key:"name",label:"Event",type:"text"},{key:"company",label:"Platform",type:"text"},{key:"value",label:"Count",type:"number"},{key:"status",label:"Trend",type:"badge"}],data:[{name:"page_view",company:"Web",value:12400,status:"Up"},{name:"button_click",company:"iOS",value:3200,status:"Up"}]},funnels:{kind:"funnel",title:"Signup funnel",description:"Step conversion rates",steps:[{label:"Landing",value:1e4,rate:100},{label:"Signup start",value:4200,rate:42},{label:"Email verify",value:3100,rate:31},{label:"Activated",value:1800,rate:18}]}}}:n==="events"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s} — Events discovery`,userRole:"Event Explorer",navItems:[{id:"discover",label:"Discover Events",icon:"events",path:"/discover",badge:12},{id:"interests",label:"Interests",icon:"tag",path:"/interests"},{id:"saved",label:"Saved Events",icon:"star",path:"/saved",badge:8},{id:"calendar",label:"My Calendar",icon:"calendar",path:"/calendar"},{id:"rsvp",label:"RSVP Tracking",icon:"inbox",path:"/rsvp",badge:3},{id:"reviews",label:"Reviews",icon:"messages",path:"/reviews"},{id:"neighborhoods",label:"Neighborhood Guides",icon:"folder",path:"/neighborhoods"},{id:"itineraries",label:"Itineraries",icon:"projects",path:"/itineraries"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"discover",kpis:[{label:"Events near you",value:48,change:14.2,changeType:"up",description:"this week"},{label:"Saved favorites",value:12,change:6,changeType:"up",description:"on calendar"},{label:"Upcoming RSVPs",value:5,change:2,changeType:"up",description:"confirmed"},{label:"Neighborhood guides",value:8,change:1,changeType:"up",description:"explored"}],chart:{type:"bar",title:"Events by interest",dataKey:"Events",dataKey2:"RSVPs",dataPoints:u},recentColumns:[{key:"name",label:"Event",type:"text"},{key:"company",label:"Neighborhood",type:"text"},{key:"status",label:"RSVP",type:"badge"},{key:"value",label:"Rating",type:"number"}],recentRows:[{name:"Jazz in the Park",company:"Mission District",status:"Going",value:4.8},{name:"Food Truck Festival",company:"SOMA",status:"Interested",value:4.6},{name:"Tech Meetup Night",company:"Hayes Valley",status:"Going",value:4.9}],routes:{discover:{kind:"grid",title:"Event feed",description:"Discover events matched to your interests",searchable:!0,primaryAction:{label:"Filter interests",icon:"tag"},columns:[{key:"title",label:"Event",type:"text"},{key:"neighborhood",label:"Area",type:"text"},{key:"date",label:"When",type:"date"},{key:"rsvp",label:"RSVP",type:"badge"}],data:[{title:"Sunset yoga series",neighborhood:"Marina",date:"2026-06-20",rsvp:"Open"},{title:"Indie film night",neighborhood:"Castro",date:"2026-06-21",rsvp:"Waitlist"},{title:"Street art walk",neighborhood:"Mission",date:"2026-06-22",rsvp:"Going"}]},saved:{kind:"list",title:"Saved events",description:"Favorites on your personal calendar",searchable:!0,columns:[{key:"name",label:"Event",type:"text"},{key:"company",label:"Neighborhood",type:"text"},{key:"date",label:"Date",type:"date"},{key:"status",label:"Reminder",type:"badge"}],data:[{name:"Farmers market brunch",company:"Noe Valley",date:"2026-06-19",status:"1 day before"},{name:"Live comedy showcase",company:"North Beach",date:"2026-06-24",status:"3 days before"}]},calendar:{kind:"calendar",title:"Personal calendar",description:"Saved events and RSVP reminders",slots:[{day:"Thu",open:3,booked:2},{day:"Fri",open:4,booked:3},{day:"Sat",open:6,booked:5},{day:"Sun",open:5,booked:4}]},rsvp:{kind:"list",title:"RSVP tracking",description:"Confirmed, waitlisted, and pending responses",searchable:!0,columns:[{key:"name",label:"Event",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"date",label:"When",type:"date"}],data:[{name:"Design systems meetup",status:"Confirmed",date:"2026-06-18"},{name:"Neighborhood block party",status:"Waitlist",date:"2026-06-20"}]},reviews:{kind:"list",title:"Event reviews",description:"Attendee ratings and highlights",searchable:!0,columns:[{key:"name",label:"Event",type:"text"},{key:"company",label:"Reviewer",type:"text"},{key:"value",label:"Stars",type:"number"},{key:"status",label:"Highlight",type:"badge"}],data:[{name:"Night market crawl",company:"Alex M.",value:5,status:"Great vibes"},{name:"Open mic poetry",company:"Sam K.",value:4,status:"Intimate venue"}]},neighborhoods:{kind:"grid",title:"Neighborhood guides",description:"Explore events by area",searchable:!0,columns:[{key:"title",label:"Neighborhood",type:"text"},{key:"events",label:"Events",type:"number"},{key:"status",label:"Trending",type:"badge"}],data:[{title:"Mission District",events:18,status:"Hot"},{title:"Hayes Valley",events:11,status:"Rising"},{title:"Marina",events:9,status:"Steady"}]},itineraries:{kind:"list",title:"Multi-day itineraries",description:"Plans grouped by neighborhood",searchable:!0,columns:[{key:"name",label:"Itinerary",type:"text"},{key:"company",label:"Days",type:"text"},{key:"status",label:"Stops",type:"badge"}],data:[{name:"Weekend arts crawl",company:"Fri–Sun",status:"6 stops"},{name:"Foodie trail",company:"Sat–Sun",status:"4 stops"}]},interests:{kind:"grid",title:"Interest categories",description:"Topics you follow for personalized discovery",columns:[{key:"title",label:"Interest",type:"text"},{key:"events",label:"Matching events",type:"number"},{key:"status",label:"Following",type:"badge"}],data:[{title:"Live music",events:14,status:"Following"},{title:"Food & drink",events:22,status:"Following"},{title:"Outdoor",events:9,status:"Suggested"}]}}}:n==="booking"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s}
1315 — Booking platform`,userRole:"Operations Manager",navItems:[{id:"dashboard",label:"Overview",icon:"dashboard",path:"/dashboard"},{id:"calendar",label:"Calendar",icon:"calendar",path:"/calendar"},{id:"bookings",label:"Bookings",icon:"deals",path:"/bookings",badge:5},{id:"clients",label:"Clients",icon:"users",path:"/clients"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"calendar",kpis:[{label:"Bookings today",value:24,change:8,changeType:"up",description:"confirmed"},{label:"Utilization",value:"78%",change:3.2,changeType:"up",description:"slots filled"},{label:"No-shows",value:2,change:-12,changeType:"down",description:"this week"},{label:"Revenue",value:"$4,280",change:5.4,changeType:"up",description:"today"}],chart:{type:"bar",title:"Bookings by day",dataKey:"Bookings",dataPoints:u},recentColumns:[{key:"name",label:"Client",type:"avatar"},{key:"company",label:"Service",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"date",label:"Time",type:"date"}],recentRows:[{name:"Jordan Lee",company:"Consultation",status:"Confirmed",date:"2026-06-18"},{name:"Sam Park",company:"Follow-up",status:"Pending",date:"2026-06-18"}],routes:{calendar:{kind:"calendar",title:"Availability",description:"Weekly schedule with open slots",slots:[{day:"Mon",open:6,booked:4},{day:"Tue",open:8,booked:7},{day:"Wed",open:8,booked:5},{day:"Thu",open:7,booked:6},{day:"Fri",open:6,booked:3}]},bookings:{kind:"list",title:"Upcoming bookings",description:"Confirmed and pending appointments",searchable:!0,columns:[{key:"name",label:"Client",type:"avatar"},{key:"company",label:"Service",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"date",label:"When",type:"date"}],data:[{name:"Alex Rivera",company:"Haircut",status:"Confirmed",date:"2026-06-18"},{name:"Morgan Wu",company:"Color",status:"Pending",date:"2026-06-19"}]}}}:n==="saas"?{domain:r,layoutKind:n,brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s} — Team workspace`,userRole:"Workspace Admin",navItems:[{id:"dashboard",label:"Overview",icon:"dashboard",path:"/dashboard"},{id:"teams",label:"Teams",icon:"team",path:"/teams"},{id:"projects",label:"Projects",icon:"projects",path:"/projects",badge:12},{id:"billing",label:"Billing",icon:"billing",path:"/billing"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"teams",kpis:[{label:"Active teams",value:18,change:10.2,changeType:"up",description:"workspaces"},{label:"Seats used",value:"142/200",change:5,changeType:"up",description:"licensed"},{label:"MRR",value:"$18.4K",change:7.3,changeType:"up",description:"recurring"},{label:"Churn",value:"1.2%",change:-.3,changeType:"down",description:"monthly"}],chart:{type:"area",title:"Workspace activity",dataKey:"Actions",dataKey2:"Users",dataPoints:u},recentColumns:[{key:"name",label:"Team",type:"text"},{key:"company",label:"Plan",type:"badge"},{key:"status",label:"Status",type:"badge"},{key:"value",label:"Members",type:"number"}],recentRows:[{name:"Product squad",company:"Pro",status:"Active",value:14},{name:"Design guild",company:"Starter",status:"Active",value:6}],routes:{teams:{kind:"list",title:"Teams",description:"Workspaces and seat usage",searchable:!0,columns:[{key:"name",label:"Team",type:"avatar"},{key:"company",label:"Plan",type:"badge"},{key:"value",label:"Members",type:"number"},{key:"status",label:"Status",type:"badge"}],data:[{name:"Engineering",company:"Pro",value:22,status:"Active"},{name:"Marketing",company:"Pro",value:8,status:"Active"}]}}}:{domain:r,layoutKind:"crm",brand:s,glyph:i,accent:l,accentSoft:c,appTitle:`${s} — CRM`,userRole:"Account Executive",navItems:[{id:"dashboard",label:"Dashboard",icon:"dashboard",path:"/dashboard"},{id:"leads",label:"Leads",icon:"leads",path:"/leads",badge:12},{id:"contacts",label:"Contacts",icon:"contacts",path:"/contacts"},{id:"deals",label:"Deals",icon:"deals",path:"/deals"},{id:"settings",label:"Settings",icon:"settings",path:"/settings"}],primaryRoute:"leads",kpis:[{label:"Total Revenue",value:"$184,200",change:12.4,changeType:"up",description:"vs. last period"},{label:"Active Deals",value:47,change:8.1,changeType:"up",description:"live count"},{label:"Leads This Month",value:216,change:-3.2,changeType:"down",de
1315scription:"needs attention"},{label:"Win Rate",value:"34%",change:2.1,changeType:"up",description:"closed"}],chart:{type:"area",title:"Revenue over time",dataKey:"Revenue",dataKey2:"Pipeline",dataPoints:u},recentColumns:[{key:"name",label:"Name",type:"avatar"},{key:"company",label:"Company",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"value",label:"Value",type:"number"}],recentRows:[{name:"Sarah Chen",company:"Acme Corp",status:"Active",value:24e3},{name:"Marcus Webb",company:"Orbit SaaS",status:"In Progress",value:18500}],routes:{leads:{kind:"list",title:"Leads",description:"Manage leads with search, filters, and actions",searchable:!0,primaryAction:{label:"Add lead",icon:"leads"},columns:[{key:"name",label:"Name",type:"avatar"},{key:"email",label:"Email",type:"email"},{key:"company",label:"Company",type:"text"},{key:"status",label:"Status",type:"badge"},{key:"score",label:"Score",type:"number"}],data:[{name:"Sarah Chen",email:"[email protected]",company:"Acme Corp",status:"Active",score:95},{name:"Marcus Webb",email:"[email protected]",company:"Orbit SaaS",status:"Qualified",score:91}]}}}}const i7={"content.schema.json":`{
1316  "$schema": "http://json-schema.org/draft-07/schema#",
1317  "title": "DashboardContent",
1318  "description": "Slot-fill API for the dashboard-app substrate. Export this as the default from src/content.ts.",
1319  "type": "object",
1320  "required": ["meta", "navigation", "user", "dashboard", "routes"],
1321  "properties": {
1322    "meta": {
1323      "type": "object",
1324      "required": ["title", "description", "brand", "brandGlyph", "theme", "accent", "accentSoft"],
1325      "properties": {
1326        "title":       { "type": "string", "description": "Browser tab title and brand name" },
1327        "description": { "type": "string", "description": "Meta description for SEO" },
1328        "brand":       { "type": "string", "description": "Brand name shown in the sidebar" },
1329        "brandGlyph":  { "type": "string", "maxLength": 3, "description": "1-2 character logo mark, e.g. 'AC'" },
1330        "theme":       { "type": "string", "enum": ["light", "dark", "system"] },
1331        "accent":      { "type": "string", "pattern": "^#|^hsl|^rgb", "description": "Primary accent color in hex/hsl/rgb" },
1332        "accentSoft":  { "type": "string", "description": "Soft tinted version of accent for hover/backgrounds" }
1333      }
1334    },
1335    "navigation": {
1336      "type": "object",
1337      "required": ["items"],
1338      "properties": {
1339        "items": {
1340          "type": "array",
1341          "minItems": 4,
1342          "maxItems": 7,
1343          "items": {
1344            "type": "object",
1345            "required": ["id", "label", "icon", "path"],
1346            "properties": {
1347              "id":    { "type": "string" },
1348              "label": { "type": "string" },
1349              "icon":  { "type": "string" },
1350              "path":  { "type": "string", "pattern": "^/" },
1351              "badge": { "oneOf": [{ "type": "string" }, { "type": "number" }] }
1352            }
1353          }
1354        }
1355      }
1356    },
1357    "user": {
1358      "type": "object",
1359      "required": ["name", "email", "role"],
1360      "properties": {
1361        "name":   { "type": "string" },
1362        "email":  { "type": "string", "format": "email" },
1363        "avatar": { "type": "string", "description": "Image URL — omit for initials fallback" },
1364        "role":   { "type": "string" }
1365      }
1366    },
1367    "dashboard": {
1368      "type": "object",
1369      "required": ["kpis", "chart", "recentTable"],
1370      "properties": {
1371        "kpis": {
1372          "type": "array",
1373          "minItems": 2,
1374          "maxItems": 4,
1375          "items": {
1376            "type": "object",
1377            "required": ["label", "value", "change", "changeType"],
1378            "properties": {
1379              "label":       { "type": "string" },
1380              "value":       { "oneOf": [{ "type": "string" }, { "type": "number" }] },
1381              "change":      { "type": "number", "description": "Percentage change vs previous period" },
1382              "changeType":  { "type": "string", "enum": ["up", "down", "flat"] },
1383              "unit":        { "type": "string" },
1384              "prefix":      { "type": "string" },
1385              "description": { "type": "string" }
1386            }
1387          }
1388        },
1389        "chart": {
1390          "type": "object",
1391          "required": ["type", "title", "dataKey", "dataPoints"],
1392          "properties": {
1393            "type":       { "type": "string", "enum": ["line", "bar", "area"] },
1394            "title":      { "type": "string" },
1395            "dataKey":    { "type": "string", "description": "Legend label for the primary series" },
1396            "dataKey2":   { "type": "string", "description": "Legend label for the secondary series" },
1397            "dataPoints": {
1398              "type": "array",
1399              "minItems": 6,
1400              "items": {
1401                "type": "object",
1402                "required": ["label", "value"],
1403                "properties": {
1404                  "label":  { "type": "string" },
1405                  "value":  { "type": "number" },
1406                  "value2": { "type": "number" }
1407                }
1408              }
1409            }
1410          }
1411        },
1412        "recentTable": {
1413          "type": "object",
1414          "required": ["columns", "rows"],
1415          "properties": {
1416            "columns": {
1417              "type": "array",
1418              "items": {
1419                "type": "object",
1420                "required": ["key", "label", "type"],
1421                "properties": {
1422                  "key":   { "type": "string" },
1423                  "label": { "type": "string" },
1424                  "type":  { "type": "string", "enum": ["text", "badge", "avatar", "date", "number", "link", "email"] },
1425                  "width": { "type": "string" }
1426                }
1427              }
1428            },
1429            "rows": { "type": "array", "items": { "type": "object" } }
1430          }
1431        }
1432      }
1433    },
1434    "routes": {
1435      "type": "object",
1436      "description": "Keys become URL path segments, e.g. 'leads' → /leads. Must be referenced by NavItem.path.",
1437      "additionalProperties": {
1438        "oneOf": [
1439          {
1440            "title": "ListConfig",
1441            "type": "object",
1442            "required": ["kind", "title", "columns", "data"],
1443            "properties": {
1444              "kind":          { "const": "list" },
1445              "title":         { "type": "string" },
1446              "description":   { "type": "string" },
1447              "searchable":    { "type": "boolean" },
1448              "primaryAction": {
1449                "type": "object",
1450                "properties": {
1451                  "label": { "type": "string" },
1452                  "icon":  { "type": "string" }
1453                }
1454              },
1455              "columns": { "type": "array" },
1456              "data":    { "type": "array", "minItems": 5 },
1457              "rowActions": { "type": "array" }
1458            }
1459          },
1460          {
1461            "title": "DetailConfig",
1462            "type": "object",
1463            "required": ["kind", "title", "fields", "detailData"],
1464            "properties": {
1465              "kind":          { "const": "detail" },
1466              "title":         { "type": "string" },
1467              "fields":        { "type": "array" },
1468              "detailData":    { "type": "object" },
1469              "primaryAction": { "type": "object" }
1470            }
1471          }
1472        ]
1473      }
1474    },
1475    "footer": {
1476      "type": "object",
1477      "properties": {
1478        "copyright": { "type": "string" },
1479        "social": {
1480          "type": "array",
1481          "items": {
1482            "type": "object",
1483            "properties": {
1484              "platform": { "type": "string", "enum": ["twitter", "linkedin", "github", "facebook", "instagram", "youtube"] },
1485              "url": { "type": "string" }
1486            }
1487          }
1488        }
1489      }
1490    }
1491  }
1492}
1493`,"index.html":`<!doctype html>
1494<html lang="en">
1495  <head>
1496    <meta charset="UTF-8" />
1497    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
1498    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1499    <title>Dashboard</title>
1500  </head>
1501  <body>
1502    <div id="root"></div>
1503    <script type="module" src="/src/main.tsx"><\/script>
1504  </body>
1505</html>
1506`,"package.json":`{
1507  "name": "dashboard-app",
1508  "private": true,
1509  "version": "0.0.0",
1510  "type": "module",
1511  "scripts": {
1512    "dev": "vite",
1513    "build": "tsc && vite build",
1514    "preview": "vite preview"
1515  },
1516  "dependencies": {
1517    "react": "^18.3.1",
1518    "react-dom": "^18.3.1",
1519    "react-router-dom": "^6.26.2",
1520    "recharts": "^2.12.7"
1521  },
1522  "devDependencies": {
1523    "@types/react": "^18.3.5",
1524    "@types/react-dom": "^18.3.0",
1525    "@vitejs/plugin-react": "^4.3.1",
1526    "autoprefixer": "^10.4.20",
1527    "postcss": "^8.4.41",
1528    "tailwindcss": "^3.4.10",
1529    "typescript": "^5.5.3",
1530    "vite": "^5.4.2"
1531  }
1532}
1533`,"postcss.config.js":`export default {
1534  plugins: {
1535    tailwindcss: {},
1536    autoprefixer: {},
1537  },
1538}
1539`,"src/App.tsx":`import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
1540import { DashboardLayout } from '@/components/DashboardLayout'
1541import { DashboardPage } from '@/pages/DashboardPage'
1542import { ListPage } from '@/pages/ListPage'
1543import { DetailPage } from '@/pages/DetailPage'
1544import { SettingsPage } from '@/pages/SettingsPage'
1545import content from './content'
1546
1547// Apply accent CSS vars to document root for Tailwind arbitrary value usage
1548const style = document.documentElement.style
1549style.setProperty('--accent', content.meta.accent)
1550style.setProperty('--accent-soft', content.meta.accentSoft)
1551document.title = content.meta.title
1552
1553export default function App() {
1554  return (
1555    <BrowserRouter>
1556      <DashboardLayout content={content}>
1557        <Routes>
1558          {/* Dashboard home */}
1559          <Route path="/" element={<Navigate to="/dashboard" replace />} />
1560          <Route path="/dashboard" element={<DashboardPage content={content} />} />
1561
1562          {/* Settings — explicit route so it doesn't fall into the dynamic router */}
1563          <Route path="/settings" element={<SettingsPage content={content} />} />
1564
1565          {/* Dynamic routes from content.routes — list and detail pages */}
1566          <Route path="/:route" element={<ListPage content={content} />} />
1567          <Route path="/:route/detail" element={<DetailPage content={content} />} />
1568
1569          {/* 404 fallback */}
1570          <Route path="*" element={<Navigate to="/dashboard" replace />} />
1571        </Routes>
1572      </DashboardLayout>
1573    </BrowserRouter>
1574  )
1575}
1576`,"src/components/Avatar.tsx":`import { cn } from '@/lib/cn'
1577
1578interface AvatarProps {
1579  name: string
1580  src?: string
1581  size?: 'xs' | 'sm' | 'md' | 'lg'
1582  className?: string
1583}
1584
1585const sizeMap = {
1586  xs: 'w-6 h-6 text-[10px]',
1587  sm: 'w-8 h-8 text-xs',
1588  md: 'w-10 h-10 text-sm',
1589  lg: 'w-12 h-12 text-base',
1590}
1591
1592function initials(name: string): string {
1593  return name
1594    .split(' ')
1595    .filter(Boolean)
1596    .slice(0, 2)
1597    .map(n => n[0])
1598    .join('')
1599    .toUpperCase()
1600}
1601
1602const COLORS = [
1603  'bg-violet-100 text-violet-700',
1604  'bg-blue-100 text-blue-700',
1605  'bg-emerald-100 text-emerald-700',
1606  'bg-amber-100 text-amber-700',
1607  'bg-rose-100 text-rose-700',
1608  'bg-cyan-100 text-cyan-700',
1609  'bg-indigo-100 text-indigo-700',
1610  'bg-fuchsia-100 text-fuchsia-700',
1611]
1612
1613function colorFor(name: string): string {
1614  let hash = 0
1615  for (const c of name) hash = (hash * 31 + c.charCodeAt(0)) & 0xffff
1616  return COLORS[hash % COLORS.length]
1617}
1618
1619export function Avatar({ name, src, size = 'md', className }: AvatarProps) {
1620  const sizeClass = sizeMap[size]
1621  const colorClass = colorFor(name)
1622
1623  if (src) {
1624    return (
1625      <img
1626        src={src}
1627        alt={name}
1628        className={cn('rounded-full object-cover shrink-0', sizeClass, className)}
1629      />
1630    )
1631  }
1632
1633  return (
1634    <div
1635      className={cn(
1636        'rounded-full flex items-center justify-center font-semibold shrink-0 select-none',
1637        sizeClass,
1638        colorClass,
1639        className
1640      )}
1641    >
1642      {initials(name)}
1643    </div>
1644  )
1645}
1646`,"src/components/Badge.tsx":`import { cn } from '@/lib/cn'
1647
1648type BadgeVariant = 'default' | 'success' | 'warning' | 'danger' | 'info' | 'neutral' | 'purple'
1649
1650interface BadgeProps {
1651  children: React.ReactNode
1652  variant?: BadgeVariant
1653  className?: string
1654}
1655
1656const VARIANT_MAP: Record<BadgeVariant, string> = {
1657  default:  'bg-slate-100 text-slate-700',
1658  success:  'bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200/60',
1659  warning:  'bg-amber-50 text-amber-700 ring-1 ring-amber-200/60',
1660  danger:   'bg-red-50 text-red-700 ring-1 ring-red-200/60',
1661  info:     'bg-blue-50 text-blue-700 ring-1 ring-blue-200/60',
1662  neutral:  'bg-slate-50 text-slate-600 ring-1 ring-slate-200/60',
1663  purple:   'bg-violet-50 text-violet-700 ring-1 ring-violet-200/60',
1664}
1665
1666// Heuristic: map common status strings to a variant
1667const STATUS_VARIANTS: Record<string, BadgeVariant> = {
1668  'closed won':    'success',
1669  'won':           'success',
1670  'active':        'success',
1671  'customer':      'success',
1672  'completed':     'success',
1673  'done':          'success',
1674  'up':            'success',
1675  'inbound':       'info',
1676  'referral':      'info',
1677  'linkedin':      'info',
1678  'event':         'info',
1679  'qualified':     'info',
1680  'proposal':      'purple',
1681  'negotiation':   'warning',
1682  'prospect':      'warning',
1683  'in progress':   'warning',
1684  'discovery':     'warning',
1685  'new lead':      'neutral',
1686  'lead':          'neutral',
1687  'cold':          'neutral',
1688  'down':          'danger',
1689  'lost':          'danger',
1690  'closed lost':   'danger',
1691  'churn':         'danger',
1692  'delete':        'danger',
1693}
1694
1695export function inferVariant(value: string): BadgeVariant {
1696  const key = String(value).toLowerCase().trim()
1697  return STATUS_VARIANTS[key] || 'default'
1698}
1699
1700export function Badge({ children, variant, className }: BadgeProps) {
1701  const resolved = variant ?? inferVariant(String(children))
1702  return (
1703    <span
1704      className={cn(
1705        'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
1706        VARIANT_MAP[resolved],
1707        className
1708      )}
1709    >
1710      {children}
1711    </span>
1712  )
1713}
1714`,"src/components/Button.tsx":`import { cn } from '@/lib/cn'
1715import { Icon } from '@/lib/icons'
1716import type { IconName } from '@/content.types'
1717
1718type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger'
1719type ButtonSize = 'sm' | 'md' | 'lg'
1720
1721interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
1722  variant?: ButtonVariant
1723  size?: ButtonSize
1724  icon?: IconName
1725  iconPosition?: 'left' | 'right'
1726  loading?: boolean
1727  children?: React.ReactNode
1728}
1729
1730const VARIANT_MAP: Record<ButtonVariant, string> = {
1731  primary:   'bg-[var(--accent)] text-white hover:opacity-90 shadow-sm',
1732  secondary: 'bg-white text-slate-700 border border-slate-200 hover:bg-slate-50 hover:border-slate-300 shadow-sm',
1733  ghost:     'text-slate-600 hover:bg-slate-100 hover:text-slate-900',
1734  danger:    'bg-red-500 text-white hover:bg-red-600 shadow-sm',
1735}
1736
1737const SIZE_MAP: Record<ButtonSize, string> = {
1738  sm:  'h-8 px-3 text-xs gap-1.5',
1739  md:  'h-9 px-4 text-sm gap-2',
1740  lg:  'h-10 px-5 text-sm gap-2',
1741}
1742
1743export function Button({
1744  variant = 'primary',
1745  size = 'md',
1746  icon,
1747  iconPosition = 'left',
1748  loading = false,
1749  children,
1750  className,
1751  disabled,
1752  ...props
1753}: ButtonProps) {
1754  const iconSize = size === 'sm' ? 14 : 16
1755
1756  return (
1757    <button
1758      {...props}
1759      disabled={disabled || loading}
1760      className={cn(
1761        'inline-flex items-center justify-center rounded-lg font-medium transition-all duration-150 select-none',
1762        'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-1',
1763        'disabled:opacity-50 disabled:pointer-events-none',
1764        VARIANT_MAP[variant],
1765        SIZE_MAP[size],
1766        className
1767      )}
1768    >
1769      {loading && (
1770        <svg className="animate-spin" width={iconSize} height={iconSize} viewBox="0 0 24 24" fill="none">
1771          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
1772          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
1773        </svg>
1774      )}
1775      {!loading && icon && iconPosition === 'left' && <Icon name={icon} size={iconSize} />}
1776      {children && <span>{children}</span>}
1777      {!loading && icon && iconPosition === 'right' && <Icon name={icon} size={iconSize} />}
1778    </button>
1779  )
1780}
1781`,"src/components/Card.tsx":`import { cn } from '@/lib/cn'
1782
1783interface CardProps {
1784  children: React.ReactNode
1785  className?: string
1786  hover?: boolean
1787  padding?: 'none' | 'sm' | 'md' | 'lg'
1788}
1789
1790const PADDING_MAP = {
1791  none: '',
1792  sm:   'p-4',
1793  md:   'p-5',
1794  lg:   'p-6',
1795}
1796
1797export function Card({ children, className, hover = false, padding = 'md' }: CardProps) {
1798  return (
1799    <div
1800      className={cn(
1801        'bg-white rounded-xl border border-slate-200 shadow-card',
1802        hover && 'transition-shadow duration-200 hover:shadow-card-hover',
1803        PADDING_MAP[padding],
1804        className
1805      )}
1806    >
1807      {children}
1808    </div>
1809  )
1810}
1811`,"src/components/DashboardLayout.tsx":`import { Sidebar } from './Sidebar'
1812import { TopBar } from './TopBar'
1813import { Icon } from '@/lib/icons'
1814import { NavLink } from 'react-router-dom'
1815import type { DashboardContent } from '@/content.types'
1816
1817interface DashboardLayoutProps {
1818  content: DashboardContent
1819  children: React.ReactNode
1820}
1821
1822export function DashboardLayout({ content, children }: DashboardLayoutProps) {
1823  const { meta, navigation } = content
1824  const layout = meta.layoutKind || 'crm'
1825
1826  const cssVars: React.CSSProperties & Record<string, string> = {
1827    '--accent': meta.accent,
1828    '--accent-soft': meta.accentSoft,
1829  }
1830
1831  if (layout === 'social') {
1832    return (
1833      <div className="flex flex-col h-full overflow-hidden bg-violet-50/30" style={cssVars}>
1834        <header className="h-14 border-b border-violet-100 bg-white flex items-center px-4 gap-3 shrink-0">
1835          <div className="w-9 h-9 rounded-xl flex items-center justify-center text-white text-xs font-bold" style={{ background: meta.accent }}>{meta.brandGlyph}</div>
1836          <div className="flex-1 min-w-0">
1837            <div className="text-sm font-semibold text-slate-900 truncate">{meta.brand}</div>
1838            <div className="text-[11px] text-violet-600">Polls & groups</div>
1839          </div>
1840          <nav className="hidden md:flex items-center gap-1">
1841            {navigation.items.filter((i) => i.path !== '/settings').map((item) => (
1842              <NavLink key={item.id} to={item.path} className={({ isActive }) => \`px-3 py-1.5 rounded-lg text-xs font-medium \${isActive ? 'bg-violet-100 text-violet-800' : 'text-slate-500 hover:bg-slate-100'}\`}>
1843                {item.label}
1844              </NavLink>
1845            ))}
1846          </nav>
1847        </header>
1848        <div className="flex flex-1 min-h-0 overflow-hidden">
1849          <aside className="hidden lg:flex w-56 flex-col border-r border-violet-100 bg-white/80 p-4 gap-2 shrink-0">
1850            <div className="text-[11px] font-semibold uppercase tracking-wide text-violet-500 mb-1">Your groups</div>
1851            {['Weekend crew', 'Roommates', 'Book club'].map((g) => (
1852              <button key={g} type="button" className="text-left px-3 py-2 rounded-xl text-sm text-slate-700 hover:bg-violet-50">{g}</button>
1853            ))}
1854          </aside>
1855          <main className="flex-1 overflow-y-auto">
1856            <div className="max-w-3xl mx-auto p-4 md:p-6 animate-fade-in">{children}</div>
1857          </main>
1858          <aside className="hidden xl:flex w-72 flex-col border-l border-violet-100 bg-white/60 p-4 gap-3 shrink-0">
1859            <div className="text-[11px] font-semibold uppercase tracking-wide text-violet-500">Live activity</div>
1860            {['Alex voted on Dinner', 'Sam created a poll', 'Morgan joined Weekend crew'].map((t) => (
1861              <div key={t} className="text-sm text-slate-600 py-2 border-b border-violet-50">{t}</div>
1862            ))}
1863          </aside>
1864        </div>
1865      </div>
1866    )
1867  }
1868
1869  if (layout === 'events') {
1870    return (
1871      <div className="flex flex-col h-full overflow-hidden bg-rose-50/25" style={cssVars}>
1872        <header className="border-b border-rose-100 bg-white shrink-0">
1873          <div className="max-w-screen-2xl mx-auto px-4 py-3 flex items-center gap-3">
1874            <div className="w-9 h-9 rounded-xl flex items-center justify-center text-white text-xs font-bold" style={{ background: meta.accent }}>{meta.brandGlyph}</div>
1875            <div className="min-w-0">
1876              <div className="text-sm font-semibold text-rose-950 truncate">{meta.brand}</div>
1877              <div className="text-[11px] text-rose-600">Events discovery</div>
1878            </div>
1879            <div className="flex-1 max-w-xl ml-2">
1880              <input className="w-full rounded-xl border border-rose-200 px-4 py-2 text-sm" placeholder="Discover events, neighborhoods, interests..." />
1881            </div>
1882          </div>
1883          <div className="max-w-screen-2xl mx-auto px-4 pb-3 flex flex-wrap gap-2">
1884            {navigation.items.filter((i) => i.path !== '/settings').map((item) => (
1885              <NavLink key={item.id} to={item.path} className={({ isActive }) => \`px-3 py-1.5 rounded-full text-xs font-medium \${isActive ? 'text-white' : 'bg-rose-50 text-rose-800 border border-rose-100 hover:bg-rose-100'}\`} style={({ isActive }) => isActive ? { background: meta.accent } : undefined}>
1886                {item.label}{item.badge ? \` (\${item.badge})\` : ''}
1887              </NavLink>
1888            ))}
1889          </div>
1890        </header>
1891        <main className="flex-1 overflow-y-auto">
1892          <div className="max-w-screen-2xl mx-auto p-4 md:p-6 animate-fade-in">{children}</div>
1893        </main>
1894      </div>
1895    )
1896  }
1897
1898  if (layout === 'booking') {
1899    return (
1900      <div className="flex h-full overflow-hidden bg-amber-50/20" style={cssVars}>
1901        <Sidebar content={content} />
1902        <div className="flex flex-col flex-1 min-w-0 overflow-hidden">
1903          <TopBar content={content} />
1904          <main className="flex-1 overflow-y-auto">
1905            <div className="max-w-screen-2xl mx-auto p-4 md:p-6 animate-fade-in">
1906              <div className="mb-4 flex flex-wrap gap-2">
1907                {['Today', 'This week', 'Waitlist', 'Staff view'].map((chip, i) => (
1908                  <button key={chip} type="button" className={\`px-3 py-1.5 rounded-full text-xs font-medium \${i === 0 ? 'text-white' : 'bg-white border border-amber-200 text-amber-900'}\`} style={i === 0 ? { background: meta.accent } : undefined}>{chip}</button>
1909                ))}
1910              </div>
1911              {children}
1912            </div>
1913          </main>
1914        </div>
1915      </div>
1916    )
1917  }
1918
1919  if (layout === 'analytics') {
1920    return (
1921      <div className="flex h-full overflow-hidden bg-slate-100" style={cssVars}>
1922        <aside className="w-16 flex flex-col items-center py-4 gap-3 border-r border-slate-200 bg-white shrink-0">
1923          {navigation.items.slice(0, 5).map((item) => (
1924            <NavLink key={item.id} to={item.path} title={item.label} className={({ isActive }) => \`w-10 h-10 rounded-xl flex items-center justify-center \${isActive ? 'bg-sky-100 text-sky-700' : 'text-slate-400 hover:bg-slate-100'}\`}>
1925              <Icon name={item.icon} size={18} />
1926            </NavLink>
1927          ))}
1928        </aside>
1929        <div className="flex flex-col flex-1 min-w-0 overflow-hidden">
1930          <header className="h-14 border-b border-slate-200 bg-white flex items-center px-6 gap-4 shrink-0">
1931            <h2 className="text-sm font-semibold text-slate-800">Analytics workspace</h2>
1932            <div className="ml-auto flex gap-2">
1933              {['24h', '7d', '30d'].map((r, i) => (
1934                <button key={r} type="button" className={\`px-2.5 py-1 rounded-md text-xs font-medium \${i === 1 ? 'bg-sky-600 text-white' : 'text-slate-500 hover:bg-slate-100'}\`}>{r}</button>
1935              ))}
1936            </div>
1937          </header>
1938          <main className="flex-1 overflow-y-auto p-4 md:p-6">
1939            <div className="animate-fade-in">{children}</div>
1940          </main>
1941        </div>
1942      </div>
1943    )
1944  }
1945
1946  if (layout === 'marketplace') {
1947    return (
1948      <div className="flex flex-col h-full overflow-hidden bg-emerald-50/20" style={cssVars}>
1949        <header className="border-b border-emerald-100 bg-white px-4 py-3 shrink-0">
1950          <div className="max-w-screen-2xl mx-auto flex items-center gap-3">
1951            <div className="font-semibold text-emerald-800">{meta.brand}</div>
1952            <div className="flex-1 max-w-xl">
1953              <input className="w-full rounded-xl border border-emerald-200 px-4 py-2 text-sm" placeholder="Search products, vendors, categories..." />
1954            </div>
1955            <button type="button" className="rounded-xl px-4 py-2 text-sm font-medium text-white" style={{ background: meta.accent }}>Cart</button>
1956          </div>
1957        </header>
1958        <div className="flex flex-1 min-h-0 overflow-hidden">
1959          <Sidebar content={content} />
1960          <main className="flex-1 overflow-y-auto">
1961            <div className="max-w-screen-2xl mx-auto p-4 md:p-6 animate-fade-in">{children}</div>
1962          </main>
1963        </div>
1964      </div>
1965    )
1966  }
1967
1968  if (layout === 'saas') {
1969    return (
1970      <div className="flex h-full overflow-hidden bg-indigo-50/20" style={cssVars}>
1971        <aside className="w-64 flex flex-col border-r border-indigo-100 bg-white shrink-0 overflow-y-auto">
1972          <div className="p-4 border-b border-indigo-100">
1973            <div className="text-[11px] font-semibold text-indigo-500 uppercase tracking-wide">Workspace</div>
1974            <button type="button" className="mt-2 w-full flex items-center justify-between rounded-xl border border-indigo-200 px-3 py-2 text-sm font-medium text-slate-800">
1975              {meta.brand}
1976              <span className="text-slate-400">▾</span>
1977            </button>
1978            <div className="mt-3 h-2 rounded-full bg-indigo-100 overflow-hidden">
1979              <div className="h-full rounded-full" style={{ width: '71%', background: meta.accent }} />
1980            </div>
1981            <div className="text-[10px] text-slate-500 mt-1">142 / 200 seats used</div>
1982          </div>
1983          <nav className="flex-1 px-3 py-4 space-y-0.5">
1984            {navigation.items.map((item) => (
1985              <NavLink key={item.id} to={item.path} className={({ isActive }) => \`flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium \${isActive ? 'bg-indigo-100 text-indigo-900' : 'text-slate-600 hover:bg-slate-50'}\`}>
1986                <Icon name={item.icon} size={18} />
1987                <span className="flex-1">{item.label}</span>
1988                {item.badge != null && <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-indigo-100 text-indigo-700">{item.badge}</span>}
1989              </NavLink>
1990            ))}
1991          </nav>
1992        </aside>
1993        <div className="flex flex-col flex-1 min-w-0 overflow-hidden bg-slate-50">
1994          <TopBar content={content} />
1995          <main className="flex-1 overflow-y-auto">
1996            <div className="max-w-screen-2xl mx-auto p-6 animate-fade-in">{children}</div>
1997          </main>
1998        </div>
1999      </div>
2000    )
2001  }
2002
2003  return (
2004    <div className="flex h-full overflow-hidden" style={cssVars}>
2005      <Sidebar content={content} />
2006      <div className="flex flex-col flex-1 min-w-0 overflow-hidden bg-slate-50">
2007        <TopBar content={content} />
2008        <main className="flex-1 overflow-y-auto">
2009          <div className="max-w-screen-2xl mx-auto p-6 animate-fade-in">{children}</div>
2010        </main>
2011      </div>
2012    </div>
2013  )
2014}
2015`,"src/components/DataTable.tsx":`import { useState } from 'react'
2016import { Avatar } from './Avatar'
2017import { Badge, inferVariant } from './Badge'
2018import type { TableColumn } from '@/content.types'
2019import { cn } from '@/lib/cn'
2020
2021interface DataTableProps {
2022  columns: TableColumn[]
2023  rows: Record<string, unknown>[]
2024  searchable?: boolean
2025  onRowClick?: (row: Record<string, unknown>) => void
2026  className?: string
2027}
2028
2029function formatDate(val: unknown): string {
2030  if (!val) return '—'
2031  try {
2032    const d = new Date(String(val))
2033    return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
2034  } catch {
2035    return String(val)
2036  }
2037}
2038
2039function formatNumber(val: unknown): string {
2040  if (val === null || val === undefined || val === '') return '—'
2041  const n = Number(val)
2042  if (isNaN(n)) return String(val)
2043  if (n >= 1000) return new Intl.NumberFormat('en-US').format(n)
2044  return String(n)
2045}
2046
2047function CellValue({ col, value }: { col: TableColumn; value: unknown }) {
2048  const str = value === null || value === undefined ? '' : String(value)
2049
2050  switch (col.type) {
2051    case 'avatar':
2052      return (
2053        <div className="flex items-center gap-2.5">
2054          <Avatar name={str} size="sm" />
2055          <span className="text-sm font-medium text-slate-800 truncate">{str}</span>
2056        </div>
2057      )
2058
2059    case 'badge':
2060      return str ? <Badge variant={inferVariant(str)}>{str}</Badge> : <span className="text-slate-400">—</span>
2061
2062    case 'date':
2063      return <span className="text-sm text-slate-500">{formatDate(value)}</span>
2064
2065    case 'number':
2066      return <span className="text-sm font-medium text-slate-800 tabular-nums">{formatNumber(value)}</span>
2067
2068    case 'email':
2069      return (
2070        <a
2071          href={\`mailto:\${str}\`}
2072          className="text-sm text-[var(--accent)] hover:underline truncate"
2073          onClick={e => e.stopPropagation()}
2074        >
2075          {str || '—'}
2076        </a>
2077      )
2078
2079    case 'link':
2080      return str ? (
2081        <a
2082          href={str}
2083          target="_blank"
2084          rel="noopener noreferrer"
2085          className="text-sm text-[var(--accent)] hover:underline"
2086          onClick={e => e.stopPropagation()}
2087        >
2088          View ↗
2089        </a>
2090      ) : <span className="text-slate-400">—</span>
2091
2092    default:
2093      return <span className="text-sm text-slate-700 truncate">{str || '—'}</span>
2094  }
2095}
2096
2097export function DataTable({ columns, rows, searchable, onRowClick, className }: DataTableProps) {
2098  const [query, setQuery] = useState('')
2099
2100  const filtered = query.trim()
2101    ? rows.filter(row =>
2102        Object.values(row).some(v =>
2103          String(v ?? '').toLowerCase().includes(query.toLowerCase())
2104        )
2105      )
2106    : rows
2107
2108  return (
2109    <div className={cn('flex flex-col', className)}>
2110      {searchable && (
2111        <div className="mb-4">
2112          <div className="relative max-w-sm">
2113            <svg
2114              className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"
2115              width={15} height={15} viewBox="0 0 24 24"
2116              fill="none" stroke="currentColor" strokeWidth={2}
2117            >
2118              <circle cx="11" cy="11" r="8" />
2119              <path d="M21 21l-4.35-4.35" />
2120            </svg>
2121            <input
2122              type="text"
2123              placeholder="Search…"
2124              value={query}
2125              onChange={e => setQuery(e.target.value)}
2126              className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg bg-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focu
2126s:border-transparent"
2127            />
2128          </div>
2129        </div>
2130      )}
2131
2132      <div className="overflow-x-auto rounded-xl border border-slate-200 bg-white">
2133        <table className="w-full text-left min-w-[640px]">
2134          <thead>
2135            <tr className="border-b border-slate-200 bg-slate-50">
2136              {columns.map(col => (
2137                <th
2138                  key={col.key}
2139                  style={col.width ? { width: col.width } : undefined}
2140                  className="px-4 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide whitespace-nowrap"
2141                >
2142                  {col.label}
2143                </th>
2144              ))}
2145            </tr>
2146          </thead>
2147          <tbody>
2148            {filtered.length === 0 ? (
2149              <tr>
2150                <td colSpan={columns.length} className="px-4 py-12 text-center text-sm text-slate-400">
2151                  {query ? 'No results match your search.' : 'No data yet.'}
2152                </td>
2153              </tr>
2154            ) : (
2155              filtered.map((row, i) => (
2156                <tr
2157                  key={i}
2158                  onClick={() => onRowClick?.(row)}
2159                  className={cn(
2160                    'border-b border-slate-100 last:border-0 transition-colors duration-100',
2161                    onRowClick ? 'cursor-pointer hover:bg-slate-50' : 'hover:bg-slate-50/60'
2162                  )}
2163                >
2164                  {columns.map(col => (
2165                    <td
2166                      key={col.key}
2167                      style={col.width ? { width: col.width } : undefined}
2168                      className="px-4 py-3 max-w-[200px]"
2169                    >
2170                      <CellValue col={col} value={row[col.key]} />
2171                    </td>
2172                  ))}
2173                </tr>
2174              ))
2175            )}
2176          </tbody>
2177        </table>
2178      </div>
2179
2180      {filtered.length > 0 && (
2181        <p className="mt-2 text-xs text-slate-400 text-right">
2182          {filtered.length} {filtered.length === 1 ? 'row' : 'rows'}
2183          {query && \` of \${rows.length} total\`}
2184        </p>
2185      )}
2186    </div>
2187  )
2188}
2189`,"src/components/PageHeader.tsx":`import { Button } from './Button'
2190import type { IconName } from '@/content.types'
2191
2192interface PageHeaderProps {
2193  title: string
2194  description?: string
2195  primaryAction?: { label: string; icon?: IconName }
2196  onPrimaryAction?: () => void
2197  children?: React.ReactNode
2198}
2199
2200export function PageHeader({
2201  title,
2202  description,
2203  primaryAction,
2204  onPrimaryAction,
2205  children,
2206}: PageHeaderProps) {
2207  return (
2208    <div className="flex items-start justify-between mb-6">
2209      <div>
2210        <h1 className="text-xl font-semibold text-slate-900">{title}</h1>
2211        {description && (
2212          <p className="text-sm text-slate-500 mt-0.5">{description}</p>
2213        )}
2214      </div>
2215
2216      <div className="flex items-center gap-2 ml-4 shrink-0">
2217        {children}
2218        {primaryAction && (
2219          <Button
2220            variant="primary"
2221            size="sm"
2222            icon={primaryAction.icon}
2223            onClick={onPrimaryAction}
2224          >
2225            {primaryAction.label}
2226          </Button>
2227        )}
2228      </div>
2229    </div>
2230  )
2231}
2232`,"src/components/Sidebar.tsx":`import { NavLink } from 'react-router-dom'
2233import { Icon } from '@/lib/icons'
2234import { Avatar } from './Avatar'
2235import { cn } from '@/lib/cn'
2236import type { DashboardContent } from '@/content.types'
2237
2238interface SidebarProps {
2239  content: DashboardContent
2240}
2241
2242export function Sidebar({ content }: SidebarProps) {
2243  const { meta, navigation, user } = content
2244
2245  return (
2246    <aside
2247      className="w-60 flex flex-col h-full shrink-0 overflow-y-auto"
2248      style={{ background: 'var(--sidebar-bg)', borderRight: '1px solid var(--sidebar-border)' }}
2249    >
2250      {/* Brand */}
2251      <div className="px-4 py-4 flex items-center gap-3 border-b" style={{ borderColor: 'var(--sidebar-border)' }}>
2252        <div
2253          className="w-8 h-8 rounded-lg flex items-center justify-center text-white text-xs font-bold shrink-0"
2254          style={{ background: 'var(--accent)' }}
2255        >
2256          {meta.brandGlyph}
2257        </div>
2258        <span className="text-sm font-semibold truncate" style={{ color: 'var(--sidebar-active)' }}>
2259          {meta.brand}
2260        </span>
2261      </div>
2262
2263      {/* Navigation */}
2264      <nav className="flex-1 px-3 py-4 space-y-0.5">
2265        {navigation.items.map(item => (
2266          <NavLink
2267            key={item.id}
2268            to={item.path}
2269            end={item.path === '/dashboard'}
2270            className={({ isActive }) =>
2271              cn(
2272                'flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 group relative',
2273                isActive
2274                  ? 'text-white'
2275                  : 'hover:bg-white/5'
2276              )
2277            }
2278            style={({ isActive }) =>
2279              isActive
2280                ? {
2281                    color: 'var(--sidebar-active)',
2282                    background: 'var(--sidebar-active-bg)',
2283                  }
2284                : {
2285                    color: 'var(--sidebar-text)',
2286                  }
2287            }
2288          >
2289            {({ isActive }) => (
2290              <>
2291                {/* Active indicator bar */}
2292                {isActive && (
2293                  <span
2294                    className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 rounded-full"
2295                    style={{ background: 'var(--accent)' }}
2296                  />
2297                )}
2298                <Icon
2299                  name={item.icon}
2300                  size={18}
2301                  className={cn(
2302                    'shrink-0 transition-colors',
2303                    isActive
2304                      ? 'text-white opacity-90'
2305                      : 'group-hover:opacity-100 opacity-60'
2306                  )}
2307                />
2308                <span className="flex-1 truncate">{item.label}</span>
2309                {item.badge !== undefined && (
2310                  <span
2311                    className="ml-auto text-[10px] font-bold px-1.5 py-0.5 rounded-full leading-none"
2312                    style={{
2313                      background: isActive ? 'rgba(255,255,255,0.2)' : 'rgba(255,255,255,0.08)',
2314                      color: isActive ? 'white' : 'var(--sidebar-muted)',
2315                    }}
2316                  >
2317                    {item.badge}
2318                  </span>
2319                )}
2320              </>
2321            )}
2322          </NavLink>
2323        ))}
2324      </nav>
2325
2326      {/* User */}
2327      <div
2328        className="px-3 py-3 border-t flex items-center gap-3"
2329        style={{ borderColor: 'var(--sidebar-border)' }}
2330      >
2331        <Avatar name={user.name} src={user.avatar} size="sm" />
2332        <div className="flex-1 min-w-0">
2333          <p
2334            className="text-xs font-medium truncate leading-none mb-0.5"
2335            style={{ color: 'var(--sidebar-active)' }}
2336          >
2337            {user.name}
2338          </p>
2339          <p className="text-[11px] truncate leading-none" style={{ color: 'var(--sidebar-muted)' }}>
2340            {user.role}
2341          </p>
2342        </div>
2343        <button
2344          className="shrink-0 opacity-40 hover:opacity-70 transition-opacity"
2345          style={{ color: 'var(--sidebar-text)' }}
2346          title="Settings"
2347          onClick={() => {}}
2348        >
2349          <Icon name="settings" size={15} />
2350        </button>
2351      </div>
2352    </aside>
2353  )
2354}
2355`,"src/components/StatCard.tsx":`import type { KPI } from '@/content.types'
2356import { cn } from '@/lib/cn'
2357
2358interface StatCardProps {
2359  kpi: KPI
2360}
2361
2362function TrendArrow({ type }: { type: 'up' | 'down' | 'flat' }) {
2363  if (type === 'flat') return <span className="text-slate-400">→</span>
2364  return (
2365    <svg
2366      width={12}
2367      height={12}
2368      viewBox="0 0 12 12"
2369      fill="currentColor"
2370      className={cn(type === 'up' ? 'text-emerald-500' : 'text-red-500')}
2371    >
2372      {type === 'up' ? (
2373        <path d="M6 2L10 7H2L6 2Z" />
2374      ) : (
2375        <path d="M6 10L2 5H10L6 10Z" />
2376      )}
2377    </svg>
2378  )
2379}
2380
2381export function StatCard({ kpi }: StatCardProps) {
2382  const isUp = kpi.changeType === 'up'
2383  const isDown = kpi.changeType === 'down'
2384
2385  const changeColorClass = isUp
2386    ? 'text-emerald-600 bg-emerald-50'
2387    : isDown
2388      ? 'text-red-600 bg-red-50'
2389      : 'text-slate-500 bg-slate-50'
2390
2391  return (
2392    <div className="relative bg-white rounded-xl border border-slate-200 shadow-card p-5 overflow-hidden group hover:shadow-card-hover transition-shadow duration-200">
2393      {/* Accent glow on hover */}
2394      <div
2395        className="absolute inset-0 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"
2396        style={{ boxShadow: 'inset 0 0 0 1px var(--accent-soft)' }}
2397      />
2398
2399      <div className="flex items-start justify-between mb-3">
2400        <p className="text-sm font-medium text-slate-500 leading-none">{kpi.label}</p>
2401        <span
2402          className={cn(
2403            'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold',
2404            changeColorClass
2405          )}
2406        >
2407          <TrendArrow type={kpi.changeType} />
2408          {Math.abs(kpi.change)}%
2409        </span>
2410      </div>
2411
2412      <div className="flex items-baseline gap-1 mb-1">
2413        {kpi.prefix && (
2414          <span className="text-lg font-semibold text-slate-500">{kpi.prefix}</span>
2415        )}
2416        <span className="text-3xl font-bold text-slate-900 tracking-tight">
2417          {kpi.value}
2418        </span>
2419        {kpi.unit && (
2420          <span className="text-sm font-medium text-slate-500 ml-0.5">{kpi.unit}</span>
2421        )}
2422      </div>
2423
2424      {kpi.description && (
2425        <p className="text-xs text-slate-400 mt-1">{kpi.description}</p>
2426      )}
2427    </div>
2428  )
2429}
2430`,"src/components/TopBar.tsx":`import { useLocation } from 'react-router-dom'
2431import { Avatar } from './Avatar'
2432import type { DashboardContent, NavItem } from '@/content.types'
2433
2434interface TopBarProps {
2435  content: DashboardContent
2436}
2437
2438function findCurrentPage(items: NavItem[], pathname: string): NavItem | undefined {
2439  return items.find(item => {
2440    if (item.path === '/dashboard') return pathname === '/dashboard' || pathname === '/'
2441    return pathname.startsWith(item.path)
2442  })
2443}
2444
2445export function TopBar({ content }: TopBarProps) {
2446  const { user, navigation } = content
2447  const { pathname } = useLocation()
2448  const currentPage = findCurrentPage(navigation.items, pathname)
2449
2450  return (
2451    <header className="h-14 border-b border-slate-200 bg-white flex items-center px-6 gap-4 shrink-0">
2452      {/* Page title */}
2453      <div className="flex-1 min-w-0">
2454        <h2 className="text-sm font-semibold text-slate-800 truncate">
2455          {currentPage?.label ?? 'Dashboard'}
2456        </h2>
2457      </div>
2458
2459      <div className="flex items-center gap-3">
2460        {/* Notification bell */}
2461        <button className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors">
2462          <svg width={16} height={16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
2463            <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9" />
2464            <path d="M13.73 21a2 2 0 01-3.46 0" />
2465          </svg>
2466        </button>
2467
2468        {/* Search */}
2469        <button className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors">
2470          <svg width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
2471            <circle cx="11" cy="11" r="8" />
2472            <path d="M21 21l-4.35-4.35" />
2473          </svg>
2474        </button>
2475
2476        {/* User */}
2477        <div className="flex items-center gap-2 pl-3 border-l border-slate-200">
2478          <Avatar name={user.name} src={user.avatar} size="sm" />
2479          <div className="hidden sm:block">
2480            <p className="text-xs font-medium text-slate-700 leading-none">{user.name}</p>
2481            <p className="text-[11px] text-slate-400 leading-none mt-0.5">{user.role}</p>
2482          </div>
2483        </div>
2484      </div>
2485    </header>
2486  )
2487}
2488`,"src/content.ts":`// ─── Default content — CRM / Lead Management ──────────────────────────────────
2489// Edit this file to customize the dashboard for your use case.
2490// See content.types.ts for the full type reference.
2491// ──────────────────────────────────────────────────────────────────────────────
2492
2493import type { DashboardContent } from './content.types'
2494
2495const content: DashboardContent = {
2496  meta: {
2497    title: 'Attio CRM',
2498    description: 'Modern CRM for high-growth teams',
2499    brand: 'Attio',
2500    brandGlyph: 'AT',
2501    theme: 'light',
2502    accent: '#6366f1',
2503    accentSoft: '#eef2ff',
2504  },
2505
2506  navigation: {
2507    items: [
2508      { id: 'dashboard', label: 'Dashboard', icon: 'dashboard', path: '/dashboard' },
2509      { id: 'leads',     label: 'Leads',     icon: 'leads',     path: '/leads',     badge: 12 },
2510      { id: 'contacts',  label: 'Contacts',  icon: 'contacts',  path: '/contacts' },
2511      { id: 'deals',     label: 'Deals',     icon: 'deals',     path: '/deals' },
2512      { id: 'analytics', label: 'Analytics', icon: 'analytics', path: '/analytics' },
2513      { id: 'settings',  label: 'Settings',  icon: 'settings',  path: '/settings' },
2514    ],
2515  },
2516
2517  user: {
2518    name: 'Jordan Lee',
2519    email: '[email protected]',
2520    role: 'Account Executive',
2521  },
2522
2523  dashboard: {
2524    kpis: [
2525      {
2526        label: 'Total Revenue',
2527        value: '$184,200',
2528        change: 12.4,
2529        changeType: 'up',
2530        description: 'vs. last quarter',
2531      },
2532      {
2533        label: 'Active Deals',
2534        value: 47,
2535        change: 8.1,
2536        changeType: 'up',
2537        description: 'in pipeline',
2538      },
2539      {
2540        label: 'Leads This Month',
2541        value: 216,
2542        change: -3.2,
2543        changeType: 'down',
2544        description: 'vs. last month',
2545      },
2546      {
2547        label: 'Win Rate',
2548        value: '34%',
2549        change: 2.1,
2550        changeType: 'up',
2551        description: 'closed-won / total',
2552      },
2553    ],
2554
2555    chart: {
2556      type: 'area',
2557      title: 'Revenue over time',
2558      dataKey: 'Revenue',
2559      dataKey2: 'Pipeline',
2560      dataPoints: [
2561        { label: 'Jan', value: 28400,  value2: 54000 },
2562        { label: 'Feb', value: 31200,  value2: 61000 },
2563        { label: 'Mar', value: 29800,  value2: 58000 },
2564        { label: 'Apr', value: 34600,  value2: 67000 },
2565        { label: 'May', value: 38100,  value2: 72000 },
2566        { label: 'Jun', value: 36700,  value2: 69000 },
2567        { label: 'Jul', value: 41200,  value2: 78000 },
2568        { label: 'Aug', value: 43500,  value2: 83000 },
2569        { label: 'Sep', value: 47800,  value2: 91000 },
2570        { label: 'Oct', value: 44100,  value2: 85000 },
2571        { label: 'Nov', value: 51300,  value2: 97000 },
2572        { label: 'Dec', value: 58200,  value2: 108000 },
2573      ],
2574    },
2575
2576    recentTable: {
2577      columns: [
2578        { key: 'name',    label: 'Contact',  type: 'avatar' },
2579        { key: 'company', label: 'Company',  type: 'text' },
2580        { key: 'status',  label: 'Status',   type: 'badge' },
2581        { key: 'value',   label: 'Value',    type: 'number' },
2582        { key: 'date',    label: 'Updated',  type: 'date' },
2583      ],
2584      rows: [
2585        { name: 'Sarah Chen',    company: 'Acme Corp',       status: 'Qualified',  value: 24000, date: '2026-05-02' },
2586        { name: 'Marcus Webb',   company: 'Orbit SaaS',      status: 'Proposal',   value: 18500, date: '2026-05-01' },
2587        { name: 'Priya Kapoor',  company: 'NexGen Labs',     status: 'Negotiation',value: 41000, date: '2026-04-30' },
2588        { name: 'Tom Burrows',   company: 'Stellar Media',   status: 'New Lead',   value: 9200,  date: '2026-04-29' },
2589        { name: 'Amara Diallo',  company: 'Vantage AI',      status: 'Closed Won', value: 55000, date: '2026-04-28' },
2590        { name: 'Luis Moreno',   company: 'BlueSky Cloud',   status: 'Qualified',  value: 32000, date: '2026-04-27' },
2591        { name: 'Elena Soares',  company: 'Pinnacle Health',  status: 'Proposal',  value: 27500, date: '2026-04-26' },
2592      ],
2593    },
2594  },
2595
2596  routes: {
2597    leads: {
2598      kind: 'list',
2599      title: 'Leads',
2600      description: 'Manage and qualify incoming leads',
2601      searchable: true,
2602      primaryAction: { label: 'Add Lead', icon: 'leads' },
2603      columns: [
2604        { key: 'name',    label: 'Name',     type: 'avatar' },
2605        { key: 'email',   label: 'Email',    type: 'email' },
2606        { key: 'company', label: 'Company',  type: 'text' },
2607        { key: 'source',  label: 'Source',   type: 'badge' },
2608        { key: 'score',   label: 'Score',    type: 'number' },
2609        { key: 'created', label: 'Created',  type: 'date' },
2610      ],
2611      data: [
2612        { name: 'Sarah Chen',      email: '[email protected]',       company: 'Acme Corp',      source: 'Inbound',  score: 92, created: '2026-05-03' },
2613        { name: 'Marcus Webb',     email: '[email protected]',      company: 'Orbit SaaS',     source: 'Referral', score: 87, created: '2026-05-02' },
2614        { name: 'Priya Kapoor',    email: '[email protected]',      company: 'NexGen Labs',    source: 'LinkedIn', score: 81, created: '2026-05-01' },
2615        { name: 'Tom Burrows',     email: '[email protected]',    company: 'Stellar Media',  source: 'Cold',     score: 55, created: '2026-04-30' },
2616        { name: 'Amara Diallo',    email: '[email protected]',     company: 'Vantage AI',     source: 'Inbound',  score: 96, created: '2026-04-29' },
2617        { name: 'Luis Moreno',     email: '[email protected]',   company: 'BlueSky Cloud',  source: 'Event',    score: 74, created: '2026-04-28' },
2618        { name: 'Elena Soares',    email: '[email protected]', company: 'Pinnacle Health',source: 'Referral', score: 83, created: '2026-04-27' },
2619        { name: 'James Okafor',    email: '[email protected]',       company: 'Delta Systems',  source: 'LinkedIn', score: 68, created: '2026-04-26' },
2620        { name: 'Nina Petrov',     email: '[email protected]',     company: 'Arclight Co',    source: 'Cold',     score: 49, created: '2026-04-25' },
2621        { name: 'Rajesh Sharma',   email: '[email protected]',   company: 'InfoCorp India', source: 'Inbound',  score: 77, created: '2026-04-24' },
2622        { name: 'Chloe Martin',    email: '[email protected]',       company: 'Lumia France',   source: 'Event',    score: 88, created: '2026-04-23' },
2623        { name: 'David Osei',      email: '[email protected]',        company: 'Zora Ghana',     source: 'Referral', score: 71, created: '2026-04-22' },
2624      ],
2625      rowActions: [
2626        { label: 'View detail', icon: 'contacts' },
2627        { label: 'Convert to deal', icon: 'deals' },
2628        { label: 'Delete', variant: 'danger' },
2629      ],
2630    },
2631
2632    contacts: {
2633      kind: 'list',
2634      title: 'Contacts',
2635      description: 'All people in your network',
2636      searchable: true,
2637      primaryAction: { label: 'Add Contact', icon: 'contacts' },
2638      columns: [
2639        { key: 'name',    label: 'Name',     type: 'avatar' },
2640        { key: 'email',   label: 'Email',    type: 'email' },
2641        { key: 'company', label: 'Company',  type: 'text' },
2642        { key: 'role',    label: 'Role',     type: 'text' },
2643        { key: 'stage',   label: 'Stage',    type: 'badge' },
2644        { key: 'updated', label: 'Updated',  type: 'date' },
2645      ],
2646      data: [
2647        { name: 'Sarah Chen',    email: '[email protected]',      company: 'Acme Corp',      role: 'VP of Engineering',  stage: 'Customer',  updated: '2026-05-03' },
2648        { name: 'Marcus Webb',   email: '[email protected]',     company: 'Orbit SaaS',     role: 'CEO',                stage: 'Prospect',  updated: '2026-05-01' },
2649        { name: 'Priya Kapoor',  email: '[email protected]',     company: 'NexGen Labs',    role: 'CTO',                stage: 'Customer',  updated: '2026-04-30' },
2650        { name: 'Tom Burrows',   email: '[email protected]',   company: 'Stellar Media',  role: 'Head of Growth',     stage: 'Lead',      updated: '2026-04-28' },
2651        { name: 'Amara Diallo',  email: '[email protected]',    company: 'Vantage AI',     role: 'Founder',            stage: 'Customer',  updated: '2026-04-27' },
2652        { name: 'Luis Moreno',   email: '[email protected]',  company: 'BlueSky Cloud',  role: 'Director of Sales',  stage: 'Prospect',  updated: '2026-04-26' },
2653        { name: 'Elena Soares',  email: '[email protected]',company: 'Pinnacle Health',role: 'COO',                stage: 'Prospect',  updated: '2026-04-24' },
2654        { name: 'James Okafor',  email: '[email protected]',      company: 'Delta Systems',  role: 'PM',                 stage: 'Lead',      updated: '2026-04-23' },
2655        { name: 'Nina Petrov',   email: '[email protected]',    company: 'Arclight Co',    role: 'Marketing Lead',     stage: 'Lead',      updated: '2026-04-21' },
2656      ],
2657    },
2658
2659    deals: {
2660      kind: 'list',
2661      title: 'Deals',
2662      description: 'Track opportunities through your pipeline',
2663      searchable: true,
2664      primaryAction: { label: 'New Deal', icon: 'deals' },
2665      columns: [
2666        { key: 'name',    label: 'Deal',     type: 'text' },
2667        { key: 'contact', label: 'Contact',  type: 'avatar' },
2668        { key: 'stage',   label: 'Stage',    type: 'badge' },
2669        { key: 'value',   label: 'Value',    type: 'number' },
2670        { key: 'owner',   label: 'Owner',    type: 'text' },
2671        { key: 'close',   label: 'Close Date', type: 'date' },
2672      ],
2673      data: [
2674        { name: 'Acme Corp Enterprise',     contact: 'Sarah Chen',   stage: 'Proposal',    value: 48000, owner: 'Jordan Lee', close: '2026-05-30' },
2675        { name: 'Orbit SaaS Expansion',     contact: 'Marcus Webb',  stage: 'Negotiation', value: 22000, owner: 'Jordan Lee', close: '2026-05-20' },
2676        { name: 'NexGen Platform License',  contact: 'Priya Kapoor', stage: 'Proposal',    value: 61000, owner: 'Mia Torres', close: '2026-06-15' },
2677        { name: 'Vantage AI Pilot',         contact: 'Amara Diallo', stage: 'Closed Won',  value: 55000, owner: 'Jordan Lee', close: '2026-04-28' },
2678        { name: 'BlueSky Starter Pack',     contact: 'Luis Moreno',  stage: 'Qualified',   value: 14000, owner: 'Mia Torres', close: '2026-06-30' },
2679        { name: 'Pinnacle Health Annual',   contact: 'Elena Soares', stage: 'Proposal',    value: 38000, owner: 'Jordan Lee', close: '2026-05-25' },
2680        { name: 'Stellar Media Bundle',     contact: 'Tom Burrows',  stage: 'Discovery',   value: 9200,  owner: 'Mia Torres', close: '2026-07-01' },
2681        { name: 'Delta Systems Integration',contact: 'James Okafor', stage: 'Qualified',   value: 17500, owner: 'Jordan Lee', close: '2026-06-10' },
2682      ],
2683    },
2684
2685    analytics: {
2686      kind: 'list',
2687      title: 'Analytics',
2688      description: 'Performance metrics across your pipeline',
2689      searchable: false,
2690      columns: [
2691        { key: 'metric',  label: 'Metric',   type: 'text' },
2692        { key: 'current', label: 'This Month', type: 'number' },
2693        { key: 'last',    label: 'Last Month', type: 'number' },
2694        { key: 'change',  label: 'Change',   type: 'badge' },
2695        { key: 'trend',   label: 'Trend',    type: 'text' },
2696      ],
2697      data: [
2698        { metric: 'Leads Created',     current: 216, last: 223, change: '-3.1%', trend: 'Down' },
2699        { metric: 'Deals Opened',      current: 47,  last: 41,  change: '+14.6%', trend: 'Up' },
2700        { metric: 'Deals Won',         current: 16,  last: 13,  change: '+23.1%', trend: 'Up' },
2701        { metric: 'Revenue Closed',    current: 184200, last: 163800, change: '+12.4%', trend: 'Up' },
2702        { metric: 'Avg Deal Size',     current: 11513, last: 12600, change: '-8.6%', trend: 'Down' },
2703        { metric: 'Sales Cycle (days)',current: 28,  last: 34,  change: '-17.6%', trend: 'Up' },
2704        { metric: 'Win Rate',          current: 34,  last: 32,  change: '+6.3%', trend: 'Up' },
2705        { metric: 'Pipeline Value',    current: 389000, last: 341000, change: '+14.1%', trend: 'Up' },
2706      ],
2707    },
2708  },
2709
2710  footer: {
2711    copyright: '© 2026 Attio. All rights reserved.',
2712  },
2713}
2714
2715export default content
2716`,"src/content.types.ts":`// ─── Dashboard-App Substrate — Slot-Fill Content API ──────────────────────────
2717// Fill src/content.ts by exporting a value matching DashboardContent.
2718// The locked shell reads this at runtime — no component changes needed.
2719// ──────────────────────────────────────────────────────────────────────────────
2720
2721export interface NavItem {
2722  /** Unique identifier for the nav item */
2723  id: string;
2724  /** Display label in the sidebar */
2725  label: string;
2726  /** Icon key — one of the keys from ICONS in src/lib/icons.ts */
2727  icon: IconName;
2728  /** Route path, e.g. '/leads' or '/dashboard' */
2729  path: string;
2730  /** Optional badge value (count, "New", etc.) */
2731  badge?: string | number;
2732}
2733
2734export type IconName =
2735  | 'dashboard'
2736  | 'users'
2737  | 'leads'
2738  | 'deals'
2739  | 'contacts'
2740  | 'projects'
2741  | 'tasks'
2742  | 'analytics'
2743  | 'reports'
2744  | 'events'
2745  | 'calendar'
2746  | 'messages'
2747  | 'documents'
2748  | 'billing'
2749  | 'settings'
2750  | 'team'
2751  | 'integrations'
2752  | 'funnel'
2753  | 'chart-bar'
2754  | 'chart-line'
2755  | 'tag'
2756  | 'star'
2757  | 'inbox'
2758  | 'folder'
2759  | 'shield'
2760
2761export interface KPI {
2762  /** Display label */
2763  label: string;
2764  /** Current value — string for pre-formatted ("$12,400") or number */
2765  value: string | number;
2766  /** Percentage change vs previous period, e.g. 12.4 */
2767  change: number;
2768  /** Direction of the change */
2769  changeType: 'up' | 'down' | 'flat';
2770  /** Optional unit appended after value, e.g. 'ms', '%' */
2771  unit?: string;
2772  /** Optional prefix before value, e.g. '$' */
2773  prefix?: string;
2774  /** Optional description shown below value */
2775  description?: string;
2776}
2777
2778export interface ChartDataPoint {
2779  /** X-axis label — date string, category name, etc. */
2780  label: string;
2781  /** Primary series value */
2782  value: number;
2783  /** Optional secondary series value */
2784  value2?: number;
2785}
2786
2787export interface ChartConfig {
2788  /** Chart type — drives which recharts component is used */
2789  type: 'line' | 'bar' | 'area';
2790  /** Card title above the chart */
2791  title: string;
2792  /** Legend label for the primary series */
2793  dataKey: string;
2794  /** Legend label for the secondary series (if value2 present) */
2795  dataKey2?: string;
2796  /** Array of data points */
2797  dataPoints: ChartDataPoint[];
2798}
2799
2800export type ColumnType = 'text' | 'badge' | 'avatar' | 'date' | 'number' | 'link' | 'email'
2801
2802export interface TableColumn {
2803  /** Must match a key in the row objects */
2804  key: string;
2805  /** Column header label */
2806  label: string;
2807  /** Drives cell rendering */
2808  type: ColumnType;
2809  /** Optional fixed width, e.g. '120px' */
2810  width?: string;
2811}
2812
2813export interface TableConfig {
2814  columns: TableColumn[];
2815  rows: Record<string, unknown>[];
2816}
2817
2818export interface RowAction {
2819  label: string;
2820  icon?: IconName;
2821  /** 'danger' renders the action in red */
2822  variant?: 'default' | 'danger';
2823}
2824
2825export interface ListConfig {
2826  kind: 'list';
2827  /** Page heading */
2828  title: string;
2829  /** Optional subheading */
2830  description?: string;
2831  /** Table column definitions */
2832  columns: TableColumn[];
2833  /** Row data — keys must include all column.key values */
2834  data: Record<string, unknown>[];
2835  /** Show a search input */
2836  searchable?: boolean;
2837  /** Primary action button in the page header */
2838  primaryAction?: { label: string; icon?: IconName };
2839  /** Per-row kebab menu actions */
2840  rowActions?: RowAction[];
2841}
2842
2843export interface DetailField {
2844  /** Must match a key in detailData */
2845  key: string;
2846  /** Field label */
2847  label: string;
2848  /** Drives value rendering */
2849  type: 'text' | 'badge' | 'date' | 'email' | 'phone' | 'url' | 'number'
2850}
2851
2852export interface DetailConfig {
2853  kind: 'detail';
2854  /** Page heading (can include a {name} placeholder resolved from detailData) */
2855  title: string;
2856  /** Field definitions */
2857  fields: DetailField[];
2858  /** Example detail row — used for the preview */
2859  detailData: Record<string, unknown>;
2860  /** Primary action button */
2861  primaryAction?: { label: string; icon?: IconName };
2862}
2863
2864export interface SocialLink {
2865  platform: 'twitter' | 'linkedin' | 'github' | 'facebook' | 'instagram' | 'youtube';
2866  url: string;
2867}
2868
2869export interface DashboardContent {
2870  meta: {
2871    /** Browser tab title and brand name */
2872    title: string;
2873    /** Meta description */
2874    description: string;
2875    /** Brand name shown in sidebar */
2876    brand: string;
2877    /** 1–2 character glyph shown as the logo mark, e.g. 'AC' */
2878    brandGlyph: string;
2879    /** Color scheme */
2880    theme: 'light' | 'dark' | 'system';
2881    /** Primary accent color in hex or hsl, e.g. '#6366f1' */
2882    accent: string;
2883    /** Soft/tinted version of accent for backgrounds, e.g. '#eef2ff' */
2884    accentSoft: string;
2885    /** Drives dashboard layout structure — set by fast content or deepen pass */
2886    layoutKind?: 'crm' | 'social' | 'marketplace' | 'analytics' | 'booking' | 'saas' | 'events';
2887  };
2888
2889  navigation: {
2890    /** 4–7 sidebar navigation items */
2891    items: NavItem[];
2892  };
2893
2894  user: {
2895    name: string;
2896    email: string;
2897    /** URL for avatar image — omit to show initials fallback */
2898    avatar?: string;
2899    role: string;
2900  };
2901
2902  dashboard: {
2903    /** 2–4 KPI metric cards at the top of the dashboard */
2904    kpis: KPI[];
2905    /** Main chart on the dashboard page */
2906    chart: ChartConfig;
2907    /** Recent activity table below the chart */
2908    recentTable: TableConfig;
2909  };
2910
2911  /**
2912   * Additional pages beyond the dashboard.
2913   * Key → URL path segment, e.g. 'leads' maps to /leads.
2914   * Value is ListConfig (a table page) or DetailConfig (a detail view).
2915   * Must be referenced by a NavItem.path for the link to appear in the sidebar.
2916   */
2917  routes: Record<string, ListConfig | DetailConfig>;
2918
2919  footer?: {
2920    copyright: string;
2921    social?: SocialLink[];
2922  };
2923}
2924`,"src/index.css":`@tailwind base;
2925@tailwind components;
2926@tailwind utilities;
2927
2928:root {
2929  /* Accent — overridden by content.ts meta.accent */
2930  --accent: #6366f1;
2931  --accent-soft: #eef2ff;
2932
2933  /* Sidebar design tokens */
2934  --sidebar-bg: #0f172a;
2935  --sidebar-text: #94a3b8;
2936  --sidebar-muted: #475569;
2937  --sidebar-active: #e2e8f0;
2938  --sidebar-active-bg: rgba(99, 102, 241, 0.12);
2939  --sidebar-border: rgba(255, 255, 255, 0.06);
2940
2941  /* Surface */
2942  --surface: #ffffff;
2943  --surface-subtle: #f8fafc;
2944  --border: #e2e8f0;
2945  --text-primary: #0f172a;
2946  --text-secondary: #64748b;
2947  --text-muted: #94a3b8;
2948}
2949
2950* {
2951  box-sizing: border-box;
2952}
2953
2954html, body, #root {
2955  height: 100%;
2956  margin: 0;
2957  padding: 0;
2958  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Inter', Roboto, Oxygen, Ubuntu, sans-serif;
2959  -webkit-font-smoothing: antialiased;
2960  -moz-osx-font-smoothing: grayscale;
2961}
2962
2963/* Scrollbar styling */
2964::-webkit-scrollbar {
2965  width: 6px;
2966  height: 6px;
2967}
2968::-webkit-scrollbar-track {
2969  background: transparent;
2970}
2971::-webkit-scrollbar-thumb {
2972  background: #cbd5e1;
2973  border-radius: 3px;
2974}
2975::-webkit-scrollbar-thumb:hover {
2976  background: #94a3b8;
2977}
2978
2979/* Utility */
2980.truncate-2 {
2981  display: -webkit-box;
2982  -webkit-line-clamp: 2;
2983  -webkit-box-orient: vertical;
2984  overflow: hidden;
2985}
2986`,"src/lib/cn.ts":`type ClassValue = string | number | boolean | null | undefined | ClassValue[]
2987
2988function flatten(val: ClassValue): string {
2989  if (!val) return ''
2990  if (typeof val === 'string') return val
2991  if (typeof val === 'number') return String(val)
2992  if (Array.isArray(val)) return val.map(flatten).filter(Boolean).join(' ')
2993  return ''
2994}
2995
2996export function cn(...inputs: ClassValue[]): string {
2997  return inputs.map(flatten).filter(Boolean).join(' ')
2998}
2999`,"src/lib/icons.ts":`import type { IconName } from '../content.types'
3000
3001// Heroicons v2 outline paths (24x24 viewBox)
3002export const ICON_PATHS: Record<IconName, string> = {
3003  dashboard:    'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6',
3004  users:        'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0',
3005  leads:        'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01',
3006  deals:        'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2',
3007  contacts:     'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7',
3008  projects:     'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2',
3009  tasks:        'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0',
3010  analytics:    'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2',
3011  reports:      'M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2',
3012  events:       'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2',
3013  calendar:     'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2',
3014  messages:     'M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5',
3015  documents:    'M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2',
3016  billing:      'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3',
3017  settings:     'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065',
3018  team:         'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0',
3019  integrations: 'M13 10V3L4 14h7v7l9-11h-7',
3020  funnel:       'M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4',
3021  'chart-bar':  'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2',
3022  'chart-line': 'M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4',
3023  tag:          'M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4',
3024  star:         'M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674',
3025  inbox:        'M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4',
3026  folder:       'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2',
3027  shield:       'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016',
3028}
3029
3030interface IconProps {
3031  name: IconName
3032  size?: number
3033  className?: string
3034}
3035
3036import { createElement } from 'react'
3037
3038export function Icon({ name, size = 20, className = '' }: IconProps) {
3039  const path = ICON_PATHS[name] || ICON_PATHS.dashboard
3040  return createElement(
3041    'svg',
3042    {
3043      xmlns: 'http://www.w3.org/2000/svg',
3044      width: size,
3045      height: size,
3046      viewBox: '0 0 24 24',
3047      fill: 'none',
3048      stroke: 'currentColor',
3049      strokeWidth: 1.75,
3050      strokeLinecap: 'round' as const,
3051      strokeLinejoin: 'round' as const,
3052      className,
3053    },
3054    createElement('path', { d: path })
3055  )
3056}
3057`,"src/main.tsx":`import { StrictMode } from 'react'
3058import { createRoot } from 'react-dom/client'
3059import './index.css'
3060import App from './App.tsx'
3061
3062createRoot(document.getElementById('root')!).render(
3063  <StrictMode>
3064    <App />
3065  </StrictMode>,
3066)
3067`,"src/pages/DashboardPage.tsx":`import {
3068  AreaChart, Area, LineChart, Line, BarChart, Bar,
3069  XAxis, YAxis, CartesianGrid, Tooltip, Legend,
3070  ResponsiveContainer,
3071} from 'recharts'
3072import { StatCard } from '@/components/StatCard'
3073import { DataTable } from '@/components/DataTable'
3074import { Card } from '@/components/Card'
3075import type { DashboardContent } from '@/content.types'
3076
3077interface DashboardPageProps {
3078  content: DashboardContent
3079}
3080
3081function DashboardChart({ chart, accent }: { chart: DashboardContent['dashboard']['chart']; accent: string }) {
3082  const data = chart.dataPoints.map(p => ({
3083    name: p.label,
3084    [chart.dataKey]: p.value,
3085    ...(chart.dataKey2 && p.value2 !== undefined ? { [chart.dataKey2]: p.value2 } : {}),
3086  }))
3087
3088  const commonProps = {
3089    data,
3090    margin: { top: 4, right: 8, left: 0, bottom: 0 },
3091  }
3092
3093  const axisProps = {
3094    tick: { fontSize: 11, fill: '#94a3b8' },
3095    axisLine: false,
3096    tickLine: false,
3097  }
3098
3099  const chartProps = {
3100    dataKey: chart.dataKey,
3101    stroke: accent,
3102    strokeWidth: 2,
3103    dot: false,
3104    activeDot: { r: 4, strokeWidth: 0 },
3105  }
3106
3107  const chart2Props = chart.dataKey2
3108    ? {
3109        dataKey: chart.dataKey2,
3110        stroke: '#cbd5e1',
3111        strokeWidth: 1.5,
3112        dot: false,
3113        strokeDasharray: '4 2',
3114      }
3115    : null
3116
3117  return (
3118    <ResponsiveContainer width="100%" height={220}>
3119      {chart.type === 'bar' ? (
3120        <BarChart {...commonProps}>
3121          <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
3122          <XAxis dataKey="name" {...axisProps} />
3123          <YAxis {...axisProps} width={40} />
3124          <Tooltip
3125            contentStyle={{ fontSize: 12, border: '1px solid #e2e8f0', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.08)' }}
3126            cursor={{ fill: '#f8fafc' }}
3127          />
3128          {chart2Props && <Legend wrapperStyle={{ fontSize: 12 }} />}
3129          <Bar dataKey={chart.dataKey} fill={accent} radius={[4, 4, 0, 0]} />
3130          {chart.dataKey2 && <Bar dataKey={chart.dataKey2} fill="#e2e8f0" radius={[4, 4, 0, 0]} />}
3131        </BarChart>
3132      ) : chart.type === 'area' ? (
3133        <AreaChart {...commonProps}>
3134          <defs>
3135            <linearGradient id="grad1" x1="0" y1="0" x2="0" y2="1">
3136              <stop offset="5%" stopColor={accent} stopOpacity={0.12} />
3137              <stop offset="95%" stopColor={accent} stopOpacity={0} />
3138            </linearGradient>
3139            <linearGradient id="grad2" x1="0" y1="0" x2="0" y2="1">
3140              <stop offset="5%" stopColor="#94a3b8" stopOpacity={0.08} />
3141              <stop offset="95%" stopColor="#94a3b8" stopOpacity={0} />
3142            </linearGradient>
3143          </defs>
3144          <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
3145          <XAxis dataKey="name" {...axisProps} />
3146          <YAxis {...axisProps} width={40} />
3147          <Tooltip contentStyle={{ fontSize: 12, border: '1px solid #e2e8f0', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.08)' }} />
3148          {chart.dataKey2 && <Legend wrapperStyle={{ fontSize: 12 }} />}
3149          <Area {...chartProps} fill="url(#grad1)" />
3150          {chart2Props && (
3151            <Area
3152              dataKey={chart2Props.dataKey}
3153              stroke={chart2Props.stroke}
3154              strokeWidth={chart2Props.strokeWidth}
3155              strokeDasharray={chart2Props.strokeDasharray}
3156              dot={false}
3157              fill="url(#grad2)"
3158            />
3159          )}
3160        </AreaChart>
3161      ) : (
3162        <LineChart {...commonProps}>
3163          <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
3164          <XAxis dataKey="name" {...axisProps} />
3165          <YAxis {...axisProps} width={40} />
3166          <Tooltip contentStyle={{ fontSize: 12, border: '1px solid #e2e8f0', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.08)' }} />
3167          {chart.dataKey2 && <Legend wrapperStyle={{ fontSize: 12 }} />}
3168          <Line {...chartProps} />
3169          {chart2Props && (
3170            <Line
3171              dataKey={chart2Props.dataKey}
3172              stroke={chart2Props.stroke}
3173              strokeWidth={chart2Props.strokeWidth}
3174              strokeDasharray={chart2Props.strokeDasharray}
3175              dot={false}
3176            />
3177          )}
3178        </LineChart>
3179      )}
3180    </ResponsiveContainer>
3181  )
3182}
3183
3184export function DashboardPage({ content }: DashboardPageProps) {
3185  const { dashboard, meta } = content
3186  const layout = meta.layoutKind || 'crm'
3187
3188  if (layout === 'social') {
3189    return (
3190      <div className="space-y-6">
3191        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3192          {dashboard.kpis.map((kpi, i) => (
3193            <StatCard key={i} kpi={kpi} />
3194          ))}
3195        </div>
3196        <div className="grid md:grid-cols-2 gap-4">
3197          {dashboard.recentTable.rows.slice(0, 3).map((row, i) => (
3198            <Card key={i} padding="lg" className="border-violet-100">
3199              <div className="text-xs font-medium text-violet-600 mb-2">Live poll</div>
3200              <h3 className="font-semibold text-slate-900">{String((row as Record<string, unknown>).name || 'Poll')}</h3>
3201              <p className="text-sm text-slate-500 mt-1">{String((row as Record<string, unknown>).company || 'Group')}</p>
3202              <div className="mt-4 h-2 rounded-full bg-violet-100 overflow-hidden">
3203                <div className="h-full rounded-full" style={{ width: '68%', background: meta.accent }} />
3204              </div>
3205              <p className="text-xs text-slate-400 mt-2">{String((row as Record<string, unknown>).value || 0)} votes</p>
3206            </Card>
3207          ))}
3208        </div>
3209        <Card padding="lg">
3210          <h3 className="text-sm font-semibold text-slate-800 mb-4">{dashboard.chart.title}</h3>
3211          <DashboardChart chart={dashboard.chart} accent={meta.accent} />
3212        </Card>
3213      </div>
3214    )
3215  }
3216
3217  if (layout === 'events') {
3218    return (
3219      <div className="space-y-6">
3220        <div className="flex flex-wrap gap-2">
3221          {['Music', 'Food & drink', 'Art', 'Tech', 'Outdoor'].map((chip, i) => (
3222            <button key={chip} type="button" className={\`px-3 py-1.5 rounded-full text-xs font-medium \${i < 3 ? 'text-white' : 'bg-white border border-rose-200 text-rose-900'}\`} style={i < 3 ? { background: meta.accent } : undefined}>{chip}</button>
3223          ))}
3224        </div>
3225        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3226          {dashboard.kpis.map((kpi, i) => (
3227            <StatCard key={i} kpi={kpi} />
3228          ))}
3229        </div>
3230        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
3231          {dashboard.recentTable.rows.map((row, i) => (
3232            <Card key={i} padding="lg" className="border-rose-100 overflow-hidden">
3233              <div className="h-24 -mx-6 -mt-6 mb-4 bg-gradient-to-br from-rose-100 to-pink-200" />
3234              <div className="text-xs font-medium text-rose-600 mb-1">{String((row as Record<string, unknown>).company || 'Neighborhood')}</div>
3235              <h3 className="font-semibold text-slate-900">{String((row as Record<string, unknown>).name || 'Event')}</h3>
3236              <div className="mt-3 flex items-center justify-between text-sm">
3237                <span className="text-rose-700 font-medium">{String((row as Record<string, unknown>).status || 'Open')}</span>
3238                <span className="text-slate-500">★ {String((row as Record<string, unknown>).value || '4.5')}</span>
3239              </div>
3240            </Card>
3241          ))}
3242        </div>
3243        <Card padding="lg" className="border-rose-100">
3244          <h3 className="text-sm font-semibold text-slate-800 mb-2">Map & neighborhoods</h3>
3245          <p className="text-sm text-slate-500 mb-4">Explore events by area and build multi-day itineraries.</p>
3246          <div className="grid sm:grid-cols-3 gap-3">
3247            {['Mission District', 'Hayes Valley', 'Marina'].map((n) => (
3248              <div key={n} className="rounded-xl border border-rose-100 bg-rose-50/60 px-4 py-3 text-sm font-medium text-rose-900">{n}</div>
3249            ))}
3250          </div>
3251        </Card>
3252        <Card padding="lg">
3253          <DashboardChart chart={dashboard.chart} accent={meta.accent} />
3254        </Card>
3255      </div>
3256    )
3257  }
3258
3259  if (layout === 'marketplace') {
3260    return (
3261      <div className="space-y-6">
3262        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3263          {dashboard.kpis.map((kpi, i) => (
3264            <StatCard key={i} kpi={kpi} />
3265          ))}
3266        </div>
3267        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
3268          {dashboard.recentTable.rows.map((row, i) => (
3269            <Card key={i} padding="none" className="overflow-hidden">
3270              <div className="h-28 bg-gradient-to-br from-emerald-50 to-teal-100" />
3271              <div className="p-4">
3272                <div className="font-semibold text-slate-900">{String((row as Record<string, unknown>).name)}</div>
3273                <div className="text-sm text-slate-500">{String((row as Record<string, unknown>).company)}</div>
3274                <div className="mt-2 text-emerald-700 font-semibold">\${String((row as Record<string, unknown>).value)}</div>
3275              </div>
3276            </Card>
3277          ))}
3278        </div>
3279        <Card padding="lg">
3280          <DashboardChart chart={dashboard.chart} accent={meta.accent} />
3281        </Card>
3282      </div>
3283    )
3284  }
3285
3286  if (layout === 'analytics') {
3287    return (
3288      <div className="space-y-6">
3289        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3290          {dashboard.kpis.map((kpi, i) => (
3291            <StatCard key={i} kpi={kpi} />
3292          ))}
3293        </div>
3294        <Card padding="lg">
3295          <DashboardChart chart={{ ...dashboard.chart, type: 'line' }} accent={meta.accent} />
3296        </Card>
3297        <Card padding="lg">
3298          <h3 className="text-sm font-semibold text-slate-800 mb-4">Top events</h3>
3299          <div className="space-y-3">
3300            {dashboard.recentTable.rows.map((row, i) => (
3301              <div key={i} className="flex items-center justify-between py-2 border-b border-slate-100 last:border-0">
3302                <code className="text-sm text-sky-700">{String((row as Record<string, unknown>).name)}</code>
3303                <span className="text-sm font-medium text-slate-700">{String((row as Record<string, unknown>).value)}</span>
3304              </div>
3305            ))}
3306          </div>
3307        </Card>
3308      </div>
3309    )
3310  }
3311
3312  if (layout === 'booking') {
3313    return (
3314      <div className="space-y-6">
3315        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3316          {dashboard.kpis.map((kpi, i) => (
3317            <StatCard key={i} kpi={kpi} />
3318          ))}
3319        </div>
3320        <Card padding="lg">
3321          <h3 className="text-sm font-semibold text-slate-800 mb-4">This week</h3>
3322          <div className="grid grid-cols-5 gap-2">
3323            {['Mon', 'Tue', 'Wed', 'Thu', 'Fri'].map((day, i) => (
3324              <div key={day} className="rounded-xl border border-amber-100 bg-amber-50/50 p-3 text-center">
3325                <div className="text-xs text-amber-800 font-medium">{day}</div>
3326                <div className="text-lg font-bold text-slate-900 mt-1">{6 - i}</div>
3327                <div className="text-[10px] text-slate-500">open slots</div>
3328              </div>
3329            ))}
3330          </div>
3331        </Card>
3332        <Card padding="none">
3333          <div className="px-5 py-4 border-b border-slate-100">
3334            <h3 className="text-sm font-semibold text-slate-800">Upcoming</h3>
3335          </div>
3336          <div className="p-5 pt-4">
3337            <DataTable columns={dashboard.recentTable.columns} rows={dashboard.recentTable.rows} />
3338          </div>
3339        </Card>
3340      </div>
3341    )
3342  }
3343
3344  if (layout === 'saas') {
3345    return (
3346      <div className="space-y-6">
3347        <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3348          {dashboard.kpis.map((kpi, i) => (
3349            <StatCard key={i} kpi={kpi} />
3350          ))}
3351        </div>
3352        <div className="grid md:grid-cols-2 gap-4">
3353          {dashboard.recentTable.rows.map((row, i) => (
3354            <Card key={i} padding="lg" className="border-indigo-100">
3355              <div className="flex items-center justify-between mb-3">
3356                <h3 className="font-semibold text-slate-900">{String((row as Record<string, unknown>).name)}</h3>
3357                <span className="text-xs px-2 py-1 rounded-full bg-indigo-100 text-indigo-700">{String((row as Record<string, unknown>).company)}</span>
3358              </div>
3359              <div className="h-2 rounded-full bg-indigo-100 overflow-hidden mb-2">
3360                <div className="h-full rounded-full" style={{ width: \`\${40 + i * 15}%\`, background: meta.accent }} />
3361              </div>
3362              <div className="text-sm text-slate-500">{String((row as Record<string, unknown>).value)} members · {String((row as Record<string, unknown>).status)}</div>
3363            </Card>
3364          ))}
3365        </div>
3366        <Card padding="lg">
3367          <DashboardChart chart={dashboard.chart} accent={meta.accent} />
3368        </Card>
3369      </div>
3370    )
3371  }
3372
3373  return (
3374    <div className="space-y-6">
3375      {/* KPI cards */}
3376      <div className="grid grid-cols-2 xl:grid-cols-4 gap-4">
3377        {dashboard.kpis.map((kpi, i) => (
3378          <StatCard key={i} kpi={kpi} />
3379        ))}
3380      </div>
3381
3382      {/* Chart */}
3383      <Card padding="lg">
3384        <div className="flex items-center justify-between mb-5">
3385          <h3 className="text-sm font-semibold text-slate-800">{dashboard.chart.title}</h3>
3386          <div className="flex items-center gap-1">
3387            {(['7d', '30d', '90d', '12mo'] as const).map((range, i) => (
3388              <button
3389                key={range}
3390                className={\`px-2.5 py-1 text-xs rounded-md font-medium transition-colors \${
3391                  i === 3
3392                    ? 'text-white'
3393                    : 'text-slate-500 hover:bg-slate-100'
3394                }\`}
3395                style={i === 3 ? { background: 'var(--accent)' } : {}}
3396              >
3397                {range}
3398              </button>
3399            ))}
3400          </div>
3401        </div>
3402        <DashboardChart chart={dashboard.chart} accent={meta.accent} />
3403      </Card>
3404
3405      {/* Recent activity table */}
3406      <Card padding="none">
3407        <div className="px-5 py-4 border-b border-slate-100">
3408          <h3 className="text-sm font-semibold text-slate-800">Recent Activity</h3>
3409        </div>
3410        <div className="p-5 pt-4">
3411          <DataTable
3412            columns={dashboard.recentTable.columns}
3413            rows={dashboard.recentTable.rows}
3414          />
3415        </div>
3416      </Card>
3417    </div>
3418  )
3419}
3420`,"src/pages/DetailPage.tsx":`import { useParams, Link } from 'react-router-dom'
3421import { Badge, inferVariant } from '@/components/Badge'
3422import { PageHeader } from '@/components/PageHeader'
3423import { Card } from '@/components/Card'
3424import type { DashboardContent, DetailConfig } from '@/content.types'
3425
3426interface DetailPageProps {
3427  content: DashboardContent
3428}
3429
3430function formatDate(val: unknown): string {
3431  if (!val) return '—'
3432  try {
3433    const d = new Date(String(val))
3434    return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })
3435  } catch {
3436    return String(val)
3437  }
3438}
3439
3440function FieldValue({ type, value }: { type: string; value: unknown }) {
3441  const str = String(value ?? '')
3442  if (!str) return <span className="text-slate-400">—</span>
3443
3444  switch (type) {
3445    case 'badge':
3446      return <Badge variant={inferVariant(str)}>{str}</Badge>
3447    case 'email':
3448      return <a href={\`mailto:\${str}\`} className="text-[var(--accent)] hover:underline text-sm">{str}</a>
3449    case 'phone':
3450      return <a href={\`tel:\${str}\`} className="text-[var(--accent)] hover:underline text-sm">{str}</a>
3451    case 'url':
3452      return <a href={str} target="_blank" rel="noopener noreferrer" className="text-[var(--accent)] hover:underline text-sm">{str}</a>
3453    case 'date':
3454      return <span className="text-sm text-slate-700">{formatDate(value)}</span>
3455    case 'number':
3456      return <span className="text-sm font-medium text-slate-900 tabular-nums">{str}</span>
3457    default:
3458      return <span className="text-sm text-slate-800">{str}</span>
3459  }
3460}
3461
3462export function DetailPage({ content }: DetailPageProps) {
3463  const { route } = useParams<{ route: string }>()
3464  const routeKey = route ?? ''
3465  const config = content.routes[routeKey]
3466
3467  if (!config || config.kind !== 'detail') {
3468    return (
3469      <div className="flex flex-col items-center justify-center py-24 text-center">
3470        <div className="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
3471          <svg width={28} height={28} viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth={1.5}>
3472            <path d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2" />
3473          </svg>
3474        </div>
3475        <h2 className="text-sm font-semibold text-slate-700 mb-1">Page not found</h2>
3476        <p className="text-sm text-slate-400">No detail config for <code className="text-xs bg-slate-100 px-1 py-0.5 rounded">{routeKey}</code></p>
3477      </div>
3478    )
3479  }
3480
3481  const detailConfig = config as DetailConfig
3482  const data = detailConfig.detailData
3483
3484  const resolvedTitle = detailConfig.title.replace(
3485    /\\{(\\w+)\\}/g,
3486    (_, key) => String(data[key] ?? '')
3487  )
3488
3489  return (
3490    <div className="space-y-6">
3491      <div className="flex items-center gap-2 text-sm text-slate-400 mb-2">
3492        <Link to={\`/\${routeKey}\`} className="hover:text-slate-600 transition-colors capitalize">
3493          {routeKey}
3494        </Link>
3495        <span>/</span>
3496        <span className="text-slate-600">{resolvedTitle}</span>
3497      </div>
3498
3499      <PageHeader
3500        title={resolvedTitle}
3501        primaryAction={detailConfig.primaryAction}
3502      />
3503
3504      <Card>
3505        <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
3506          {detailConfig.fields.map(field => (
3507            <div key={field.key}>
3508              <dt className="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">
3509                {field.label}
3510              </dt>
3511              <dd>
3512                <FieldValue type={field.type} value={data[field.key]} />
3513              </dd>
3514            </div>
3515          ))}
3516        </div>
3517      </Card>
3518    </div>
3519  )
3520}
3521`,"src/pages/ListPage.tsx":`import { useParams } from 'react-router-dom'
3522import { PageHeader } from '@/components/PageHeader'
3523import { DataTable } from '@/components/DataTable'
3524import { Card } from '@/components/Card'
3525import type { DashboardContent, ListConfig } from '@/content.types'
3526
3527interface ListPageProps {
3528  content: DashboardContent
3529}
3530
3531function GridRoute({ config, accent }: { config: Record<string, unknown>; accent: string }) {
3532  const rows = (config.data as Record<string, unknown>[]) || []
3533  const cols = (config.columns as Array<{ key: string; label: string }>) || []
3534  return (
3535    <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
3536      {rows.map((row, i) => (
3537        <Card key={i} padding="lg" className="hover:shadow-md transition-shadow">
3538          {cols.slice(0, 2).map((col) => (
3539            <div key={col.key} className={col.key === cols[0]?.key ? 'font-semibold text-slate-900' : 'text-sm text-slate-500 mt-1'}>
3540              {String(row[col.key] ?? '')}
3541            </div>
3542          ))}
3543          <div className="mt-3 text-sm font-medium" style={{ color: accent }}>
3544            {row.price != null ? \`$\${row.price}\` : row.votes != null ? \`\${row.votes} votes\` : ''}
3545          </div>
3546        </Card>
3547      ))}
3548    </div>
3549  )
3550}
3551
3552function CalendarRoute({ config }: { config: Record<string, unknown> }) {
3553  const slots = (config.slots as Array<{ day: string; open: number; booked: number }>) || []
3554  return (
3555    <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
3556      {slots.map((slot) => (
3557        <Card key={slot.day} padding="md" className="text-center">
3558          <div className="text-xs font-medium text-amber-700">{slot.day}
3558</div>
3559          <div className="text-2xl font-bold text-slate-900 my-1">{slot.open - slot.booked}</div>
3560          <div className="text-[10px] text-slate-500">{slot.booked}/{slot.open} booked</div>
3561        </Card>
3562      ))}
3563    </div>
3564  )
3565}
3566
3567function FunnelRoute({ config, accent }: { config: Record<string, unknown>; accent: string }) {
3568  const steps = (config.steps as Array<{ label: string; value: number; rate: number }>) || []
3569  return (
3570    <div className="space-y-2 max-w-xl">
3571      {steps.map((step, i) => (
3572        <div key={step.label} className="flex items-center gap-3">
3573          <div className="w-28 text-sm text-slate-600 shrink-0">{step.label}</div>
3574          <div className="flex-1 h-8 rounded-lg bg-slate-100 overflow-hidden">
3575            <div className="h-full rounded-lg flex items-center px-2 text-xs font-medium text-white" style={{ width: \`\${step.rate}%\`, background: accent }}>
3576              {step.value.toLocaleString()}
3577            </div>
3578          </div>
3579          <div className="text-xs text-slate-500 w-10">{step.rate}%</div>
3580        </div>
3581      ))}
3582    </div>
3583  )
3584}
3585
3586export function ListPage({ content }: ListPageProps) {
3587  const { route } = useParams<{ route: string }>()
3588  const routeKey = route ?? ''
3589  const config = content.routes[routeKey] as Record<string, unknown> | undefined
3590
3591  if (!config) {
3592    return (
3593      <div className="flex flex-col items-center justify-center py-24 text-center">
3594        <h2 className="text-sm font-semibold text-slate-700 mb-1">Page not found</h2>
3595        <p className="text-sm text-slate-400">No route config for <code className="text-xs bg-slate-100 px-1 py-0.5 rounded">{routeKey}</code></p>
3596      </div>
3597    )
3598  }
3599
3600  const kind = String(config.kind || 'list')
3601  const title = String(config.title || routeKey)
3602  const description = config.description ? String(config.description) : undefined
3603
3604  if (kind === 'grid') {
3605    return (
3606      <div className="space-y-4">
3607        <PageHeader title={title} description={description} primaryAction={config.primaryAction as ListConfig['primaryAction']} />
3608        <GridRoute config={config} accent={content.meta.accent} />
3609      </div>
3610    )
3611  }
3612
3613  if (kind === 'calendar') {
3614    return (
3615      <div className="space-y-4">
3616        <PageHeader title={title} description={description} />
3617        <CalendarRoute config={config} />
3618      </div>
3619    )
3620  }
3621
3622  if (kind === 'funnel') {
3623    return (
3624      <div className="space-y-4">
3625        <PageHeader title={title} description={description} />
3626        <Card padding="lg"><FunnelRoute config={config} accent={content.meta.accent} /></Card>
3627      </div>
3628    )
3629  }
3630
3631  if (kind !== 'list') {
3632    return (
3633      <div className="space-y-4">
3634        <PageHeader title={title} description={description} />
3635        <Card padding="lg"><p className="text-sm text-slate-500">Unsupported route kind: {kind}</p></Card>
3636      </div>
3637    )
3638  }
3639
3640  const listConfig = config as ListConfig
3641
3642  return (
3643    <div className="space-y-4">
3644      <PageHeader
3645        title={listConfig.title}
3646        description={listConfig.description}
3647        primaryAction={listConfig.primaryAction}
3648      />
3649
3650      <Card padding="none">
3651        <div className="p-5">
3652          <DataTable
3653            columns={listConfig.columns}
3654            rows={listConfig.data}
3655            searchable={listConfig.searchable}
3656          />
3657        </div>
3658      </Card>
3659    </div>
3660  )
3661}
3662`,"src/pages/SettingsPage.tsx":`import { useState } from 'react'
3663import { PageHeader } from '@/components/PageHeader'
3664import { Card } from '@/components/Card'
3665import { Button } from '@/components/Button'
3666import { Avatar } from '@/components/Avatar'
3667import type { DashboardContent } from '@/content.types'
3668
3669interface SettingsPageProps {
3670  content: DashboardContent
3671}
3672
3673export function SettingsPage({ content }: SettingsPageProps) {
3674  const { user, meta } = content
3675  const [saved, setSaved] = useState(false)
3676
3677  function handleSave(e: React.FormEvent) {
3678    e.preventDefault()
3679    setSaved(true)
3680    setTimeout(() => setSaved(false), 2000)
3681  }
3682
3683  return (
3684    <div className="space-y-6 max-w-2xl">
3685      <PageHeader title="Settings" description="Manage your account and preferences" />
3686
3687      {/* Profile */}
3688      <Card>
3689        <h3 className="text-sm font-semibold text-slate-800 mb-4">Profile</h3>
3690        <form onSubmit={handleSave} className="space-y-4">
3691          <div className="flex items-center gap-4 mb-5">
3692            <Avatar name={user.name} src={user.avatar} size="lg" />
3693            <div>
3694              <p className="text-sm font-medium text-slate-700">{user.name}</p>
3695              <p className="text-xs text-slate-400 mt-0.5">{user.email}</p>
3696            </div>
3697            <Button variant="secondary" size="sm" className="ml-auto">
3698              Change photo
3699            </Button>
3700          </div>
3701
3702          <div className="grid grid-cols-2 gap-4">
3703            <SettingField label="Full name" defaultValue={user.name} />
3704            <SettingField label="Email" type="email" defaultValue={user.email} />
3705          </div>
3706          <SettingField label="Role" defaultValue={user.role} />
3707
3708          <div className="flex items-center gap-3 pt-2">
3709            <Button type="submit" variant="primary" size="sm">
3710              {saved ? 'Saved ✓' : 'Save changes'}
3711            </Button>
3712            <Button type="button" variant="ghost" size="sm">Cancel</Button>
3713          </div>
3714        </form>
3715      </Card>
3716
3717      {/* Appearance */}
3718      <Card>
3719        <h3 className="text-sm font-semibold text-slate-800 mb-4">Appearance</h3>
3720        <div className="space-y-4">
3721          <div className="flex items-center justify-between">
3722            <div>
3723              <p className="text-sm font-medium text-slate-700">Theme</p>
3724              <p className="text-xs text-slate-400 mt-0.5">Currently: {meta.theme}</p>
3725            </div>
3726            <div className="flex gap-2">
3727              {(['light', 'dark', 'system'] as const).map(t => (
3728                <button
3729                  key={t}
3730                  className={\`px-3 py-1.5 text-xs rounded-lg border font-medium transition-colors capitalize \${
3731                    meta.theme === t
3732                      ? 'border-[var(--accent)] text-[var(--accent)] bg-[var(--accent-soft)]'
3733                      : 'border-slate-200 text-slate-500 hover:bg-slate-50'
3734                  }\`}
3735                >
3736                  {t}
3737                </button>
3738              ))}
3739            </div>
3740          </div>
3741
3742          <div className="flex items-center justify-between">
3743            <div>
3744              <p className="text-sm font-medium text-slate-700">Accent color</p>
3745              <p className="text-xs text-slate-400 mt-0.5">{meta.accent}</p>
3746            </div>
3747            <div
3748              className="w-8 h-8 rounded-lg border-2 border-white shadow-sm ring-1 ring-slate-200"
3749              style={{ background: meta.accent }}
3750            />
3751          </div>
3752        </div>
3753      </Card>
3754
3755      {/* Notifications */}
3756      <Card>
3757        <h3 className="text-sm font-semibold text-slate-800 mb-4">Notifications</h3>
3758        <div className="space-y-3">
3759          {[
3760            { label: 'Email digests', description: 'Weekly summary of activity' },
3761            { label: 'New lead alerts', description: 'Instantly notify on new leads' },
3762            { label: 'Deal updates', description: 'Stage changes in your pipeline' },
3763          ].map(n => (
3764            <div key={n.label} className="flex items-center justify-between">
3765              <div>
3766                <p className="text-sm font-medium text-slate-700">{n.label}</p>
3767                <p className="text-xs text-slate-400">{n.description}</p>
3768              </div>
3769              <Toggle />
3770            </div>
3771          ))}
3772        </div>
3773      </Card>
3774    </div>
3775  )
3776}
3777
3778function SettingField({ label, defaultValue = '', type = 'text' }: { label: string; defaultValue?: string; type?: string }) {
3779  return (
3780    <div>
3781      <label className="block text-xs font-medium text-slate-600 mb-1">{label}</label>
3782      <input
3783        type={type}
3784        defaultValue={defaultValue}
3785        className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focu
3785s:border-transparent transition"
3786      />
3787    </div>
3788  )
3789}
3790
3791function Toggle() {
3792  const [on, setOn] = useState(true)
3793  return (
3794    <button
3795      onClick={() => setOn(v => !v)}
3796      className={\`relative w-9 h-5 rounded-full transition-colors duration-200 \${on ? 'bg-[var(--accent)]' : 'bg-slate-200'}\`}
3797    >
3798      <span
3799        className={\`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform duration-200 \${on ? 'translate-x-4' : 'translate-x-0'}\`}
3800      />
3801    </button>
3802  )
3803}
3804`,"tailwind.config.ts":`import type { Config } from 'tailwindcss'
3805
3806export default {
3807  content: [
3808    './index.html',
3809    './src/**/*.{js,ts,jsx,tsx}',
3810  ],
3811  theme: {
3812    extend: {
3813      colors: {
3814        accent: 'var(--accent)',
3815        'accent-soft': 'var(--accent-soft)',
3816        sidebar: {
3817          bg: 'var(--sidebar-bg)',
3818          text: 'var(--sidebar-text)',
3819          muted: 'var(--sidebar-muted)',
3820          active: 'var(--sidebar-active)',
3821          'active-bg': 'var(--sidebar-active-bg)',
3822          border: 'var(--sidebar-border)',
3823        },
3824      },
3825      boxShadow: {
3826        'card': '0 1px 3px 0 rgb(0 0 0 / 0.06), 0 1px 2px -1px rgb(0 0 0 / 0.06)',
3827        'card-hover': '0 4px 12px 0 rgb(0 0 0 / 0.08), 0 2px 4px -2px rgb(0 0 0 / 0.06)',
3828        'glow': '0 0 0 3px var(--accent-soft)',
3829      },
3830      animation: {
3831        'fade-in': 'fadeIn 0.15s ease-out',
3832        'slide-in': 'slideIn 0.2s ease-out',
3833      },
3834      keyframes: {
3835        fadeIn: {
3836          '0%': { opacity: '0' },
3837          '100%': { opacity: '1' },
3838        },
3839        slideIn: {
3840          '0%': { opacity: '0', transform: 'translateY(4px)' },
3841          '100%': { opacity: '1', transform: 'translateY(0)' },
3842        },
3843      },
3844    },
3845  },
3846  plugins: [],
3847} satisfies Config
3848`,"tsconfig.json":`{
3849  "compilerOptions": {
3850    "target": "ES2020",
3851    "useDefineForClassFields": true,
3852    "lib": ["ES2020", "DOM", "DOM.Iterable"],
3853    "module": "ESNext",
3854    "skipLibCheck": true,
3855    "moduleResolution": "bundler",
3856    "allowImportingTsExtensions": true,
3857    "resolveJsonModule": true,
3858    "isolatedModules": true,
3859    "noEmit": true,
3860    "jsx": "react-jsx",
3861    "strict": true,
3862    "noUnusedLocals": false,
3863    "noUnusedParameters": false,
3864    "noFallthroughCasesInSwitch": true,
3865    "baseUrl": ".",
3866    "paths": {
3867      "@/*": ["./src/*"]
3868    }
3869  },
3870  "include": ["src"],
3871  "references": [{ "path": "./tsconfig.node.json" }]
3872}
3873`,"tsconfig.node.json":`{
3874  "compilerOptions": {
3875    "composite": true,
3876    "skipLibCheck": true,
3877    "module": "ESNext",
3878    "moduleResolution": "bundler",
3879    "allowSyntheticDefaultImports": true,
3880    "strict": true
3881  },
3882  "include": ["vite.config.ts"]
3883}
3884`,"vite.config.ts":`import { defineConfig } from 'vite'
3885import react from '@vitejs/plugin-react'
3886import path from 'path'
3887
3888export default defineConfig({
3889  plugins: [react()],
3890  resolve: {
3891    alias: {
3892      '@': path.resolve(__dirname, './src'),
3893    },
3894  },
3895})
3896`},a0=i7;function o7(e){const t=Xw(e),r=a7(e),n=new Date().getFullYear(),s={meta:{title:r.appTitle,description:`${r.brand} — ${t.slice(0,120)||"Modern team app with live data"}`,brand:r.brand,brandGlyph:r.glyph,theme:"light",accent:r.accent,accentSoft:r.accentSoft,layoutKind:r.layoutKind},navigation:{items:r.navItems},user:{name:"Jordan Lee",email:`jordan@${r.brand.toLowerCase().replace(/\s/g,"")}.app`,role:r.userRole},dashboard:{kpis:r.kpis,chart:r.chart,recentTable:{columns:r.recentColumns,rows:r.recentRows}},routes:r.routes,footer:{copyright:`© ${n} ${r.brand}. All rights reserved.`}};return`import type { DashboardContent } from './content.types'
3897
3898const content: DashboardContent = ${JSON.stringify(s,null,2)}
3899
3900export default content
3901`}const i0={"package.json":`{
3902  "name": "saas-landing-substrate",
3903  "private": true,
3904  "version": "0.1.0",
3905  "type": "module",
3906  "scripts": {
3907    "dev": "vite",
3908    "build": "tsc -b && vite build",
3909    "preview": "vite preview"
3910  },
3911  "dependencies": {
3912    "react": "^18.3.1",
3913    "react-dom": "^18.3.1",
3914    "react-router-dom": "^6.30.1",
3915    "lucide-react": "^0.469.0",
3916    "clsx": "^2.1.1",
3917    "tailwind-merge": "^2.6.0",
3918    "class-variance-authority": "^0.7.1"
3919  },
3920  "devDependencies": {
3921    "@types/react": "^18.3.3",
3922    "@types/react-dom": "^18.3.0",
3923    "@vitejs/plugin-react": "^4.3.1",
3924    "autoprefixer": "^10.4.20",
3925    "postcss": "^8.4.49",
3926    "tailwindcss": "^3.4.17",
3927    "typescript": "^5.5.3",
3928    "vite": "^5.4.1"
3929  }
3930}
3931`,"vite.config.ts":`import { defineConfig } from 'vite';
3932import react from '@vitejs/plugin-react';
3933
3934export default defineConfig({
3935  plugins: [react()],
3936  server: { port: 5173 },
3937});
3938`,"tsconfig.json":`{
3939  "compilerOptions": {
3940    "target": "ES2022",
3941    "lib": ["ES2022", "DOM", "DOM.Iterable"],
3942    "module": "ESNext",
3943    "moduleResolution": "bundler",
3944    "jsx": "react-jsx",
3945    "strict": true,
3946    "noUnusedLocals": false,
3947    "noUnusedParameters": false,
3948    "skipLibCheck": true,
3949    "allowImportingTsExtensions": true,
3950    "noEmit": true,
3951    "isolatedModules": true,
3952    "esModuleInterop": true,
3953    "resolveJsonModule": true
3954  },
3955  "include": ["src"]
3956}
3957`,"tailwind.config.ts":`import type { Config } from 'tailwindcss';
3958
3959export default {
3960  content: ['./index.html', './src/**/*.{ts,tsx}'],
3961  darkMode: 'class',
3962  theme: {
3963    extend: {
3964      colors: {
3965        // Surface tokens — drive light/dark via CSS variables in index.css.
3966        // Content config picks an \`accent\` color from a curated palette;
3967        // shell renders it via these tokens.
3968        bg: 'rgb(var(--bg) / <alpha-value>)',
3969        surface: 'rgb(var(--surface) / <alpha-value>)',
3970        border: 'rgb(var(--border) / <alpha-value>)',
3971        text: 'rgb(var(--text) / <alpha-value>)',
3972        muted: 'rgb(var(--muted) / <alpha-value>)',
3973        accent: 'rgb(var(--accent) / <alpha-value>)',
3974        accentSoft: 'rgb(var(--accent-soft) / <alpha-value>)',
3975      },
3976      fontFamily: {
3977        sans: ['Inter', 'system-ui', '-apple-system', 'sans-serif'],
3978        display: ['"Geist"', 'Inter', 'system-ui', 'sans-serif'],
3979      },
3980      letterSpacing: {
3981        tightest: '-0.04em',
3982      },
3983      maxWidth: {
3984        page: '76rem',
3985      },
3986    },
3987  },
3988} satisfies Config;
3989`,"postcss.config.js":`export default {
3990  plugins: { tailwindcss: {}, autoprefixer: {} },
3991};
3992`,"index.html":`<!doctype html>
3993<html lang="en" class="dark">
3994  <head>
3995    <meta charset="UTF-8" />
3996    <meta name="viewport" content="width=device-width, initial-scale=1" />
3997    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
3998    <link rel="preconnect" href="https://fonts.googleapis.com" />
3999    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
4000    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet" />
4001    <title>Loading…</title>
4002  </head>
4003  <body class="bg-bg text-text antialiased">
4004    <div id="root"></div>
4005    <script type="module" src="/src/main.tsx"><\/script>
4006  </body>
4007</html>
4008`,"src/main.tsx":`import { StrictMode } from 'react';
4009import { createRoot } from 'react-dom/client';
4010import { BrowserRouter } from 'react-router-dom';
4011import { App } from './App';
4012import { content } from './content';
4013import './index.css';
4014
4015// Apply content-driven design tokens BEFORE first paint so the page never
4016// flashes a default-emerald accent before swapping. The accent value in
4017// content.meta is an "rgb r g b" triple string (e.g. "245 158 11" for amber).
4018const root = document.documentElement;
4019if (content.meta.accent) root.style.setProperty('--accent', content.meta.accent);
4020if (content.meta.accentSoft) root.style.setProperty('--accent-soft', content.meta.accentSoft);
4021root.classList.toggle('dark', content.meta.theme !== 'light');
4022document.title = content.meta.title;
4023const desc = document.querySelector('meta[name="description"]');
4024if (desc) desc.setAttribute('content', content.meta.description);
4025
4026// BrowserRouter lives here (not App.tsx) so E2B can inject basename for
4027// iframe previews without fighting duplicate-router repair loops.
4028createRoot(document.getElementById('root')!).render(
4029  <StrictMode>
4030    <BrowserRouter>
4031      <App />
4032    </BrowserRouter>
4033  </StrictMode>,
4034);
4035`,"src/App.tsx":`import { Routes, Route } from 'react-router-dom';
4036import { content } from './content';
4037import { Nav } from './components/Nav';
4038import { Footer } from './components/Footer';
4039import { HomePage } from './pages/HomePage';
4040
4041// App shell — wraps every page in the same Nav + Footer.
4042// BrowserRouter is in src/main.tsx (E2B basename injection).
4043// To add a new page (e.g. /careers, /about, /pricing):
4044//   1) Create src/pages/<Name>Page.tsx that exports a default component.
4045//   2) Optionally extend src/content.ts (and src/content.types.ts) with
4046//      content for that page so it stays config-driven.
4047//   3) Import the page above and add a new <Route path="..." element={...}/>
4048//      below. The Nav/Footer wrap it automatically.
4049export function App() {
4050  return (
4051    <div className="min-h-screen bg-bg text-text flex flex-col">
4052      <Nav nav={content.nav} brand={content.meta.brand} brandGlyph={content.meta.brandGlyph} />
4053      <main className="flex-1">
4054        <Routes>
4055          <Route path="/" element={<HomePage />} />
4056        </Routes>
4057      </main>
4058      <Footer footer={content.footer} brand={content.meta.brand} brandGlyph={content.meta.brandGlyph} />
4059    </div>
4060  );
4061}
4062`,"src/pages/HomePage.tsx":`import { content } from '../content';
4063import { Hero } from '../components/Hero';
4064import { LogoBar } from '../components/LogoBar';
4065import { Features } from '../components/Features';
4066import { Showcase } from '../components/Showcase';
4067import { Pricing } from '../components/Pricing';
4068import { Testimonials } from '../components/Testimonials';
4069import { FAQ } from '../components/FAQ';
4070import { FinalCta } from '../components/FinalCta';
4071
4072// Slot-fill home page. Sections render iff the corresponding content slot is
4073// non-null. The order is curated (proof → product → social → buy â
4073†’ objection
4074// → close) but you can rearrange when the prompt asks for it. Building a new
4075// page (Careers/About/Contact/etc.) doesn't touch this file — add it under
4076// src/pages and register the route in src/App.tsx.
4077export function HomePage() {
4078  return (
4079    <>
4080      <Hero hero={content.hero} />
4081      {content.logoBar && <LogoBar bar={content.logoBar} />}
4082      {content.features && <Features features={content.features} />}
4083      {content.showcase && <Showcase showcase={content.showcase} />}
4084      {content.pricing && <Pricing pricing={content.pricing} />}
4085      {content.testimonials && <Testimonials testimonials={content.testimonials} />}
4086      {content.faq && <FAQ faq={content.faq} />}
4087      {content.finalCta && <FinalCta finalCta={content.finalCta} />}
4088    </>
4089  );
4090}
4091
4092export default HomePage;
4093`,"src/index.css":`@tailwind base;
4094@tailwind components;
4095@tailwind utilities;
4096
4097/* Design tokens — light + dark surfaces. The \`accent\` token is overridden
4098   per-site by the content config (see content.ts → meta.accent). All
4099   components reference these tokens, never raw hex/rgb. */
4100:root {
4101  --bg: 255 255 255;             /* white */
4102  --surface: 250 250 250;        /* zinc-50 */
4103  --border: 226 232 240;         /* slate-200 */
4104  --text: 15 23 42;              /* slate-900 */
4105  --muted: 100 116 139;          /* slate-500 */
4106  --accent: 16 185 129;          /* emerald-500 (default; content config can override) */
4107  --accent-soft: 209 250 229;    /* emerald-100 */
4108}
4109
4110.dark {
4111  --bg: 9 9 11;                  /* zinc-950 */
4112  --surface: 24 24 27;           /* zinc-900 */
4113  --border: 39 39 42;            /* zinc-800 */
4114  --text: 244 244 245;           /* zinc-100 */
4115  --muted: 161 161 170;          /* zinc-400 */
4116  /* accent + accent-soft inherit from :root unless content config overrides */
4117}
4118
4119/* Tailwind utilities used so frequently across sections that they earn
4120   a class. \`section-y\` sets vertical rhythm, \`card\` sets the shared card
4121   shape so every section's grid feels consistent. */
4122@layer components {
4123  .section-y { @apply py-20 md:py-28; }
4124  .container-page { @apply mx-auto max-w-page px-6; }
4125  .card { @apply rounded-2xl border border-border bg-surface; }
4126  .btn-primary {
4127    @apply inline-flex items-center gap-2 rounded-full bg-accent px-5 py-2.5
4128           text-sm font-semibold text-bg shadow-lg shadow-accent/20
4129           transition hover:opacity-90 active:scale-[0.98];
4130  }
4131  .btn-ghost {
4132    @apply inline-flex items-center gap-2 rounded-full px-5 py-2.5
4133           text-sm font-semibold text-text/80 transition
4134           hover:bg-surface hover:text-text;
4135  }
4136  .eyebrow {
4137    @apply text-xs font-semibold uppercase tracking-[0.2em] text-accent;
4138  }
4139  .h-section { @apply text-4xl md:text-5xl font-bold tracking-tightest; }
4140  .h-hero { @apply text-5xl md:text-7xl font-bold leading-[0.95] tracking-tightest; }
4141}
4142
4143/* Headings get the display font automatically. */
4144h1, h2, h3, h4, h5, h6 { font-family: theme('fontFamily.display'); }
4145
4146/* Smooth scroll for in-page nav anchors. */
4147html { scroll-behavior: smooth; }
4148`,"src/content.types.ts":`// SLOT-FILL CONTRACT — this is what the AI emits.
4149// Every field is a string / array of objects. Zero React, zero JSX, zero
4150// HTML, zero <svg>. The shell renders all of it. This file is the ENTIRE
4151// API surface the AI has — the failure surface of a build is just whether
4152// this object validates against the SiteContent type.
4153
4154export interface SiteContent {
4155  meta: SiteMeta;
4156  nav: Nav;
4157  hero: Hero;
4158  logoBar?: LogoBar | null;
4159  features?: Features | null;
4160  showcase?: Showcase | null;
4161  pricing?: Pricing | null;
4162  testimonials?: Testimonials | null;
4163  faq?: FAQ | null;
4164  finalCta?: FinalCta | null;
4165  footer: Footer;
4166}
4167
4168export interface SiteMeta {
4169  // <title> and <meta description>
4170  title: string;
4171  description: string;
4172  // Brand short name (used as logo wordmark) and 1-letter glyph (used as logo mark).
4173  brand: string;
4174  brandGlyph: string;
4175  // Theme: 'light' | 'dark' (default 'dark'). Drives the \`.dark\` class.
4176  theme: 'light' | 'dark';
4177  // Accent color as "r g b" triple (Tailwind CSS variable format).
4178  // Examples: "16 185 129" emerald, "245 158 11" amber, "139 92 246" violet,
4179  // "59 130 246" blue, "236 72 153" pink, "239 68 68" red.
4180  accent: string;
4181  accentSoft: string; // a 10-15% saturation variant of accent
4182}
4183
4184export interface NavLink {
4185  label: string;
4186  href: string; // anchor like "#features" OR external https URL
4187}
4188export interface Nav {
4189  links: NavLink[];          // 3-6 items
4190  primaryCta: { label: string; href: string };  // e.g. "Start free"
4191  secondaryCta?: { label: string; href: string }; // e.g. "Log in"
4192}
4193
4194export interface Hero {
4195  eyebrow?: string;          // small uppercase tag above headline (optional)
4196  headline: string;          // 4-9 words; the BIG line
4197  highlightWord?: string;    // ONE word inside \`headline\` to color in accent
4198  subhead: string;           // 1-2 sentences expanding on the headline
4199  primaryCta: { label: string; href: string };
4200  secondaryCta?: { label: string; href: string };
4201  // Stats row under CTAs (optional). Each has a label + value e.g. "12k+ users"
4202  stats?: Array<{ label: string; value: string }>;
4203  // Optional hero illustration. Use stock photo URLs (Unsplash) or leave empty.
4204  image?: { src: string; alt: string } | null;
4205}
4206
4207export interface LogoBar {
4208  label: string;             // "Trusted by teams at" / "Loved by musicians at"
4209  // Plain text strings — the shell renders them as a styled wordmark row.
4210  // Avoids needing real logo SVGs which would break the slot-fill contract.
4211  brands: string[];
4212}
4213
4214export interface Feature {
4215  title: string;             // 2-4 words
4216  description: string;       // 1-2 sentences
4217  // Pick ONE icon name from the curated set in components/Features.tsx.
4218  // Available: 'sparkles', 'bolt', 'shield', 'chart', 'clock', 'users',
4219  // 'globe', 'lock', 'zap', 'star', 'check', 'cube'. Anything else falls
4220  // back to 'sparkles'.
4221  icon: string;
4222}
4223export interface Features {
4224  eyebrow?: string;          // small uppercase tag e.g. "FEATURES"
4225  headline: string;          // section title
4226  subhead?: string;
4227  items: Feature[];          // 3-6 items
4228}
4229
4230export interface AudioSample {
4231  title: string;
4232  beforeUrl: string;
4233  afterUrl: string;
4234  description?: string;
4235}
4236export interface Showcase {
4237  // Image showcase (optional when audio samples are provided).
4238  src?: string;
4239  alt?: string;
4240  caption?: string;
4241  // Before/after playable audio demos for music / podcast / audio AI products.
4242  eyebrow?: string;
4243  headline?: string;
4244  subhead?: string;
4245  samples?: AudioSample[];
4246}
4247
4248export interface PricingTier {
4249  name: string;              // "Starter" / "Pro" / "Studio"
4250  price: string;             // "$0" / "$29" / "$99" — formatted; the shell adds /mo if \`period\` set
4251  period?: string;           // "month" | "year" | undefined
4252  description: string;       // 1 sentence
4253  features: string[];        // bullet list
4254  cta: { label: string; href: string };
4255  popular?: boolean;         // shows the "Most popular" ribbon
4256}
4257export interface Pricing {
4258  eyebrow?: string;
4259  headline: string;
4260  subhead?: string;
4261  tiers: PricingTier[];      // 2-4 tiers
4262}
4263
4264export interface Testimonial {
4265  quote: string;             // 1-2 sentences
4266  author: string;            // "Sarah Chen"
4267  role: string;              // "Head of Engineering, Acme"
4268  // Optional avatar URL. If omitted, the shell renders the author's initials
4269  // in a gradient circle.
4270  avatar?: string;
4271}
4272export interface Testimonials {
4273  eyebrow?: string;
4274  headline: string;
4275  subhead?: string;
4276  items: Testimonial[];      // 3+ items
4277}
4278
4279export interface FAQItem { question: string; answer: string }
4280export interface FAQ {
4281  eyebrow?: string;
4282  headline: string;
4283  items: FAQItem[];          // 5-10 entries
4284}
4285
4286export interface FinalCta {
4287  headline: string;          // bold closing pitch
4288  subhead?: string;
4289  primaryCta: { label: string; href: string };
4290  secondaryCta?: { label: string; href: string };
4291}
4292
4293export interface FooterColumn {
4294  heading: string;           // "Product" / "Company" / "Resources"
4295  links: NavLink[];
4296}
4297export interface Footer {
4298  tagline?: string;          // 1-line summary under brand mark
4299  columns: FooterColumn[];
4300  // Social links (optional). Use icon names from a curated set: 'twitter',
4301  // 'github', 'linkedin', 'youtube', 'discord'. Anything else hides.
4302  social?: Array<{ icon: string; href: string }>;
4303  // Copyright text. The shell prepends the current year automatically.
4304  copyright: string;
4305}
4306`,"src/lib/cn.ts":`export function cn(...classes: Array<string | false | null | undefined>): string {
4307  return classes.filter(Boolean).join(' ');
4308}
4309`,"src/components/Nav.tsx":`import { Link } from 'react-router-dom';
4310import type { Nav as NavType } from '../content.types';
4311
4312// Route-aware nav link: internal hrefs ("/", "/careers", "/about") use SPA
4313// navigation via <Link>; external + anchor links (#features, https://…)
4314// fall through to a plain <a>. Lets the same content.ts links work for
4315// both single-page anchors and multi-page projects without changes.
4316function NavLink({ href, className, children }: { href: string; className?: string; children: React.ReactNode }) {
4317  const isInternal = href.startsWith('/') && !href.startsWith('//');
4318  if (isInternal) {
4319    return <Link to={href} className={className}>{children}</Link>;
4320  }
4321  return <a href={href} className={className}>{children}</a>;
4322}
4323
4324export function Nav({ nav, brand, brandGlyph }: { nav: NavType; brand: string; brandGlyph: string }) {
4325  return (
4326    <header className="sticky top-0 z-50 backdrop-blur-md bg-bg/80 border-b border-border">
4327      <nav className="container-page flex items-center justify-between py-4">
4328        <Link to="/" className="flex items-center gap-2.5 group">
4329          <span className="grid place-items-center w-9 h-9 rounded-xl bg-accent text-bg font-bold text-lg shadow-md shadow-accent/30 transition group-hover:scale-105">
4330            {brandGlyph}
4331          </span>
4332          <span className="font-display font-semibold text-text tracking-tight">{brand}</span>
4333        </Link>
4334        <div className="hidden md:flex items-center gap-7">
4335          {nav.links.map((l) => (
4336            <NavLink key={l.label} href={l.href} className="text-sm text-text/70 hover:text-text transition">
4337              {l.label}
4338            </NavLink>
4339          ))}
4340        </div>
4341        <div className="flex items-center gap-2">
4342          {nav.secondaryCta && (
4343            <NavLink href={nav.secondaryCta.href} className="btn-ghost hidden sm:inline-flex">
4344              {nav.secondaryCta.label}
4345            </NavLink>
4346          )}
4347          <NavLink href={nav.primaryCta.href} className="btn-primary">
4348            {nav.primaryCta.label}
4349          </NavLink>
4350        </div>
4351      </nav>
4352    </header>
4353  );
4354}
4355`,"src/components/Hero.tsx":`import { Link } from 'react-router-dom';
4356import type { Hero as HeroType } from '../content.types';
4357
4358function HeroCtaLink({ href, className, children }: { href: string; className?: string; children: React.ReactNode }) {
4359  const isInternal = href.startsWith('/') && !href.startsWith('//');
4360  if (isInternal) {
4361    return <Link to={href} className={className}>{children}</Link>;
4362  }
4363  return <a href={href} className={className}>{children}</a>;
4364}
4365
4366export function Hero({ hero }: { hero: HeroType }) {
4367  // If a highlightWord is provided, split the headline so we can color it.
4368  // Falls back gracefully when the word doesn't appear (rare model quirk).
4369  const renderHeadline = () => {
4370    if (!hero.highlightWord) return hero.headline;
4371    const idx = hero.headline.toLowerCase().indexOf(hero.highlightWord.toLowerCase());
4372    if (idx < 0) return hero.headline;
4373    const before = hero.headline.slice(0, idx);
4374    const word = hero.headline.slice(idx, idx + hero.highlightWord.length);
4375    const after = hero.headline.slice(idx + hero.highlightWord.length);
4376    return (
4377      <>
4378        {before}
4379        <span className="bg-gradient-to-r from-accent via-accent to-accent/70 bg-clip-text text-transparent">{word}</span>
4380        {after}
4381      </>
4382    );
4383  };
4384
4385  return (
4386    <section className="relative section-y overflow-hidden">
4387      {/* Layered ambient gradient — derives from accent so any brand color
4388          stays cohesive. Three offset blobs feel richer than a single
4389          solid wash without taxing paint. */}
4390      <div className="pointer-events-none absolute inset-0 -z-10">
4391        <div className="absolute inset-x-0 top-0 h-[640px] bg-gradient-to-b from-accent/15 via-accent/5 to-transparent" />
4392        <div className="absolute -top-32 left-1/2 -translate-x-1/2 w-[1100px] h-[620px] rounded-full bg-accent/15 blur-[120px]" />
4393        <div className="absolute top-40 left-[15%] w-[420px] h-[420px] rounded-full bg-accent/10 blur-[100px]" />
4394        <div className="absolute top-24 right-[10%] w-[360px] h-[360px] rounded-full bg-accent/10 blur-[100px]" />
4395        <div
4396          className="absolute inset-0 opacity-[0.035] mix-blend-overlay"
4397          style={{
4398            backgroundImage:
4399              'radial-gradient(currentColor 1px, transparent 1px)',
4400            backgroundSize: '32px 32px',
4401          }}
4402        />
4403      </div>
4404      <div className="container-page text-center">
4405        {hero.eyebrow && (
4406          <span className="inline-flex items-center gap-2 rounded-full border border-accent/30 bg-accent/10 px-3.5 py-1 text-xs font-semibold tracking-wide text-accent mb-6 backdrop-blur">
4407            <span className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse" />
4408            {hero.eyebrow}
4409          </span>
4410        )}
4411        <h1 className="h-hero text-text max-w-4xl mx-auto">{renderHeadline()}</h1>
4412        <p className="mt-6 text-lg md:text-xl text-text/70 max-w-2xl mx-auto leading-relaxed">
4413          {hero.subhead}
4414        </p>
4415        <div className="mt-10 flex flex-wrap items-center justify-center gap-3">
4416          <HeroCtaLink href={hero.primaryCta.href} className="btn-primary text-base px-7 py-3 hover:-translate-y-0.5 hover:shadow-2xl hover:shadow-accent/30 transition">
4417            {hero.primaryCta.label}
4418          </HeroCtaLink>
4419          {hero.secondaryCta && (
4420            <HeroCtaLink href={hero.secondaryCta.href} className="btn-ghost text-base px-7 py-3">
4421              {hero.secondaryCta.label}
4422            </HeroCtaLink>
4423          )}
4424        </div>
4425        {hero.stats && hero.stats.length > 0 && (
4426          <div className="mt-14 flex flex-wrap items-center justify-center gap-x-10 gap-y-4 text-sm text-text/60">
4427            {hero.stats.map((s, i) => (
4428              <div key={i} className="flex items-center gap-2">
4429                <span className="font-semibold text-text">{s.value}</span>
4430                <span>{s.label}</span>
4431              </div>
4432            ))}
4433          </div>
4434        )}
4435        {hero.image && (
4436          <div className="mt-16 relative max-w-5xl mx-auto">
4437            <div className="absolute -inset-4 rounded-3xl bg-gradient-to-r from-accent/20 to-transparent blur-2xl" />
4438            <img
4439              src={hero.image.src}
4440              alt={hero.image.alt}
4441              loading="eager"
4442              width={1280}
4443              height={720}
4444              className="relative rounded-2xl border border-border shadow-2xl shadow-black/30 w-full"
4445            />
4446          </div>
4447        )}
4448      </div>
4449    </section>
4450  );
4451}
4452`,"src/components/LogoBar.tsx":`import type { LogoBar as LogoBarType } from '../content.types';
4453
4454export function LogoBar({ bar }: { bar: LogoBarType }) {
4455  return (
4456    <section className="border-y border-border bg-surface/30">
4457      <div className="container-page py-12 text-center">
4458        <p className="text-xs font-medium uppercase tracking-[0.2em] text-text/60 mb-6">
4459          {bar.label}
4460        </p>
4461        <div className="flex flex-wrap items-center justify-center gap-x-10 gap-y-4 opacity-70">
4462          {bar.brands.map((b, i) => (
4463            <span key={i} className="font-display font-semibold text-text/80 text-lg tracking-tight">
4464              {b}
4465            </span>
4466          ))}
4467        </div>
4468      </div>
4469    </section>
4470  );
4471}
4472`,"src/components/Features.tsx":`import type { Features as FeaturesType } from '../content.types';
4473
4474// Curated icon set — 12 SVG paths the AI can pick from by name. Keeping this
4475// inside the locked shell means the AI never emits raw <svg> markup, so the
4476// "giant unsized SVG eats the page" bug class is structurally impossible.
4477const ICONS: Record<string, JSX.Element> = {
4478  sparkles: <path d="M12 3l1.6 4.3L18 9l-4.4 1.7L12 15l-1.6-4.3L6 9l4.4-1.7L12 3zm6 9l.9 2.4L21 15l-2.1.6L18 18l-.9-2.4L15 15l2.1-.6L18 12z" />,
4479  bolt: <path d="M13 2L3 14h7l-1 8 10-12h-7l1-8z" />,
4480  shield: <path d="M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z" />,
4481  chart: <path d="M3 3v18h18M7 14l4-4 4 4 5-7" />,
4482  clock: <><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></>,
4483  users: <><circle cx="9" cy="8" r="4" /><path d="M2 21c0-3.9 3.1-7 7-7s7 3.1 7 7M16 11a4 4 0 100-8M22 21c0-3.5-2.5-6.5-6-7" /></>,
4484  globe: <><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18" /></>,
4485  lock: <><rect x="4" y="11" width="16" height="10" rx="2" /><path d="M8 11V7a4 4 0 018 0v4" /></>,
4486  zap: <path d="M13 2L3 14h7l-1 8 10-12h-7l1-8z" />,
4487  star: <path d="M12 2l3 6.5 7 1-5 5 1.2 7L12 18l-6.2 3.5L7 14.5l-5-5 7-1L12 2z" />,
4488  check: <path d="M5 12l5 5 9-12" />,
4489  cube: <path d="M12 3l9 5v8l-9 5-9-5V8l9-5zM3 8l9 5 9-5M12 13v9" />,
4490};
4491
4492function Icon({ name }: { name: string }) {
4493  const path = ICONS[name] || ICONS.sparkles;
4494  return (
4495    <svg
4496      width="24"
4497      height="24"
4498      viewBox="0 0 24 24"
4499      fill="none"
4500      stroke="currentColor"
4501      strokeWidth="2"
4502      strokeLinecap="round"
4503      strokeLinejoin="round"
4504      aria-hidden="true"
4505    >
4506      {path}
4507    </svg>
4508  );
4509}
4510
4511export function Features({ features }: { features: FeaturesType }) {
4512  return (
4513    <section id="features" className="section-y">
4514      <div className="container-page">
4515        <div className="text-center max-w-2xl mx-auto">
4516          {features.eyebrow && <p className="eyebrow mb-3">{features.eyebrow}</p>}
4517          <h2 className="h-section text-text">{features.headline}</h2>
4518          {features.subhead && (
4519            <p className="mt-4 text-lg text-text/70 leading-relaxed">{features.subhead}</p>
4520          )}
4521        </div>
4522        <div className="mt-16 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
4523          {features.items.map((f, i) => (
4524            <div key={i}
4524 className="card p-7 hover:border-accent/40 transition-colors">
4525              <div className="grid place-items-center w-11 h-11 rounded-xl bg-accent/10 text-accent mb-5">
4526                <Icon name={f.icon} />
4527              </div>
4528              <h3 className="font-display font-semibold text-lg text-text">{f.title}</h3>
4529              <p className="mt-2 text-text/70 leading-relaxed">{f.description}</p>
4530            </div>
4531          ))}
4532        </div>
4533      </div>
4534    </section>
4535  );
4536}
4537`,"src/components/Showcase.tsx":`import type { Showcase as ShowcaseType } from '../content.types';
4538
4539export function Showcase({ showcase }: { showcase: ShowcaseType }) {
4540  if (showcase.samples && showcase.samples.length > 0) {
4541    return (
4542      <section id="showcase" className="section-y">
4543        <div className="container-page">
4544          {(showcase.eyebrow || showcase.headline) && (
4545            <div className="text-center max-w-2xl mx-auto mb-14">
4546              {showcase.eyebrow && <p className="eyebrow mb-3">{showcase.eyebrow}</p>}
4547              {showcase.headline && <h2 className="h-section text-text">{showcase.headline}</h2>}
4548              {showcase.subhead && (
4549                <p className="mt-4 text-lg text-text/70 leading-relaxed">{showcase.subhead}</p>
4550              )}
4551            </div>
4552          )}
4553          <div className="grid gap-6 md:grid-cols-2 max-w-5xl mx-auto">
4554            {showcase.samples.map((sample, i) => (
4555              <div key={i} className="card p-6 md:p-7 hover:border-accent/40 transition">
4556                <h3 className="font-display font-semibold text-lg text-text">{sample.title}</h3>
4557                {sample.description && (
4558                  <p className="mt-1 text-sm text-text/60 leading-relaxed">{sample.description}</p>
4559                )}
4560                <div className="mt-5 space-y-4">
4561                  <div>
4562                    <p className="text-xs font-semibold uppercase tracking-wider text-text/50 mb-2">Before</p>
4563                    <audio controls preload="none" className="w-full h-10" src={sample.beforeUrl} />
4564                  </div>
4565                  <div>
4566                    <p className="text-xs font-semibold uppercase tracking-wider text-accent mb-2">After AI</p>
4567                    <audio controls preload="none" className="w-full h-10" src={sample.afterUrl} />
4568                  </div>
4569                </div>
4570              </div>
4571            ))}
4572          </div>
4573        </div>
4574      </section>
4575    );
4576  }
4577
4578  if (!showcase.src) return null;
4579
4580  return (
4581    <section className="section-y">
4582      <div className="container-page">
4583        <div className="relative max-w-6xl mx-auto">
4584          <div className="absolute -inset-6 rounded-3xl bg-gradient-to-r from-accent/15 to-transparent blur-3xl" />
4585          <img
4586            src={showcase.src}
4587            alt={showcase.alt || ''}
4588            loading="lazy"
4589            width={1280}
4590            height={720}
4591            className="relative rounded-2xl border border-border shadow-2xl shadow-black/30 w-full"
4592          />
4593          {showcase.caption && (
4594            <p className="mt-6 text-center text-sm text-text/60">{showcase.caption}</p>
4595          )}
4596        </div>
4597      </div>
4598    </section>
4599  );
4600}
4601`,"src/components/Pricing.tsx":`import type { Pricing as PricingType } from '../content.types';
4602import { cn } from '../lib/cn';
4603
4604export function Pricing({ pricing }: { pricing: PricingType }) {
4605  return (
4606    <section id="pricing" className="section-y">
4607      <div className="container-page">
4608        <div className="text-center max-w-2xl mx-auto">
4609          {pricing.eyebrow && <p className="eyebrow mb-3">{pricing.eyebrow}</p>}
4610          <h2 className="h-section text-text">{pricing.headline}</h2>
4611          {pricing.subhead && (
4612            <p className="mt-4 text-lg text-text/70 leading-relaxed">{pricing.subhead}</p>
4613          )}
4614        </div>
4615        <div className={cn(
4616          'mt-16 grid gap-5',
4617          pricing.tiers.length === 2 && 'sm:grid-cols-2 max-w-3xl mx-auto',
4618          pricing.tiers.length === 3 && 'lg:grid-cols-3',
4619          pricing.tiers.length === 4 && 'sm:grid-cols-2 lg:grid-cols-4',
4620        )}>
4621          {pricing.tiers.map((t, i) => (
4622            <div
4623              key={i}
4624              className={cn(
4625                'card p-7 relative flex flex-col',
4626                t.popular && 'border-accent shadow-xl shadow-accent/10 scale-[1.02]',
4627              )}
4628            >
4629              {t.popular && (
4630                <span className="absolute -top-3 left-1/2 -translate-x-1/2 rounded-full bg-accent text-bg px-3 py-1 text-xs font-semibold">
4631                  Most popular
4632                </span>
4633              )}
4634              <h3 className="font-display text-lg font-semibold text-text">{t.name}</h3>
4635              <p className="mt-1 text-sm text-text/60 leading-relaxed">{t.description}</p>
4636              <div className="mt-5 flex items-baseline gap-1">
4637                <span className="text-4xl font-bold tracking-tightest text-text">{t.price}</span>
4638                {t.period && <span className="text-sm text-text/60">/{t.period}</span>}
4639              </div>
4640              <ul className="mt-6 space-y-2.5 flex-1">
4641                {t.features.map((f, j) => (
4642                  <li key={j} className="flex items-start gap-2.5 text-sm text-text/80">
4643                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="text-accent shrink-0 mt-0.5">
4644                      <path d="M5 12l5 5 9-12" strokeLinecap="round" strokeLinejoin="round" />
4645                    </svg>
4646                    {f}
4647                  </li>
4648                ))}
4649              </ul>
4650              <a
4651                href={t.cta.href}
4652                className={cn(
4653                  'mt-7 w-full text-center',
4654                  t.popular ? 'btn-primary justify-center' : 'btn-ghost justify-center bg-surface',
4655                )}
4656              >
4657                {t.cta.label}
4658              </a>
4659            </div>
4660          ))}
4661        </div>
4662      </div>
4663    </section>
4664  );
4665}
4666`,"src/components/Testimonials.tsx":`import type { Testimonials as TestimonialsType } from '../content.types';
4667
4668function initials(name: string): string {
4669  return name
4670    .split(/\\s+/)
4671    .map((p) => p[0])
4672    .filter(Boolean)
4673    .slice(0, 2)
4674    .join('')
4675    .toUpperCase();
4676}
4677
4678export function Testimonials({ testimonials }: { testimonials: TestimonialsType }) {
4679  return (
4680    <section className="section-y bg-surface/30">
4681      <div className="container-page">
4682        <div className="text-center max-w-2xl mx-auto">
4683          {testimonials.eyebrow && <p className="eyebrow mb-3">{testimonials.eyebrow}</p>}
4684          <h2 className="h-section text-text">{testimonials.headline}</h2>
4685          {testimonials.subhead && (
4686            <p className="mt-4 text-lg text-text/70 leading-relaxed">{testimonials.subhead}</p>
4687          )}
4688        </div>
4689        <div className="mt-16 grid gap-5 md:grid-cols-2 lg:grid-cols-3">
4690          {testimonials.items.map((t, i) => (
4691            <figure key={i}
4691 className="card p-7 flex flex-col">
4692              <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor" className="text-accent/40 mb-4">
4693                <path d="M3 17l3-6H4V7h6v4l-3 6H3zm10 0l3-6h-2V7h6v4l-3 6h-4z" />
4694              </svg>
4695              <blockquote className="text-text leading-relaxed flex-1">{t.quote}</blockquote>
4696              <figcaption className="mt-6 flex items-center gap-3">
4697                {t.avatar ? (
4698                  <img
4699                    src={t.avatar}
4700                    alt={t.author}
4701                    width="40"
4702                    height="40"
4703                    loading="lazy"
4704                    className="rounded-full object-cover w-10 h-10"
4705                  />
4706                ) : (
4707                  <span className="grid place-items-center rounded-full w-10 h-10 bg-gradient-to-br from-accent/40 to-accent/10 text-text font-semibold text-sm">
4708                    {initials(t.author)}
4709                  </span>
4710                )}
4711                <div>
4712                  <div className="font-semibold text-text text-sm">{t.author}</div>
4713                  <div className="text-xs text-text/60">{t.role}</div>
4714                </div>
4715              </figcaption>
4716            </figure>
4717          ))}
4718        </div>
4719      </div>
4720    </section>
4721  );
4722}
4723`,"src/components/FAQ.tsx":`import type { FAQ as FAQType } from '../content.types';
4724
4725export function FAQ({ faq }: { faq: FAQType }) {
4726  return (
4727    <section id="faq" className="section-y">
4728      <div className="container-page max-w-3xl">
4729        <div className="text-center">
4730          {faq.eyebrow && <p className="eyebrow mb-3">{faq.eyebrow}</p>}
4731          <h2 className="h-section text-text">{faq.headline}</h2>
4732        </div>
4733        <dl className="mt-12 space-y-3">
4734          {faq.items.map((item, i) => (
4735            <details
4736              key={i}
4737              className="group card px-6 py-5 open:border-accent/40 transition-colors"
4738            >
4739              <summary className="cursor-pointer list-none flex items-center justify-between gap-4">
4740                <dt className="font-display font-semibold text-text">{item.question}</dt>
4741                <svg
4742                  width="20"
4743                  height="20"
4744                  viewBox="0 0 24 24"
4745                  fill="none"
4746                  stroke="currentColor"
4747                  strokeWidth="2"
4748                  strokeLinecap="round"
4749                  strokeLinejoin="round"
4750                  className="text-text/60 shrink-0 transition-transform group-open:rotate-180"
4751                >
4752                  <path d="M6 9l6 6 6-6" />
4753                </svg>
4754              </summary>
4755              <dd className="mt-3 text-text/70 leading-relaxed">{item.answer}</dd>
4756            </details>
4757          ))}
4758        </dl>
4759      </div>
4760    </section>
4761  );
4762}
4763`,"src/components/FinalCta.tsx":`import type { FinalCta as FinalCtaType } from '../content.types';
4764
4765export function FinalCta({ finalCta }: { finalCta: FinalCtaType }) {
4766  return (
4767    <section className="section-y">
4768      <div className="container-page">
4769        <div className="relative overflow-hidden rounded-3xl border border-border bg-surface px-8 py-16 md:px-16 md:py-20 text-center">
4770          {/* Accent glow */}
4771          <div className="pointer-events-none absolute inset-0 -z-10">
4772            <div className="absolute -top-32 left-1/2 -translate-x-1/2 w-[700px] h-[400px] rounded-full bg-accent/15 blur-3xl" />
4773          </div>
4774          <h2 className="h-section text-text max-w-2xl mx-auto">{finalCta.headline}</h2>
4775          {finalCta.subhead && (
4776            <p className="mt-4 text-lg text-text/70 max-w-xl mx-auto leading-relaxed">
4777              {finalCta.subhead}
4778            </p>
4779          )}
4780          <div className="mt-8 flex flex-wrap items-center justify-center gap-3">
4781            <a href={finalCta.primaryCta.href} className="btn-primary text-base px-7 py-3">
4782              {finalCta.primaryCta.label}
4783            </a>
4784            {finalCta.secondaryCta && (
4785              <a href={finalCta.secondaryCta.href} className="btn-ghost text-base px-7 py-3">
4786                {finalCta.secondaryCta.label}
4787              </a>
4788            )}
4789          </div>
4790        </div>
4791      </div>
4792    </section>
4793  );
4794}
4795`,"src/components/Footer.tsx":`import { Link } from 'react-router-dom';
4796import type { Footer as FooterType } from '../content.types';
4797
4798// Internal hrefs (e.g. /careers) become SPA <Link>s; anchors + external
4799// URLs fall through to <a>.
4800function FooterLink({ href, className, children }: { href: string; className?: string; children: React.ReactNode }) {
4801  const isInternal = href.startsWith('/') && !href.startsWith('//');
4802  if (isInternal) {
4803    return <Link to={href} className={className}>{children}</Link>;
4804  }
4805  return <a href={href} className={className}>{children}</a>;
4806}
4807
4808const SOCIAL_ICONS: Record<string, JSX.Element> = {
4809  twitter: <path d="M22 5.8c-.7.3-1.5.6-2.4.7.9-.5 1.5-1.3 1.8-2.3-.8.5-1.7.8-2.7 1A4.2 4.2 0 0011.5 9c0 .3 0 .6.1.9C8 9.7 4.9 8.1 2.8 5.5c-.4.6-.6 1.4-.6 2.2 0 1.5.7 2.8 1.9 3.5-.7 0-1.3-.2-1.9-.5v.1c0 2 1.5 3.7 3.4 4.1-.4.1-.7.2-1.1.2-.3 0-.5 0-.8-.1.5 1.7 2.1 2.9 3.9 2.9a8.4 8.4 0 01-6.2 1.7c1.9 1.2 4.1 1.9 6.4 1.9 7.7 0 11.9-6.4 11.9-11.9v-.5c.8-.6 1.5-1.3 2.1-2.1z" />,
4810  github: <path d="M12 2a10 10 0 00-3.2 19.5c.5.1.7-.2.7-.5v-1.7c-2.8.6-3.4-1.4-3.4-1.4-.5-1.2-1.1-1.5-1.1-1.5-.9-.6.1-.6.1-.6 1 .1 1.5 1 1.5 1 .9 1.5 2.4 1.1 3 .8.1-.7.4-1.1.6-1.4-2.2-.3-4.6-1.1-4.6-5 0-1.1.4-2 1-2.7-.1-.3-.4-1.3.1-2.7 0 0 .8-.3 2.7 1a9.4 9.4 0 015 0c1.9-1.3 2.7-1 2.7-1 .5 1.4.2 2.4.1 2.7.6.7 1 1.6 1 2.7 0 3.9-2.3 4.7-4.6 5 .4.3.7 1 .7 2v3c0 .3.2.6.7.5A10 10 0 0012 2z" />,
4811  linkedin: <><path d="M4 8h3v12H4zM5.5 4a1.7 1.7 0 110 3.5 1.7 1.7 0 010-3.5z" /><path d="M9 8h3v1.6c.4-.7 1.4-1.7 3.1-1.7 3.3 0 3.9 2.2 3.9 5.1V20h-3v-5.6c0-1.3 0-3-1.9-3-1.8 0-2.1 1.4-2.1 2.9V20H9z" /></>,
4812  youtube: <><path d="M22 8.5a3 3 0 00-2.1-2.1C18 6 12 6 12 6s-6 0-7.9.4A3 3 0 002 8.5C1.5 10.4 1.5 12 1.5 12s0 1.6.5 3.5a3 3 0 002.1 2.1C6 18 12 18 12 18s6 0 7.9-.4a3 3 0 002.1-2.1c.5-1.9.5-3.5.5-3.5s0-1.6-.5-3.5z" /><path d="M10 9v6l5-3z" fill="currentColor" /></>,
4813  discord: <path d="M19 5.3a17 17 0 00-4.4-1.4l-.2.4a15 15 0 014 1.3 14 14 0 00-12.7 0 15 15 0 014-1.3l-.2-.4a17 17 0 00-4.4 1.4A18 18 0 002 16.4a17 17 0 005.2 2.6l1.1-1.5a11 11 0 01-1.7-.8c.1-.1.3-.2.4-.3a12 12 0 0010.1 0l.4.3a11 11 0 01-1.7.8l1 1.5A17 17 0 0022 16.4a18 18 0 00-3-11.1zM9.4 13.7c-1 0-1.9-.9-1.9-2 0-1.2.8-2 1.9-2 1 0 1.9.8 1.9 2 0 1.1-.8 2-1.9 2zm5.2 0c-1 0-1.9-.9-1.9-2 0-1.2.9-2 1.9-2 1 0 1.9.8 1.9 2 0 1.1-.9 2-1.9 2z" />,
4814};
4815
4816function SocialIcon({ name }: { name: string }) {
4817  const path = SOCIAL_ICONS[name];
4818  if (!path) return null;
4819  return (
4820    <svg
4821      width="18"
4822      height="18"
4823      viewBox="0 0 24 24"
4824      fill="currentColor"
4825      stroke="currentColor"
4826      strokeWidth="0"
4827      aria-hidden="true"
4828    >
4829      {path}
4830    </svg>
4831  );
4832}
4833
4834export function Footer({ footer, brand, brandGlyph }: { footer: FooterType; brand: string; brandGlyph: string }) {
4835  const year = new Date().getFullYear();
4836  return (
4837    <footer className="border-t border-border bg-surface/30 mt-20">
4838      <div className="container-page py-16 grid gap-10 md:grid-cols-12">
4839        <div className="md:col-span-4">
4840          <div className="flex items-center gap-2.5">
4841            <span className="grid place-items-center w-9 h-9 rounded-xl bg-accent text-bg font-bold text-lg shadow-md shadow-accent/30">
4842              {brandGlyph}
4843            </span>
4844            <span className="font-display font-semibold text-text tracking-tight">{brand}</span>
4845          </div>
4846          {footer.tagline && (
4847            <p className="mt-4 text-sm text-text/70 leading-relaxed max-w-xs">{footer.tagline}</p>
4848          )}
4849          {footer.social && footer.social.length > 0 && (
4850            <div className="mt-6 flex items-center gap-3">
4851              {footer.social.map((s, i) => (
4852                <a
4853                  key={i}
4854                  href={s.href}
4855                  className="grid place-items-center w-9 h-9 rounded-lg border border-border text-text/70 hover:text-text hover:border-accent/40 transition"
4856                  aria-label={s.icon}
4857                >
4858                  <SocialIcon name={s.icon} />
4859                </a>
4860              ))}
4861            </div>
4862          )}
4863        </div>
4864        <div className="md:col-span-8 grid grid-cols-2 sm:grid-cols-3 gap-8">
4865          {footer.columns.map((col, i) => (
4866            <div key={i}>
4867              <h3 className="text-xs font-semibold uppercase tracking-[0.2em] text-text/60">
4868                {col.heading}
4869              </h3>
4870              <ul className="mt-4 space-y-2.5">
4871                {col.links.map((l, j) => (
4872                  <li key={j}>
4873                    <FooterLink href={l.href} className="text-sm text-text/80 hover:text-text transition">
4874                      {l.label}
4875                    </FooterLink>
4876                  </li>
4877                ))}
4878              </ul>
4879            </div>
4880          ))}
4881        </div>
4882      </div>
4883      <div className="border-t border-border">
4884        <div className="container-page py-6 text-xs text-text/60 text-center">
4885          © {year} {footer.copyright}
4886        </div>
4887      </div>
4888    </footer>
4889  );
4890}
4891`};function l7(e){const t=Xw(e);t.toLowerCase();const r=Zw(t),n=r==="audio",s=r==="saas",o=n?"SonicForge":s?"DevFlow":Qw(r,t),l=o.charAt(0).toUpperCase()||"S";if(n){const x={meta:{title:`${o} — AI audio production in minutes`,description:"Create, mix, and master tracks with AI. Hear before/after demos and start free.",brand:o,brandGlyph:l,theme:"dark",accent:"139 92 246",accentSoft:"139 92 246 / 0.15"},nav:{links:[{label:"Features",href:"#features"},{label:"Demos",href:"#showcase"},{label:"Pricing",href:"#pricing"}],primaryCta:{label:"Create Your First Track Free",href:"#pricing"},secondaryCta:{label:"Hear Demos",href:"#showcase"}},hero:{eyebrow:"AI-powered audio studio",headline:"Produce pro tracks without a studio",highlightWord:"pro",subhead:"Mix, master, and polish vocals and beats with AI that understands your sound. Upload a rough demo — get radio-ready audio in minutes.",primaryCta:{label:"Create Your First Track Free",href:"#pricing"},secondaryCta:{label:"Compare before & after",href:"#showcase"},stats:[{label:"Tracks mastered",value:"120K+"},{label:"Avg. time saved",value:"4.2 hrs"},{label:"Creator rating",value:"4.9★"}],image:{src:"https://images.unsplash.com/photo-1511379938547-c1f69419868d?w=1400&h=900&fit=crop",alt:"Music producer working in a modern studio"}},logoBar:{label:"Trusted by creators at",brands:["BeatLab","PodcastHQ","IndieWave","SoundStack","MixRoom","ToneCraft"]},features:{eyebrow:"FEATURES",headline:"Everything you need to ship great audio",subhead:"From bedroom demos to release-ready masters — one workflow, zero friction.",items:[{title:"AI mastering",description:"Automatic loudness, EQ, and clarity tuned for Spotify, YouTube, and podcasts.",icon:"sparkles"},{title:"Stem separation",description:"Isolate vocals, drums, and instruments for remixes and clean edits.",icon:"cube"},{title:"Style transfer",description:"Apply genre presets — lo-fi, trap, cinematic, podcast — without losing your voice.",icon:"zap"}]},showcase:{eyebrow:"HEAR THE DIFFERENCE",headline:"Before & after — play the demos",subhead:"Real samples processed by our AI. Hit play to compare raw uploads vs polished output.",samples:[{title:"Vocal polish",description:"Bedroom vocal → broadcast-ready",beforeUrl:"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",afterUrl:"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"},{title:"Beat enhancement",description:"Loose demo → tight, punchy mix",beforeUrl:"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3",afterUrl:"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3"}]},pricing:{eyebrow:"PRICING",headline:"Hobbyist or pro — pick your lane",subhead:"Start free. Upgrade when you're ready to release.",tiers:[{name:"Hobbyist",price:"$0",period:"month",description:"Perfect for experimenting and learning the workflow.",features:["3 exports per month","Standard AI mastering","WAV + MP3 export","Community presets"],cta:{label:"Create Your First Track Free",href:"#pricing"}},{name:"Professional",price:"$29",period:"month",description:"For creators shipping releases and client work.",features:["Unlimited exports","Pro mastering chain","Stem separation","Priority processing","Commercial license"],cta:{label:"Start 14-day trial",href:"#pricing"},popular:!0}]},testimonials:{headline:"Creators love the speed",items:[{quote:"I mastered my EP in one afternoon. The before/after on my vocals was honestly shocking.",author:"Maya Chen",role:"Indie artist"},{quote:"Stem separation saved my remix — pulled clean vocals from a muddy phone recording.",author:"DJ Kairo",role:"Producer"},{quote:"My podcast sounds like a studio show now. Listeners keep asking what mic I use.",author:"Priya Nair",role:"Podcast host"}]},faq:{headline:"Common questions",items:[{question:"Do I need a DAW?",answer:"No — upload WAV or MP3 and export finished files. Optional stems for your DAW."},{question:"Is the free tier really free?",answer:"Yes. Three exports per month, no credit card required."},{question:"Can I use exports commercially?",answer:"Professional plan includes a commercial license for releases and client work."}]},finalCta:{headline:"Your next track is waiting",subhead:"Upload a rough demo and hear the AI magic in under a minute.",primaryCta:{label:"Create Your First Track Free",href:"#pricing"}},footer:{tagline:`${o} — AI audio production for everyone.`,columns:[{heading:"Product",links:[{label:"Features",href:"#features"},{label:"Pricing",href:"#pricing"}]},{heading:"Company",links:[{label:"About",href:"#"},{label:"Contact",href:"#contact"}]}],copyright:`© ${new Date().getFullYear()} ${o}`}};
4891return`export const content = ${JSON.stringify(x,null,2)} as const;
4892`}const c=t,u=r7(r),d=e7(c,r,o),p=t7(r,o,c),h=n7(r),f={meta:{title:`${o} — ${d}`,description:p.slice(0,160),brand:o,brandGlyph:l,theme:u.theme,accent:u.accent,accentSoft:u.accentSoft},nav:{links:[{label:"Features",href:"#features"},{label:"Pricing",href:"#pricing"},{label:"Contact",href:"#contact"}],primaryCta:{label:r==="social"?"Start a poll":r==="bookclub"?"Create a club":"Get Started",href:"#pricing"},secondaryCta:{label:"Learn More",href:"#features"}},hero:{eyebrow:r==="generic"?"Built for you":o,headline:d,highlightWord:void 0,subhead:p,primaryCta:{label:r==="social"?"Start a poll":"Get Started",href:"#pricing"},secondaryCta:{label:"See features",href:"#features"},stats:r==="saas"||r==="social"?[{label:"Active users",value:"2.4K+"},{label:"Uptime",value:"99.9%"},{label:"Rating",value:"4.8★"}]:void 0},logoBar:{label:"Trusted by teams at",brands:r==="bookclub"?["PageTurners","LitCircle","NovelNight","ChapterOne","Bookish","ReadTogether"]:r==="social"?["FriendGroup","CampusPoll","WeekendCrew","VoteNight","CircleUp","Hangout"]:["Acme","Northwind","Lumio","Stackline","Cobalt","Voltage"]},features:{eyebrow:"FEATURES",headline:r==="generic"?"What we built for you":`Built for ${r.replace("bookclub","book clubs")}`,subhead:p.slice(0,120),items:h},pricing:{headline:"Simple, transparent pricing",subhead:"No hidden fees. Cancel anytime.",tiers:[{name:"Starter",price:"$0",period:"month",description:"For individuals and small projects.",features:["Core features","Email support","1 workspace"],cta:{label:"Start free",href:"#pricing"}},{name:"Pro",price:"$29",period:"month",description:"For growing teams that need more power.",features:["Everything in Starter","Priority support","Unlimited workspaces","Advanced analytics"],cta:{label:"Start trial",href:"#pricing"},popular:!0}]},testimonials:{headline:"What people say",items:r==="bookclub"?[{quote:"Finally — one place for picks, votes, and meetup reminders.",author:"Elena M.",role:"Club host"},{quote:"Our group actually finishes books now. The vote feature is perfect.",author:"Chris P.",role:"Member"}]:r==="social"?[{quote:"We use it every Friday to decide where to eat. No more endless texts.",author:"Sam K.",role:"Friend group"},{quote:"Polls + reactions feel native — not like a corporate tool.",author:"Jordan L.",role:"Community lead"}]:[{quote:"Outstanding from start to finish. Highly recommend!",author:"Alex M.",role:"Customer"},{quote:"Easy to use and professional throughout.",author:"Jordan K.",role:"Customer"}]},finalCta:{headline:r==="bookclub"?"Start your next chapter":r==="social"?"Gather your circle":"Ready to get started?",subhead:p.slice(0,100),primaryCta:{label:"Get Started",href:"#pricing"}},footer:{tagline:`${o} — ${p.slice(0,80)}`,columns:[{heading:"Company",links:[{label:"About",href:"#"},{label:"Contact",href:"#contact"}]},{heading:"Legal",links:[{label:"Privacy",href:"#"},{label:"Terms",href:"#"}]}],copyright:`© ${new Date().getFullYear()} ${o}`}};return`export const content = ${JSON.stringify(f,null,2)} as const;
4893`}const Jk=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","fs/promises","http","http2","https","inspector","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","repl","stream","stream/promises","stream/web","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib"]),_m=new Set(["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","react-router-dom","react-router","/@vite/client","vite/client",...Jk,...Array.from(Jk).map(e=>`node:${e}`)]),c7=new Set(["@tanstack/react-query","@supabase/supabase-js","react","react-dom","react-router-dom","lucide-react","tailwindcss","clsx","class-variance-authority","tailwind-merge"]),sx={"@supabase/supabase-js":"^2.49.1","@tanstack/react-query":"^5.83.0","date-fns":"^3.6.0",recharts:"^2.15.4",zod:"^3.25.76",sonner:"^1.7.4","@hookform/resolvers":"^3.10.0","react-hook-form":"^7.61.1","framer-motion":"^11.11.0",uuid:"^11.0.0",zustand:"^5.0.0",vaul:"^0.9.9",clsx:"^2.1.1","tailwind-merge":"^2.6.0","class-variance-
4893authority":"^0.7.1","lucide-react":"^0.469.0","embla-carousel-react":"^8.6.0","next-themes":"^0.3.0",cmdk:"^1.1.1","input-otp":"^1.4.2","react-day-picker":"^8.10.1","react-resizable-panels":"^2.1.9",motion:"^11.18.2",gsap:"^3.12.5","lottie-react":"^2.4.0","@formkit/auto-animate":"^0.8.2","canvas-confetti":"^1.9.3","@tsparticles/react":"^3.0.0","@tsparticles/slim":"^3.5.0","@tsparticles/engine":"^3.5.0","@nivo/core":"^0.88.0","@nivo/line":"^0.88.0","@nivo/bar":"^0.88.0","@nivo/pie":"^0.88.0","@tanstack/react-table":"^8.20.5","@react-three/fiber":"^8.17.10","@react-three/drei":"^9.114.0",three:"^0.169.0","@splinetool/react-spline":"^4.0.0","react-leaflet":"^4.2.1",leaflet:"^1.9.4","@tiptap/react":"^2.9.1","@tiptap/starter-kit":"^2.9.1","@tiptap/pm":"^2.9.1","react-markdown":"^9.0.1","remark-gfm":"^4.0.0","@dnd-kit/core":"^6.1.0","@dnd-kit/sortable":"^8.0.0","@dnd-kit/utilities":"^3.2.2","react-helmet-async":"^2.0.5"};function HE(e){const t=e.find(l=>l.path.replace(/^\/+/,"")==="package.json");if(!t)return{files:e,added:[]};const r=new Set;try{const l=JSON.parse(t.content);for(const c of Object.keys(l.dependencies||{}))r.add(c);for(const c of Object.keys(l.devDependencies||{}))r.add(c);for(const c of Object.keys(l.peerDependencies||{}))r.add(c)}catch{return{files:e,added:[]}}const n=new Set;for(const l of e)if(/\.(tsx|ts|jsx|js|mjs)$/i.test(l.path))for(const c of VE(l.content)){if(c.startsWith(".")||c.startsWith("@/")||c.startsWith("/")||c.startsWith("http://")||c.startsWith("https://"))continue;const u=WE(c);_m.has(c)||_m.has(u)||r.has(u)||sx[u]&&n.add(u)}const s=[...n];if(s.length===0)return{files:e,added:[]};const{content:i,added:o}=e1(t.content,s);return o.length===0?{files:e,added:[]}:{files:e.map(l=>l.path.replace(/^\/+/,"")==="package.json"?{...l,content:i}:l),added:o}}function e1(e,t){var n;const r=[];try{const s=JSON.parse(e);s.dependencies||(s.dependencies={});for(const i of t){if(s.dependencies[i]||(n=s.devDependencies)!=null&&n[i])continue;const o=sx[i];o&&(s.dependencies[i]=o,r.push(i))}return r.length===0?{content:e,added:r}:{content:`${JSON.stringify(s,null,2)}
4894`,added:r}}catch{return{content:e,added:r}}}const Tm=[".tsx",".ts",".jsx",".js",".mjs"];function WE(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]}function VE(e){const t=[],r=/(?:^|[\s;])(?:import|export)\s+(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g,n=/require\s*\(\s*["']([^"']+)["']\s*\)/g,s=/import\s*\(\s*["']([^"']+)["']\s*\)/g;let i;for(;i=r.exec(e);)t.push(i[1]);for(;i=n.exec(e);)t.push(i[1]);for(;i=s.exec(e);)t.push(i[1]);return t}function o0(e,t,r){const n=e.split("/").slice(0,-1),s=t.split("/"),i=[...n];for(const c of s)c===""||c==="."||(c===".."?i.pop():i.push(c));const o=i.join("/"),l=[o];for(const c of Tm)l.push(`${o}${c}`);for(const c of Tm)l.push(`${o}/index${c}`);l.push(`${o}.css`,`${o}.svg`,`${o}.png`,`${o}.jpg`,`${o}.json`);for(const c of l)if(r.has(c))return c;return null}function Xk(e,t){if(!e.startsWith("@/"))return null;const r=e.slice(2);return o0("src/_dummy",`./${r}`,t)}function GE(e){const t=new Map;for(const n of e.matchAll(/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g))t.set(n[1],n[2]);for(const n of e.matchAll(/import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g)){const s=n[2],i=n[1].split(",").map(o=>o.trim().split(/\s+as\s+/)[0].trim());for(const o of i)o&&t.set(o,s)}for(const n of e.matchAll(/const\s+(\w+)\s*=\s*lazy\([^)]*import\(['"]([^'"]+)['"]\)/g))t.set(n[1],n[2]);const r=[];for(const n of e.matchAll(/<Route[^>]*path=["']([^"']+)["'][^>]*element=\{<(\w+)/g)){const s=t.get(n[2]);s&&r.push({path:n[1],spec:s})}return r}function t1(e){return e.map(t=>({path:t.path.replace(/^\/+/,""),content:t.content})).filter(t=>t.path&&!TT(t.path))}function n1(e){const t=new Set(e.map(d=>d.path)),r=e.find(d=>d.path==="package.json");let n=new Set(c7);if(r)try{const d=JSON.parse(r.content);for(const p of Object.keys(d.dependencies||{}))n.add(p);for(const p of Object.keys(d.devDependencies||{}))n.add(p);for(const p of Object.keys(d.peerDependencies||{}))n.add(p)}catch{}const s=[],i=[];for(const d of e){if(!/\.(tsx|ts|jsx|js|mjs)$/i.test(d.path))continue;const p=VE(d.content);for(const h of p)if(!/\.(?:png|jpe?g|gif|webp|avif|ico|bmp|tiff?|mp[34]|webm|ogg|wav|flac|woff2?|ttf|otf|eot|pdf)$/i.test(h))if(h.startsWith("."))o0(d.path,h,t)||s.push({importer:d.path,spec:h});else if(h.startsWith("@/"))Xk(h,t)||s.push({importer:d.path,spec:h});else{if(h.startsWith("/"))continue;if(h.startsWith("http://")||h.startsWith("https://"))continue;
4894{const x=WE(h);if(_m.has(h)||_m.has(x)||n.has(x))continue;i.push({importer:d.path,pkg:x})}}}const o=[];t.has("package.json")&&(t.has("index.html")||o.push("index.html"),Tm.some(h=>t.has(`src/main${h}`))||o.push("src/main.tsx"),Tm.some(h=>t.has(`src/App${h}`))||o.push("src/App.tsx"));const l=[],c=e.find(d=>d.path==="src/App.tsx"||d.path==="src/App.jsx");if(c)for(const d of GE(c.content))(d.spec.startsWith("@/")?Xk(d.spec,t):o0(c.path,d.spec,t))||l.push({path:d.path,spec:d.spec});const u=(d,p)=>{const h=new Set,f=[];for(const x of d){const g=p(x);h.has(g)||(h.add(g),f.push(x))}return f};return{missingFiles:u(s,d=>d.spec),missingPackages:u(i,d=>d.pkg),missingEntrypoints:o,missingRoutes:u(l,d=>`${d.path}:${d.spec}`)}}function KE(e){const t=[];for(const r of e.missingEntrypoints)t.push(`Missing required entrypoint: ${r} — the AI emitted other files but forgot the shell.`);for(const r of e.missingFiles)t.push(`Cannot find file ${r.spec} imported by ${r.importer} — emit it or remove the import.`);for(const r of e.missingPackages)t.push(`Cannot find package ${r.pkg} imported by ${r.importer} — add it to package.json dependencies.`);for(const r of e.missingRoutes)t.push(`Route ${r.path} references ${r.spec} but that page file was not generated — emit it or remove the Route.`);return t}function l0(e){return e.missingFiles.length>0||e.missingPackages.length>0||e.missingEntrypoints.length>0||e.missingRoutes.length>0}function df(e){return(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"")||"/"}function u7(e){return e.filter(t=>t.content.includes("AUTO-GENERATED STUB")).length}function d7(e){const t=e.find(u=>/^(src\/)?App\.(tsx|jsx)$/i.test(u.path.replace(/^\/+/,"")));if(!t)return[];const r=new Set(["/"]);for(const u of t.content.matchAll(/<Route[^>]*path=["']([^"']+)["']/g))r.add(df(u[1]));for(const u of GE(t.content))r.add(df(u.path));const n=["/login","/signin","/signup","/register","/auth","/forgot-password","/reset-password"];[...r].some(u=>n.includes(u))&&n.forEach(u=>r.add(u));const s=new Set,i=/(?:href|to)=["'](\/?[a-zA-Z#][a-zA-Z0-9\-_/#]*)["']/g,o=/navigate\(\s*["'](\/?[a-zA-Z][a-zA-Z0-9\-_/]*)["']/g;for(const u of e){if(!/\.(tsx|jsx)$/i.test(u.path))continue;let d;for(;(d=i.exec(u.content))!==null;){const p=d[1];p.startsWith("mailto:")||p.startsWith("tel:")||p.startsWith("http")||p.startsWith("#")||s.add(df(p.split("#")[0].split("?")[0]))}for(;(d=o.exec(u.content))!==null;)s.add(df(d[1]))}const l=new Set(e.filter(u=>/src\/pages\/[^/]+\.(tsx|jsx)$/i.test(u.path.replace(/^\/+/,""))).map(u=>(u.path.split("/").pop()||"").replace(/\.(tsx|jsx)$/i,"").toLowerCase())),c=[];return s.forEach(u=>{if(r.has(u))return;const d=u.split("/").filter(Boolean),p=(d[d.length-1]||"home").toLowerCase(),h=new Set([p,"dashboard","home"]);(u==="/app"||u==="/dashboard")&&h.add("dashboard"),![...h].some(f=>l.has(f))&&c.push(u)}),c}const r1=`// AUTO-GENERATED STUB — this file was imported but never written by the AI.
4895// Re-prompt the AI to fill in real content, or delete this file if the import was a mistake.
4896`,p7=`      {(import.meta as ImportMeta & { env: { DEV: boolean } }).env.DEV && (
4897        <div style={{ padding: 8, background: '#fef3c7', color: '#92400e', fontSize: 12, borderRadius: 4, marginBottom: 16 }}>
4898          ⚠️ Placeholder — ask the AI to build this out.
4899        </div>
4900      )}`;function h7(e){const n=(e.split("/").pop()||"Stub").replace(/\.(tsx|jsx|ts|js|mjs)$/,"").replace(/[^A-Za-z0-9_$]/g,"").replace(/^\d+/,"")||"Stub";return n[0].toUpperCase()+n.slice(1)}function YE(e){return/\/pages?\//i.test(e)||/\/screens?\//i.test(e)||/\/routes?\//i.test(e)}function f7(e){return/\/components?\//i.test(e)||/\/widgets?\//i.test(e)}function Zk(e){return/\.(tsx|jsx)$/i.test(e)}function m7(e){return/\.(ts|js|mjs)$/i.test(e)}function g7(e){return`${r1}
4901export default function ${e}() {
4902  return (
4903    <div style={{ padding: 24, maxWidth: 720, margin: '0 auto' }}>
4904${p7}
4905      <h1 style={{ fontSize: 28, fontWeight: 600, marginBottom: 8 }}>Coming soon</h1>
4906      <p style={{ color: '#64748b' }}>This page hasn't been built yet. Ask the AI to fill in the content.</p>
4907    </div>
4908  );
4909}
4910`}function x7(e){return`${r1}
4911export default function ${e}() {
4912  if ((import.meta as ImportMeta & { env: { DEV: boolean } }).env.DEV) {
4913    return (
4914      <div style={{ padding: 8, background: '#fef3c7', color: '#92400e', fontSize: 12, borderRadius: 4 }}>
4915        ⚠️ Placeholder \`${e}\` — ask the AI to build this out.
4916      </div>
4917    );
4918  }
4919  return null;
4920}
4921`}function y7(){return`${r1}
4922// Plain module placeholder. Replace with real exports.
4923export {};
4924`}function JE(e,t){if(t.startsWith("@/")){const o=t.slice(2);return JE("src/_dummy",`./${o}`)}if(!t.startsWith("."))return null;const r=e.split("/").slice(0,-1),n=t.split("/"),s=[...r];for(const o of n)o===""||o==="."||(o===".."?s.pop():s.push(o));const i=s.join("/");return/\.[a-z0-9]+$/i.test(i)?i:YE(i)||f7(i)||/\/[A-Z]/.test(i)?`${i}.tsx`:`${i}.ts`}function XE(e,t=[]){const r=t.length>0?t:[],n=[],s=new Set;for(const i of e.missingFiles){const o=JE(i.importer,i.spec);if(!o||s.has(o)||!Zk(o)&&!m7(o))continue;const l=h7(o);let c;Zk(o)?c=YE(o)||/\/[A-Z][A-Za-z0-9]*Page\.tsx?$/.test(o)?g7(l):x7(l):c=(r.length>0?ZE(r,o):null)??y7(),s.add(o),n.push({path:o,content:c,triggeredBy:i})}return n}function ZE(e,t){if(t!=="src/content.ts")return null;const r=e.find(s=>
4924/^src\/App\.tsx?$/i.test(s.path.replace(/^\/+/,""))),n=(r==null?void 0:r.content)||"";return/import\s+\{\s*content\s*\}/.test(n)?i0["src/content.ts"]??null:e.some(s=>/DashboardLayout|DashboardPage/i.test(s.path))||/DashboardLayout|DashboardPage/.test(n)?a0["src/content.ts"]??null:a0["src/content.ts"]??i0["src/content.ts"]??null}function b7(e){const t=t1(e),r=n1(t);if(r.missingFiles.length===0&&r.missingRoutes.length===0)return e;const n=t.find(d=>/^src\/App\.tsx?$/i.test(d.path)),s=r.missingRoutes.map(d=>({importer:(n==null?void 0:n.path)||"src/App.tsx",spec:d.spec})),i=[...r.missingFiles],o=new Set(i.map(d=>d.spec));for(const d of s)o.has(d.spec)||(o.add(d.spec),i.push(d));const l=XE({...r,missingFiles:i},t);if(l.length===0)return e;const c=new Set(t.map(d=>d.path)),u=[...e];for(const d of l){const p=d.path.replace(/^\/+/,"");if(c.has(p))continue;const h=ZE(t,p)??d.content;u.push({path:p,content:h}),c.add(p)}return u}const v7=2e4;function w7(e){if(!e)return{};const t=e.last_heartbeat_at,r=typeof t=="string"?new Date(t).getTime():null;return{viteUp:typeof e.vite_up=="boolean"?e.vite_up:null,viteReady:e.vite_ready===!0,lastHeartbeatAt:Number.isFinite(r)?r:null}}function j7(e){const[t,r]=m.useState({viteUp:null,viteReady:!1,lastHeartbeatAt:null,heartbeatStale:!1}),n=m.useRef(null);return m.useEffect(()=>{if(!e)return;let s=!1;const i=l=>{const c=w7(l);c.lastHeartbeatAt!=null&&(n.current=c.lastHeartbeatAt),!s&&r(u=>({...u,...c,heartbeatStale:!1}))};(async()=>{try{const{data:l}=await G.from("preview_runner_sessions").select("metadata").eq("project_id",e).order("updated_at",{ascending:!1}).limit(1);!s&&l&&l[0]&&i(l[0].metadata)}catch{}})();const o=G.channel(`preview_vitals_${e}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"preview_runner_sessions",filter:`project_id=eq.${e}`},l=>{var c;i((c=l.new)==null?void 0:c.metadata)}).subscribe();return()=>{s=!0,G.removeChannel(o)}},[e]),m.useEffect(()=>{if(!e)return;const s=setInterval(()=>{const i=n.current;if(i==null)return;const o=Date.now()-i>v7;r(l=>l.heartbeatStale===o?l:{...l,heartbeatStale:o})},5e3);return()=>clearInterval(s)},[e]),t}function N7({toolCallHistory:e}){const t=e.find(n=>n.status==="running"),r=(t==null?void 0:t.label)||"Applying your changes";return a.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 z-30 pointer-events-none animate-in fade-in duration-300",children:a.jsxs("div",{className:"flex items-center gap-2.5 rounded-full border border-border/60 bg-background/95 backdrop-blur-md shadow-lg px-3.5 py-2 text-[12px] text-foreground",children:[a.jsxs("span",{className:"relative flex h-2 w-2",children:[a.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),a.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]}),a.jsx("span",{className:"font-medium",children:"Updating preview"}),a.jsxs("span",{className:"text-muted-foreground max-w-[280px] truncate",children:["— ",r]})]})})}function k7({phase:e,isBuilding:t,hasLogs:r,onToggleLogs:n,showLogs:s,minimal:i,projectName:o}){const l=(o==null?void 0:o.trim())||"Your app",c=e==="warming"?`Warming up the preview for ${l}`:e==="installing"?`Installing dependencies for ${l}`:e==="syncing"?"Syncing your latest changes":t?`Building ${l}`:`Starting preview for ${l}`;return a.jsxs(a.Fragment,{children:[!i&&a.jsx("div",{className:"absolute inset-0 bg-background overflow-hidden flex items-center justify-center px-6 pointer-events-none",children:a.jsxs("div",{className:"w-full max-w-md rounded-2xl border bg-card/80 backdrop-blur-sm shadow-sm p-7 flex flex-col items-center text-center gap-4",children:[a.jsxs("div",{className:"relative w-16 h-16 rounded-2xl bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center",children:[a.jsx("span",{className:"absolute inset-0 rounded-2xl border border-primary/30 animate-[sj-card-pulse_2.2s_ease-out_infinite]"}),a.jsx("span",{className:"text-2xl font-semibold text-primary",children:(l[0]||"?").toUpperCase()})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:"Working…"}),a.jsx("div",{className:"text-[13px] text-muted-foreground leading-snug",children:c})]}),a.jsx("style",{children:"@keyframes sj-card-pulse { 0% { transform: scale(1); opacity: 0.6; } 70% { transform: scale(1.18); opacity: 0; } 100% { transform: scale(1.18); opacity: 0; } }"})]})}),a.jsxs("div",{className:"absolute top-0 left-0 right-0 h-[2px] overflow-hidden pointer-events-none",children:[a.jsx("div",{className:"h-full w-1/3 bg-primary animate-[sj-sync-bar_1.6s_ease-in-out_infinite]"}),a.jsx("style",{children:"@keyframes sj-sync-bar { 0% { transform: translateX(-100%); } 50% { transform: translateX(180%); } 100% { transform: translateX(380%); } }"})]}),r&&a.jsx("div",{className:"absolute bottom-3 right-3 pointer-events-auto",children:a.jsx("button",{onClick:n,className:"text-[10px] text-muted-foreground hover:text-foreground bg-card/80 backdrop-blur-sm border rounded-lg px-2 py-1 shadow-sm",children:s?"Hide logs":"Show logs"})})]})}const S7=new RegExp("\x1B\\[[0-9;]*m","g"),C7=e=>e.replace(S7,"");function zc(e,t,r){e&&G.functions.invoke("record-build-preview-status",{body:{project_id:e,preview_status:t,error_message:(r==null?void 0:r.slice(0,2e3))||null}}).catch(n=>{console.warn("[build-ledger] preview status update failed:",(n==null?void 0:n.message)||n)})}const P7=`/// <reference types="vite/client" />
4925`,A7=`@tailwind base;
4926@tailwind components;
4927@tailwind utilities;
4928
4929body {
4930  min-width: 320px;
4931  min-height: 100vh;
4932}
4933`,QE=`/** @type {import('tailwindcss').Config} */
4934export default {
4935  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
4936  theme: {
4937    extend: {
4938      colors: {
4939        ink: {
4940          50: '#f7f8f5',
4941          100: '#e8ede4',
4942          200: '#d1dacb',
4943          300: '#aebda5',
4944          400: '#849976',
4945          500: '#667b56',
4946          600: '#4f6142',
4947          700: '#3f4d35',
4948          800: '#333f2d',
4949          900: '#1f2a1e',
4950          950: '#0b120d',
4951        },
4952        jungle: {
4953          50: '#eef8f1',
4954          100: '#d8efdf',
4955          200: '#b5dfc2',
4956          300: '#84c79b',
4957          400: '#4ba96e',
4958          500: '#289351',
4959          600: '#1d743f',
4960          700: '#195d35',
4961          800: '#164a2d',
4962          900: '#123d25',
4963          950: '#082114',
4964        },
4965        moss: {
4966          50: '#f5f7ed',
4967          100: '#e8ecd5',
4968          200: '#d3dcaf',
4969          300: '#b6c57f',
4970          400: '#98ab56',
4971          500: '#7a8d3d',
4972          600: '#5f7130',
4973          700: '#4a5828',
4974          800: '#3d4824',
4975          900: '#343e22',
4976          950: '#1a2110',
4977        },
4978        cream: '#f5efe1',
4979        paper: '#fbf7ef',
4980      },
4981    },
4982  },
4983  plugins: [],
4984};
4985`,Qk=`{
4986        ink: {
4987          50: '#f7f8f5',
4988          100: '#e8ede4',
4989          200: '#d1dacb',
4990          300: '#aebda5',
4991          400: '#849976',
4992          500: '#667b56',
4993          600: '#4f6142',
4994          700: '#3f4d35',
4995          800: '#333f2d',
4996          900: '#1f2a1e',
4997          950: '#0b120d',
4998        },
4999        jungle: {
5000          50: '#eef8f1',
5001          100: '#d8efdf',
5002          200: '#b5dfc2',
5003          300: '#84c79b',
5004          400: '#4ba96e',
5005          500: '#289351',
5006          600: '#1d743f',
5007          700: '#195d35',
5008          800: '#164a2d',
5009          900: '#123d25',
5010          950: '#082114',
5011        },
5012        moss: {
5013          50: '#f5f7ed',
5014          100: '#e8ecd5',
5015          200: '#d3dcaf',
5016          300: '#b6c57f',
5017          400: '#98ab56',
5018          500: '#7a8d3d',
5019          600: '#5f7130',
5020          700: '#4a5828',
5021          800: '#3d4824',
5022          900: '#343e22',
5023          950: '#1a2110',
5024        },
5025        cream: '#f5efe1',
5026        paper: '#fbf7ef',
5027      }`,_7=`export default {
5028  plugins: {
5029    tailwindcss: {},
5030    autoprefixer: {},
5031  },
5032};
5033`;function gp(e,t,r){const n=e.findIndex(s=>s.path===t);if(n>=0){const s=[...e];return s[n]={...s[n],content:r},s}return[...e,{path:t,content:r}]}function T7(e){return/\bink\s*:/.test(e)&&/\bpaper\s*:/.test(e)?e:/theme\s*:\s*\{\s*extend\s*:\s*\{\s*\}\s*\}/s.test(e)?e.replace(/theme\s*:\s*\{\s*extend\s*:\s*\{\s*\}\s*\}/s,`theme: {
5034    extend: {
5035      colors: ${Qk},
5036    },
5037  }`):/extend\s*:\s*\{/s.test(e)?e.replace(/extend\s*:\s*\{/,`extend: {
5038      colors: ${Qk},`):QE}function E7(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/^tailwind\.config\.(?:js|cjs|mjs|ts|mts)$/.test(r))return t;const n=T7(t.content);return n===t.content?t:{...t,content:n}})}function I7(e){const t=e.split(`
5039`),r=[],n=[];
5039for(const s of t)/^\s*@import\s+/i.test(s)?r.push(s):n.push(s);return r.length===0?e:[...r,...n.filter((s,i)=>i>0||s.trim()!=="")].join(`
5040`)}function O7(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/\.css$/i.test(r))return t;const n=I7(t.content);return n===t.content?t:{...t,content:n}})}function R7(e){if(e.some(n=>n.path==="src/vite-env.d.ts"))return e;const t=e.some(n=>n.path==="vite.config.ts"||n.path==="vite.config.js"||n.path==="src/main.tsx"||n.path==="src/main.ts"),r=e.some(n=>/\bimport\.meta\.env\b/.test(n.content));return!t&&!r?e:[...e,{path:"src/vite-env.d.ts",content:P7}]}function D7(e){const t=new Set(e.map(n=>n.path));return t.has("package.json")&&(t.has("vite.config.ts")||t.has("vite.config.js")||t.has("vite.config.mjs")||t.has("src/main.tsx")||t.has("src/main.jsx")||t.has("src/main.ts")||t.has("src/main.js"))?e.map(n=>{var s;if(n.path!=="package.json")return n;try{const i=JSON.parse(n.content);return i.scripts={...i.scripts||{}},i.dependencies={...i.dependencies||{}},i.devDependencies={...i.devDependencies||{}},(s=i.scripts).dev||(s.dev="vite"),!i.dependencies.vite&&!i.devDependencies.vite&&(i.devDependencies.vite="^5.4.19"),e.some(o=>/@vitejs\/plugin-react/.test(o.content))&&!i.dependencies["@vitejs/plugin-react"]&&!i.devDependencies["@vitejs/plugin-react"]&&(i.devDependencies["@vitejs/plugin-react"]="^4.5.0"),{...n,content:`${JSON.stringify(i,null,2)}
5041`}}catch{return n}}):e}function e3(e){const t=new Set(e.map(r=>r.path.replace(/^\/+/,"").replace(/\\/g,"/")));return["src/main.tsx","src/main.jsx","src/main.ts","src/main.js"].find(r=>t.has(r))||null}function M7(e,t){var i,o,l,c;const r=((o=(i=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i))==null?void 0:i[1])==null?void 0:o.trim())||"Studio Jungle Preview",n=(c=(l=e.match(/<meta\s+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i))==null?void 0:l[1])==null?void 0:c.trim();return`<!-- route: / -->
5042<!doctype html>
5043<html lang="en">
5044  <head>
5045    <meta charset="UTF-8" />
5046    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
5047${n?`    <meta name="description" content="${n.replace(/"/g,"&quot;")}" />
5048`:""}    <title>${r}</title>
5049  </head>
5050  <body>
5051    <div id="root"></div>
5052    <script type="module" src="/${t}"><\/script>
5053  </body>
5054</html>
5055`}function L7(e){const t=new Set(e.map(i=>i.path.replace(/^\/+/,"").replace(/\\/g,"/"))),r=e3(e);if(!r||!t.has("package.json"))return e;const n=e.find(i=>i.path.replace(/^\/+/,"").replace(/\\/g,"/")==="index.html"),s=M7((n==null?void 0:n.content)||"",r);return gp(e,"index.html",s)}function $7(e){var u,d,p;const t=new Set(e.map(h=>h.path));if(!((t.has("src/main.tsx")||t.has("src/main.jsx"))&&t.has("index.html")&&t.has("package.json")))return e;const n=e.filter(h=>/\.(tsx|jsx|html)$/.test(h.path)).map(h=>h.content).join(`
5056`);if(!/\b(?:className|class)=["'][^"']*(?:bg-|text-|flex|grid|rounded|shadow|px-|py-|p-|m-|w-|h-|min-h-|max-w-|mx-|gap-|space-y-|border|items-|justify-)/.test(n))return e;let i=[...e];const o=i.find(h=>h.path==="package.json");if(o)try{const h=JSON.parse(o.content);h.devDependencies={...h.devDependencies||{}},(u=h.devDependencies).tailwindcss||(u.tailwindcss="^3.4.17"),(d=h.devDependencies).postcss||(d.postcss="^8.5.6"),(p=h.devDependencies).autoprefixer||(p.autoprefixer="^10.4.21"),o.content=`${JSON.stringify(h,null,2)}
5057`}catch{}t.has("src/index.css")||(i=gp(i,"src/index.css",A7)),!t.has("tailwind.config.js")&&!t.has("tailwind.config.ts")&&(i=gp(i,"tailwind.config.js",QE)),!t.has("postcss.config.js")&&!t.has("postcss.config.ts")&&(i=gp(i,"postcss.config.js",_7));const l=t.has("src/main.tsx")?"src/main.tsx":"src/main.jsx",c=i.find(h=>h.path===l);return c&&!/import\s+['"]\.\/index\.css['"]/.test(c.content)&&(c.content=`import './index.css';
5058${c.content}`),E7(i)}function F7(){return`import { createClient, type SupabaseClient } from '@supabase/supabase-js';
5059
5060const supabaseUrl = (import.meta.env.VITE_SUPABASE_URL as string | undefined) ?? '';
5061const supabaseAnonKey = (import.meta.env.VITE_SUPABASE_ANON_KEY as string | undefined) ?? '';
5062const projectShortId = (import.meta.env.VITE_STUDIO_PROJECT_SHORT_ID as string | undefined) ?? '';
5063
5064export const hasSupabaseConfig: boolean = supabaseUrl.length > 0 && supabaseAnonKey.length > 0;
5065
5066if (!hasSupabaseConfig) {
5067  console.warn('[supabase] credentials not configured. Connect Supabase via the Cloud tab to enable auth and database.');
5068}
5069
5070const baseClient = createClient(
5071  supabaseUrl || 'https://placeholder.supabase.co',
5072  supabaseAnonKey || 'placeholder-anon-key',
5073  {
5074    auth: {
5075      storage: typeof window !== 'undefined' ? (function() {
5076        try {
5077          window.localStorage.setItem('__test', '1');
5078          window.localStorage.removeItem('__test');
5079          return window.localStorage;
5080        } catch {
5081          return { getItem: () => null, setItem: () => {}, removeItem: () => {} };
5082        }
5083      })() : undefined,
5084    },
5085  },
5086);
5087
5088function resolveEdgeFunctionName(name: string): string {
5089  if (projectShortId && !name.startsWith('p-')) {
5090    return \`p-\${projectShortId}-\${name}\`;
5091  }
5092  return name;
5093}
5094
5095export const supabase: SupabaseClient = new Proxy(baseClient, {
5096  get(target, prop, receiver) {
5097    if (prop === 'functions') {
5098      const fns = target.functions;
5099      return {
5100        ...fns,
5101        invoke: (name: string, opts?: Parameters<typeof fns.invoke>[1]) =>
5102          fns.invoke(resolveEdgeFunctionName(name), opts),
5103      };
5104    }
5105    return Reflect.get(target, prop, receiver);
5106  },
5107});
5108`}function B7(e){return!(!e.includes("createClient")||e.includes("hasSupabaseConfig")&&e.includes("placeholder.supabase.co"))}function U7(e){return/fetch\s*\(\s*['"]\/api\//.test(e)||/export const supabase\s*=\s*\{/.test(e)&&!e.includes("createClient")||/functions:\s*\{[\s\S]*invoke:/.test(e)&&!e.includes("createClient")}function eS(e){const t=e.replace(/^\/+/,"").replace(/\\/g,"/");return t==="src/lib/supabase.ts"||t==="src/lib/supabase.tsx"}function z7(e){const t=F7(),r=e.map(i=>eS(i.path)&&(U7(i.content)||B7(i.content))?{...i,path:"src/lib/supabase.ts",content:t}:i),n=r.some(i=>eS(i.path)),s=r.some(i=>i.path.replace(/^\/+/,"")==="package.json");return!n&&s&&r.push({path:"src/lib/supabase.ts",content:t}),r}function q7(){const e="https://xfmlsevleobdlnjqxmdi.supabase.co",t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo";return{VITE_SUPABASE_URL:e,VITE_SUPABASE_ANON_KEY:t,VITE_SUPABASE_PUBLISHABLE_KEY:t}}function tS(e,t){const r=q7(),n=t?{VITE_STUDIO_PROJECT_SHORT_ID:t.slice(0,8)}:void 0;if(!(!r&&!e&&!n))return{...r,...n,...e}}function H7(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/^vite\.config\.(?:ts|js|mjs|mts)$/.test(r))return t;const n=t.content.replace(/^\s*import\s+path\s+from\s+['"]path['"];?\s*$/gm,"").replace(/^\s*import\s+\*\s+as\s+path\s+from\s+['"]path['"];?\s*$/gm,"").replace(/path\.resolve\(\s*__dirname\s*,\s*['"]\.?\/?src['"]\s*\)/g,"'/src'").replace(/\n{3,}/g,`
5109
5110`);return n===t.content?t:{...t,content:n}})}function W7(e){let t="";for(let r=0;r<e.length;r+=1){const n=e[r];t+=n==="'"&&e[r-1]!=="\\"?"\\'":n}return t}function V7(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/\.(?:ts|tsx|js|jsx)$/.test(r))return t;const n=t.content.split(`
5111`).map(s=>s.replace(/^(\s*[A-Za-z_$][\w$-]*\s*:\s*)'(.+)'(\s*[,}]\s*)$/,(i,o,l,c)=>/,\s*[A-Za-z_$][\w$-]*\s*:/.test(l)?i:l.includes("'")?`${o}'${W7(l)}'${c}`:i)).join(`
5112`);return n===t.content?t:{...t,content:n}})}function G7(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/^tsconfig(?:\.[^.\/]+)?\.json$/i.test(r))return t;try{const n=JSON.parse(t.content);return n.compilerOptions={...n.compilerOptions||{}},n.compilerOptions.noUnusedLocals=!1,n.compilerOptions.noUnusedParameters=!1,{...t,content:`${JSON.stringify(n,null,2)}
5113`}}catch{const n=t.content.replace(/"noUnusedLocals"\s*:\s*true/g,'"noUnusedLocals": false').replace(/"noUnusedParameters"\s*:\s*true/g,'"noUnusedParameters": false');return n===t.content?t:{...t,content:n}}})}const K7=`
5114import React, { Component, ErrorInfo, ReactNode } from "react";
5115
5116export class PreviewErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error: Error | null }> {
5117  constructor(props: { children: ReactNode }) {
5118    super(props);
5119    this.state = { hasError: false, error: null };
5120  }
5121
5122  static getDerivedStateFromError(error: Error) {
5123    return { hasError: true, error };
5124  }
5125
5126  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
5127    console.error("React Error Boundary caught an error:", error, errorInfo);
5128  }
5129
5130  render() {
5131    if (this.state.hasError) {
5132      return (
5133        <div style={{ padding: '24px', fontFamily: 'system-ui, sans-serif', color: '#ef4444', backgroundColor: '#fef2f2', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
5134          <h2 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '16px' }}>Component Error</h2>
5135          <p style={{ marginBottom: '16px', color: '#991b1b' }}>The preview encountered a rendering error. The rest of the app is still running.</p>
5136          <pre style={{ backgroundColor: '#fee2e2', color: '#7f1d1d', padding: '16px', borderRadius: '8px', overflow: 'auto', fontSize: '13px', whiteSpace: 'pre-wrap' }}>
5137            {this.state.error?.toString()}
5138          </pre>
5139        </div>
5140      );
5141    }
5142    return this.props.children;
5143  }
5144}
5145`;function Y7(e){const t=e3(e);
5145if(!t)return e;let r=[...e];const n=r.findIndex(o=>o.path.replace(/^\/+/,"").split("\\").join("/")===t);if(n<0)return e;const s=r[n].content;if(s.includes("PreviewErrorBoundary"))return e;r=gp(r,"src/PreviewErrorBoundary.tsx",K7);let i=`import { PreviewErrorBoundary } from './PreviewErrorBoundary';
5146`+s;return i=i.replace(new RegExp("<App\\\\s*/?>","g"),"<PreviewErrorBoundary><App /></PreviewErrorBoundary>"),r[n]={...r[n],content:i},r}function pf(e){return Qf(e).files}function Qf(e){const t=X7(J7(O7(Y7(L7($7(D7(R7(G7(V7(H7(z7(_F(e))))))))))))),r=b7(t),n=HE(t1(r));return{files:n.added.length>0?n.files:r,addedDeps:n.added}}function J7(e){const t=typeof window<"u"?window.location.origin.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",r=t?new RegExp(`${t}\\/studio(?=\\/|["'?#\\s]|$)`,"g"):null;return e.map(n=>{if(!/\.(tsx|jsx|ts|js|html)$/.test(n.path))return n;let s=n.content.replace(/https?:\/\/(?:www\.)?studiojungle\.ai\/studio(?=\/|["'?#\s]|$)/gi,"").replace(/https?:\/\/(?:www\.)?studiojungle\.ai(?=\/|["'?#\s]|$)/gi,"").replace(/https?:\/\/(?:127\.0\.0\.1|localhost):\d+\/studio(?=\/|["'?#\s]|$)/gi,"");return r&&(s=s.replace(r,"")),s=s.replace(/\b(href|to|data-href|data-to)=["']\/studio(?:\/)?["']/g,'$1="/"').replace(/\b(href|to|data-href|data-to)=["']\/studio\/([^"']*)["']/g,'$1="/$2"').replace(/(["'`])\/studio(?:\/)?\1/g,"$1/$1").replace(/(["'`])\/studio\/([^"'`]*)\1/g,"$1/$2$1"),s===n.content?n:{...n,content:s}})}function X7(e){return e.map(t=>{if(!/\.html?$/i.test(t.path))return t;const r=t.content.split(`
5147`);let n=!1;const s=r.map(i=>{var o;return/<link\b/i.test(i)&&/\brel=["']icon["']/i.test(i)&&/data:image\/svg\+xml;utf8,<svg/i.test(i)?(n=!0,`${((o=i.match(/^\s*/))==null?void 0:o[0])||""}<link rel="icon" type="image/svg+xml" href="/favicon.svg" />`):i});return n?{...t,content:s.join(`
5148`)}:t})}const _y="__sj_webcontainer_singleton__";function Z7(){const e=globalThis;return e[_y]||(e[_y]={instance:null,bootPromise:null}),e[_y]}async function Q7(){const e=Z7();return e.instance?e.instance:(e.bootPromise||(e.bootPromise=C$.boot().then(t=>(e.instance=t,t)).catch(t=>{throw e.bootPromise=null,t})),e.bootPromise)}const t3=Q7;let n3=!1;function eU(){return n3}function tU(){n3=!0}function hf(e){return e.map(t=>`${t.path}::${t.content.length}::${t.content.slice(0,48)}::${t.content.slice(-48)}`).sort().join("|")}function nS(e){return e.filter(t=>t.path==="package.json"||t.path==="package-lock.json").map(t=>`${t.path}::${t.content}`).sort().join(`
5149`)}function rS(e){const t=new Map;for(const r of e)t.set(r.path,`${r.content.length}::${r.content.slice(0,48)}::${r.content.slice(-48)}`);return t}function sS(e,t){const r=[];for(const n of t){const s=e.get(n.path),i=`${n.content.length}::${n.content.slice(0,48)}
5149::${n.content.slice(-48)}`;s!==i&&r.push(n)}return r}const nU=900,rU=300,sU=250,aU=6e4,iU=500,oU=12e3,aS=15e3,lU=2*6e4,cU=25e3;function uU(e,t){const r=[e,...t||[]].join(`
5150`).toLowerCase();return/node_modules\/vite\/package\.json.*no such file|vite binary missing|no vite process|\(no vite\.log\)|preview isn't responding/i.test(r)}function iS(e,t){const r=[e,...t||[]].join(`
5151`).toLowerCase();return/sandbox.*not.*found|sandbox.*not.*running|failed to fetch|networkerror|edge function 5xx|connection error|preview runtime request failed|no sandbox|e2b.*timeout/i.test(r)}function dU(e){const t=e.toLowerCase();return/sandbox.*not.*found|sandbox.*not.*running|failed to fetch|networkerror|connection error|edge function|eaddrinuse|port\s*5173.*in use/.test(t)?!1:/cannot find module|failed to resolve import|does not provide an export named|syntaxerror|referenceerror|ts\d{4}|enoent|eresolve|plugin .* failed/.test(t)}async function oS(e,t=45e3,r=iU){const n=Date.now();for(;Date.now()-n<t;){try{const s=await Pr({action:"health",projectId:e});if(s.kind==="healthy"||s.ok!==!1&&s.port_open)return!0;if(s.transitional){await new Promise(i=>setTimeout(i,Math.min(r,800)));continue}if(s.kind==="vite_dead"||s.kind==="sandbox_missing"||s.kind==="no_sandbox")return!1}catch{}await new Promise(s=>setTimeout(s,r))}return!1}function ff(e){return e.kind==="dead"||e.kind==="sandbox_missing"||e.kind==="no_sandbox"||e.sandbox_alive===!1}function mf(e){return e==="warming"||e==="installing"||e==="syncing"}const r3=new Map,s3=4*60*1e3;function gf(e){const t=r3.get(e);return!!t&&Date.now()-t<s3}function Dd(e){r3.set(e,Date.now())}const zo=new Map;function _o(e){const t=zo.get(e);return t?Date.now()-t.ts>s3?(zo.delete(e),null):t.url:null}function lS(e,t){zo.set(e,{url:t,ts:Date.now()})}const cS=new Map,Nl=new Map,kl=new Map,To=new Set,xf=new Set;function pU({mobile:e,children:t}){return a.jsxs("div",{className:e?"relative flex h-full w-full items-center justify-center overflow-auto py-4":"relative h-full w-full",style:e?{perspective:"1200px"}:void 0,children:[e&&a.jsx("div",{className:"absolute inset-0 pointer-events-none bg-[radial-gradient(circle_at_center,rgba(34,197,94,0.10),transparent_42%)]"}),a.jsxs("div",{className:e?"relative flex flex-col rounded-[3.2rem] border border-white/10 bg-gradient-to-b from-[#0d0d12] via-[#24242b] to-[#08080b] shadow-2xl":"relative h-full w-full",style:e?{width:"min(392px, calc(100vw - 96px))",height:"min(800px, calc(100vh - 200px))",minHeight:"640px",maxHeight:"calc(100vh - 200px)",padding:"12px 10px",boxShadow:"0 0 0 1px rgba(255,255,255,0.08) inset, 0 25px 60px -12px rgba(0,0,0,0.5), 0 8px 24px -4px rgba(0,0,0,0.3), -4px 0 12px -2px rgba(0,0,0,0.15), 4px 0 12px -2px rgba(0,0,0,0.15)"}:void 0,children:[e&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute -left-[3px] top-[120px] w-[3px] h-[32px] rounded-l-sm bg-gradient-to-b from-[#3a3a42] to-[#2a2a30]"}),a.jsx("div",{className:"absolute -left-[3px] top-[164px] w-[3px] h-[32px] rounded-l-sm bg-gradient-to-b from-[#3a3a42] to-[#2a2a30]"}),a.jsx("div",{className:"absolute -right-[3px] top-[148px] w-[3px] h-[48px] rounded-r-sm bg-gradient-to-b from-[#3a3a42] to-[#2a2a30]"})]}),a.jsxs("div",{className:e?"flex-1 flex flex-col rounded-[2.6rem] overflow-hidden bg-black relative":"h-full w-full",children:[e&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"absolute top-[10px] left-1/2 -translate-x-1/2 z-20 flex items-center gap-2 bg-black rounded-full px-4 py-[5px] pointer-events-none",style:{minWidth:"120px"},children:[a.jsx("div",{className:"w-[8px] h-[8px] rounded-full bg-[#1a1a2e] ring-1 ring-[#2a2a3a]"}),a.jsx("div",{className:"flex-1"}),a.jsx("div",{className:"w-[6px] h-[6px] rounded-full bg-[#0a3d0a]"})]}),a.jsx("div",{className:"h-[52px] bg-black flex items-end justify-between px-8 pb-1 shrink-0 z-10 pointer-events-none",children:a.jsx("span",{className:"text-[12px] font-semibold text-white/90 tabular-nums",children:"9:41"})})]}),a.jsx("div",{className:e?"flex-1 flex w-full bg-white relative min-h-0":"h-full w-full",children:t}),e&&a.jsx("div",{className:"h-[26px] bg-black flex items-center justify-center shrink-0 pointer-events-none",children:a.jsx("div",{className:"w-[120px] h-[4px] rounded-full bg-white/25"})})]})]})]})}function hU({files:e,envVars:t,previewPath:r,projectId:n,viewport:s="desktop",isBuilding:i=!1,onBuildError:o,visualEditorActive:l=!1,onVisualEditClick:c,onVisualEditMulti:u}){const{project:d,notifyVitePreviewReady:p,previewSyncing:h,toolCallHistory:f}=gn(),x=(d==null?void 0:d.name)??null,g=n?_o(n):null,[y,b]=m.useState(g?"ready":"warming"),[v,k]=m.useState(g),[N,j]=m.useState(null),[w,S]=m.useState(null),[T,C]=m.useState([]),[A,P]=m.useState(!1),[E,_]=m.useState(n?To.has(n):!1),I=m.useRef(null),D=j7(n);m.useEffect(()=>{v&&(D.viteReady||D.viteUp===!0)&&(_(!0),b(V=>V==="warming"||V==="installing"||V==="syncing"?"ready":V))},[D.viteReady,D.viteUp,v]);const M=m.useRef(null);m.useEffect(()=>{const V=M.current;M.current=v,V!==null&&V!==v&&(_(!1),n&&To.delete(n))},[v,n]);const B=m.useRef(e),$=m.useRef(!1),K=m.useRef(0),R=m.useRef(!1),Y=m.useRef(y);m.useEffect(()=>{Y.current=y},[y]);const Z=m.useRef(E);m.useEffect(()=>{Z.current=E},[E]);const O=m.useRef(!1),ne=m.useRef(0),oe=2e4,he=m.useRef(0),ae=12e3,ve=m.useRef(!1),re=m.useRef(!1),se=m.useRef(null),le=m.useRef(null),te=()=>n&&cS.get(n)||"",We=V=>{n&&cS.set(n,V)},Me=()=>n?Nl.get(n)||new Map:new Map,Te=V=>{n&&Nl.set(n,V)},Ee=m.useRef(!1),st=m.useRef(!1);m.useEffect(()=>{st.current=i},[i]);const xt=m.useRef(!1),on=m.useRef(0),Yt=m.useRef(0),mt=m.useRef(!1),ln=m.useRef(0);m.useEffect(()=>{B.current=e},[e]);const at=m.useCallback(V=>{C(ye=>[...ye.slice(-180),C7(V)])},[]),gt=m.useCallback(async V=>{var ye,me,_e,dt,kt,wn,kn,Ae;if(!n){b("error"),j("No project id available.");return}if($.current&&V==="apply"){O.current=!0;return}if($.current=!0,V==="start"?(b("warming"),_(!1)):V==="reinstall"?b("installing"):V==="restart"&&b("syncing"),V==="restart"||V==="reinstall"){try{I.current&&(I.current.src="about:blank")}catch{}
5151ie.current=null,_(!1)}try{const rt=B.current,{files:fe,addedDeps:lt}=Qf(rt);let yt=fe.map(ge=>({path:ge.path,content:ge.content}));if(lt.length>0){const ge=kl.get(n)??new Set,Se=lt.filter(Ie=>!ge.has(Ie));if(Se.length>0){at(`[sync] auto-patching package.json deps: ${Se.join(", ")}`);const Ie=yt.find(De=>De.path.replace(/^\/+/,"")==="package.json");if(Ie&&(V==="apply"||V==="start"))try{await Pr({action:"add_deps",projectId:n,deps:Se,files:[{path:"package.json",content:Ie.content}]});for(const De of Se)ge.add(De);kl.set(n,ge)}catch{}}}const zt=tS(t,n);if(zt&&Object.keys(zt).length>0){const ge=`${Object.entries(zt).map(([Se,Ie])=>`${Se}=${Ie}`).join(`
5152`)}
5153`;yt=yt.filter(Se=>{const Ie=Se.path.replace(/^\/+/,"");return Ie!==".env.local"&&Ie!==".env"}),yt.push({path:".env.local",content:ge})}const Fe=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]);let qt=yt,fr,Jt=!1;const _t=Me();if(V==="apply"&&_t.size>0){const ge=sS(_t,yt),Se=new Set(ge.map(De=>De.path)),Ie=yt.filter(De=>Fe.has(De.path)&&!Se.has(De.path));if(qt=[...ge,...Ie],Se.has("src/App.tsx")){const De=new Set(qt.map(Ce=>Ce.path));for(const Ce of yt)!De.has(Ce.path)&&Ce.content.includes("AUTO-GENERATED STUB")&&(qt.push(Ce),De.add(Ce.path))}fr=yt.map(De=>De.path),Jt=ge.length===0,at(`[sync] changed ${ge.length}/${yt.length} file${ge.length===1?"":"s"}${Jt?" — skipping reload":""}`)}if(V==="apply"&&Jt){if(at("[sync] no changes to send — skipping apply"),_o(n)&&(b("ready"),_(!0)),!st.current&&xt.current&&!mt.current){xt.current=!1;try{(me=(ye=I.current)==null?void 0:ye.contentWindow)==null||me.postMessage({type:"sj-reload"},"*")}catch{}}return}V==="apply"&&(_o(n)||Z.current||b("syncing"));const z=V==="apply"&&!1,ee=V==="start"?"start":V==="restart"?"restart":V==="reinstall"?"reinstall":z?"apply_via_agent":"apply";let de=await Pr({action:ee,projectId:n,files:qt,manifest:fr,previewPath:r,filesHash:hf(yt),packageHash:nS(yt)});if(z&&(de==null?void 0:de.ok)===!1&&(de.code==="agent_not_ready"||de.code==="agent_ws_failed")&&(at(`[apply] agent fast-path failed (${de.code}), falling back to legacy apply`),de=await Pr({action:"apply",projectId:n,files:qt,manifest:fr,previewPath:r,filesHash:hf(yt),packageHash:nS(yt)})),(_e=de.logs)!=null&&_e.length&&C(de.logs.slice(-180)),(dt=de.timing_breakdown_ms)!=null&&dt.milestonesMs){const ge=de.timing_breakdown_ms.milestonesMs,Se=Ie=>typeof Ie=="number"?`${Math.round(Ie)}ms`:"n/a";at(`[sla] create=${Se(ge.sandboxCreateMs)} ready=${Se(ge.sandboxReadyMs)} install=${Se(ge.dependencyInstallMs)} vite=${Se(ge.viteBootMs)} compile=${Se(ge.compileMs)}`)}if(de.ok===!1||de.error){const ge=de.error||de.message||"Live preview failed.",Se=de.logs||[];if(iS(ge,Se)&&V!=="restart"&&Date.now()-Yt.current>
5153cU){Yt.current=Date.now(),at("[sync] runtime infrastructure issue detected — forcing sandbox restart"),S(null),$.current=!1,window.setTimeout(()=>gt("restart"),0);return}if(de.compile_auto_repair_attempted&&at("[sync] compile auto-repair attempted once before failing"),uU(ge,Se)&&(V==="apply"||V==="start")&&Date.now()-on.current>lU){on.current=Date.now(),at("[sync] Vite or node_modules missing in sandbox — auto reinstall"),$.current=!1,window.setTimeout(()=>gt("reinstall"),0);return}if(at(ge),j(ge),b("error"),zc(n,"failed",ge),o){const Ie=(de.logs||[]).filter(Ce=>dU(Ce)).slice(-8),De=Ie.length>0?Ie:[ge];iS(De.join(`
5154`),void 0)||o(De)}return}if(de.preview_proxy_url){Te(rS(yt));let ge=de.preview_proxy_url;const Se=void 0,Ie=!!_o(n)||Z.current,De=V==="apply"?Ie?0:aS:oU,Ce=De===0?!0:await oS(n,De);Ce||at("[sync] Vite port not ready yet — showing preview optimistically"),n&&lS(n,ge),k(wt=>wt===ge?wt:ge),j(null),S(null),b("ready"),_(!0),n&&To.add(n),Ce&&zc(n,"passed"),p(),Ce||oS(n,aS).then(wt=>{wt&&n&&zc(n,"passed")}).catch(()=>null);try{if(I.current){const wt=Nt(ge);(!I.current.src||I.current.src==="about:blank"||I.current.src!==wt)&&(I.current.src=wt)}}catch{}if((V==="apply"||V==="restart"||V==="reinstall")&&!mt.current&&!(V==="apply"&&Jt))if(st.current&&V==="apply")xt.current=!0;else try{(wn=(kt=I.current)==null?void 0:kt.contentWindow)==null||wn.postMessage({type:"sj-reload"},"*"),xt.current=!1}catch{}(V==="restart"||V==="reinstall")&&(mt.current=!1),Array.isArray(de.build_errors)&&de.build_errors.length>0&&o&&o(de.build_errors.map(wt=>`${wt.file?`${wt.file}: `:""}${wt.message}${wt.plugin?` [${wt.plugin}]`:""}`))}else if(de.ok!==!1&&(de.status==="running"||ee==="apply_via_agent")){if(Te(rS(yt)),j(null),S(null),b("ready"),_(!0),n&&To.add(n),zc(n,"passed"),p(),(V==="apply"||V==="restart"||V==="reinstall")&&!mt.current&&!(V==="apply"&&Jt))if(st.current&&V==="apply")xt.current=!0;else try{(Ae=(kn=I.current)==null?void 0:kn.contentWindow)==null||Ae.postMessage({type:"sj-reload"},"*"),xt.current=!1}catch{}(V==="restart"||V==="reinstall")&&(mt.current=!1),Array.isArray(de.build_errors)&&de.build_errors.length>0&&o&&o(de.build_errors.map(Se=>`${Se.file?`${Se.file}: `:""}${Se.message}${Se.plugin?` [${Se.plugin}]`:""}`))}else de.status==="running"&&(j("Runtime returned no proxy URL; HMR will not work."),b("error"))}catch(rt){const fe=rt instanceof Error?rt.message:String(rt);at(fe),j(fe),b("error"),zc(n,"failed",fe)}finally{if($.current=!1,K.current=Date.now(),R.current&&(R.current=!1),re.current){re.current=!1,O.current=!1;const rt=n;(async()=>{if(rt){try{const fe=await Pr({action:"health",projectId:rt});if(!ff(fe)&&fe.ok!==!1)return}catch{}gt("restart")}})()}else O.current&&(O.current=!1,window.setTimeout(()=>gt("apply"),0));ve.current&&(ve.current=!1,window.setTimeout(()=>gt("restart"),0))}},[at,t,p,o,r,n]),$t=m.useCallback(V=>{if(!n)return;const ye=Date.now();if(!(ye-he.current<ae)){if(mf(Y.current)){at(`${V} bootstrap in progress — deferring respawn`),_(!1);return}he.current=ye,at(`${V} sandbox reaped — respawning from saved files`),b("warming"),_(!1),ie.current=null;try{I.current&&I.current.src!=="about:blank"&&(I.current.src="about:blank")}catch{}if(zo.delete(n),Nl.delete(n),kl.delete(n),$.current){re.current=!0;return}gt("restart")}},[n,at,gt]);m.useEffect(()=>{if(!n)return;if(gf(n)){const ye=_o(n);ye&&(k(ye),b("ready"),_(!1),Pr({action:"health",projectId:n}).then(me=>{const _e=me,dt=ff(_e)||_e.ok===!1;if(!dt&&(_e.kind==="healthy"||_e.port_open)){_(!0);return}dt&&(at("[sync] cached preview URL stale — respawning sandbox"),zo.delete(n),Nl.delete(n),kl.delete(n),_(!1),b("warming"),gt("restart"))}).catch(()=>null)),xf.has(n)||(xf.add(n),Te(new Map),at("[sync] remount reconcile — forcing full apply to sandbox"),gt("apply"));return}try{if(sessionStorage.getItem(`sj-defer-warmup:${n}`))return}catch{}if(Dd(n),pf(B.current).length<3){at("[sync] deferring start — waiting for project files");return}We(hf(e)),gt("start")},[n]);const ue=m.useRef(!1);m.useEffect(()=>{ue.current=!1},[n]),m.useEffect(()=>{if(!n||v)return;const V=window.setTimeout(()=>{if(!(v||$.current||ue.current)){ue.current=!0,at("[watchdog] no preview URL after 20s — retrying start");try{sessionStorage.removeItem(`sj-defer-warmup:${n}`)}catch{}gt("start")}},2e4);return()=>window.clearTimeout(V)},[n,v,gt,at]),m.useEffect(()=>{if(!n)return;const V=ye=>{const me=ye.detail;if(!(me!=null&&me.projectId&&me.projectId!==n||v||$.current||pf(B.current).length<3)){try{sessionStorage.removeItem(`sj-defer-warmup:${n}`)}catch{}gf(n)||Dd(n),at("[sync] first-preview-kick — starting sandbox with streamed files"),gt("start")}};return window.addEventListener("sj:first-preview-kick",V),()=>window.removeEventListener("sj:first-preview-kick",V)},[n,v,gt,at]),m.useEffect(()=>{if(!n||v||$.current)return;let V=!1;try{V=!!sessionStorage.getItem(`sj-defer-warmup:${n}`)}catch{}if(!(!V||pf(B.current).length<3)){try{sessionStorage.removeItem(`sj-defer-warmup:${n}`)}catch{}gf(n)||Dd(n),at("[sync] defer-warmup cleared — enough files to start preview"),gt("start")}},[e,n,v,gt,at]);const je=m.useRef("");m.useEffect(()=>{const V=tS(t,n);if(!n||!V||Object.keys(V).length===0)return;const ye=Object.entries(V).sort(([dt],[kt])=>dt.localeCompare(kt)).map(([dt,kt])=>`${dt}=${kt}`).join("&");if(ye===je.current)return;const me=je.current.length>0,_e=!!_o(n);je.current=ye,me||_e||$.current?gt("restart"):ve.current=!0},[t,n,gt]),m.useEffect(()=>{var kt,wn;if(!n)return;const V=hf(e),ye=V!==te();ye&&We(V);const me=Ee.current&&!i;if(Ee.current=i,me&&xt.current&&!mt.current){xt.current=!1;try{(wn=(kt=I.current)==null?void 0:kt.contentWindow)==null||wn.postMessage({type:"sj-reload"},"*")}catch{}}if(!ye&&!me)return;const _e=Me();if(_e.size>0&&!me){const{files:kn}=Qf(B.current);if(sS(_e,kn).length===0)return}const dt=me?0:i?_o(n)?nU:sU:rU;return se.current&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{if(se.current=null,le.current&&(window.clearTimeout(le.current),le.current=null),!_o(n)&&pf(B.current).length>=3){try{sessionStorage.removeItem(`sj-defer-warmup:${n}`)}catch{}gf(n)||Dd(n),gt("start")}else gt("apply")},dt),i&&!le.current&&!me&&(le.current=window.setTimeout(()=>{le.current=null,se.current&&(window.clearTimeout(se.current),se.current=null),gt("apply")},aU)),()=>{se.current&&window.clearTimeout(se.current)}},[e,n,gt,i]);const ct=m.useRef([]),it=m.useRef(null),q=m.useRef(0);m.useEffect(()=>{if(!n)return;const V=2*6e4,ye=()=>{if(document.visibilityState!=="visible")return;const me=Date.now();me-q.current<V||(q.current=me,!$.current&&gt("apply"))};return document.addEventListener("visibilitychange",ye),()=>{document.removeEventListener("visibilitychange",ye)}},[n,gt]),m.useEffect(()=>{if(!n)return;const V=[5e3,3e4,12e4],ye=5*6e4,me=3,_e=dt=>{var Ae,rt;if(!dt.data||typeof dt.data!="object")return;if(dt.data.type==="sj-runtime-error"){const fe=dt.data.payload||{},lt=((Ae=fe==null?void 0:fe.error)==null?void 0:Ae.message)||"unknown",yt=(rt=fe==null?void 0:fe.error)==null?void 0:rt.signature,zt=yt?`[${yt}]`:"",Fe=fe!=null&&fe.source?` at ${fe.source}:${(fe==null?void 0:fe.lineno)??"?"}`:"";if(at(`Preview runtime ${fe.kind||"error"} ${zt}: ${lt}${Fe}`),/failed to resolve import/i.test(lt)&&n&&!$.current&&Date.now()-ne.current>oe){const{addedDeps:qt}=Qf(B.current);qt.length>0&&(ne.current=Date.now(),at(`[sync] Vite missing deps — installing: ${qt.join(", ")}`),gt("apply"))}S(`${lt}${Fe}`),o&&o([`RUNTIME${zt}: ${lt}${Fe}`]),fe!=null&&fe.first_load&&yt==="duplicate_router"&&at("Detected duplicate <Router>. Running repair pass…");return}if(dt.data.type!=="sj-preview-sandbox-stopped")return;const kt=Date.now(),wn=ct.current.filter(fe=>kt-fe<ye);if(ct.current=wn,wn.length>=me){at("Sandbox went offline again — auto-restart paused, click Restart to retry.");return}if(it.current)return;const kn=V[wn.length]??V[V.length-1];at(`Sandbox went offline — auto-restart in ${Math.round(kn/1e3)}s.`),it.current=window.setTimeout(()=>{it.current=null,ct.current.push(Date.now()),gt("restart")},kn)};return window.addEventListener("message",_e),()=>{window.removeEventListener("message",_e),it.current&&(window.clearTimeout(it.current),it.current=null)}}
5154,[at,n,gt]);const Nt=m.useCallback(V=>{if(!V||V==="about:blank")return V;try{const ye=new URL(V),me=ye.pathname.replace(/\/{2,}/g,"/"),_e=me.endsWith("/"),dt=me.split("/").filter(Boolean),kt=[];for(const kn of dt){if(kt[kt.length-1]===kn){console.warn(`[preview] collapsing duplicate URL segment "${kn}" in ${ye.pathname}`);continue}kt.push(kn)}const wn=kt.length===0?"/":"/"+kt.join("/")+(_e?"/":"");return wn!==ye.pathname?(ye.pathname=wn,console.log(`[base-trace] iframe src normalized: ${V} → ${ye.toString()}`),ye.toString()):(console.log(`[base-trace] iframe src (host=${ye.host}, path=${ye.pathname||"/"})`),V)}catch{return V}},[]),U=m.useCallback((V,ye)=>{const me=V.replace(/\/+$/,""),_e=(ye||"").replace(/^\/+/,"").replace(/\/{2,}/g,"/");return _e===""?me+"/":me+"/"+_e},[]);m.useEffect(()=>{if(!n)return;const V=ye=>{const me=ye.detail;if(!(!(me!=null&&me.url)||me.projectId!==n)){lS(n,me.url),k(_e=>_e||me.url),b("warming"),_(!1),Dd(n);try{if(I.current){const _e=Nt(me.url);I.current.src!==_e&&(I.current.src=_e)}}catch{}}};return window.addEventListener("sj:preview-url-ready",V),()=>window.removeEventListener("sj:preview-url-ready",V)},[n,Nt]);const Ne=m.useRef(0),Ft=12e3,Zt=m.useCallback(()=>{!I.current||!v||(I.current.src=Nt(v))},[v,Nt]),Ke=m.useCallback(()=>{var ye;if(((ye=I.current)==null?void 0:ye.src)==="about:blank")return;$.current&&(R.current=!0);const V=n?To.has(n):!1;Y.current!=="ready"&&!V&&!Z.current&&_(!1),n&&(async()=>{try{const me=await Pr({action:"health",projectId:n}),_e=ff(me);if($.current&&!_e)return;if($.current&&_e&&mf(Y.current)){_(!1);return}if(_e&&mf(Y.current)){_(!1);return}if(me.transitional||me.kind==="transitional"){if(at(`[iframe-load] sandbox is ${me.status} — holding skeleton, no restart`),!$.current&&v&&(Y.current==="ready"||Z.current)){_(!0),b("ready");return}if(!v&&(Y.current==="warming"||Y.current==="installing")){_(!1);try{I.current&&I.current.src!=="about:blank"&&(I.current.src="about:blank")}catch{}}return}if(me.ok!==!1){if(I.current&&I.current.src==="about:blank"&&v){I.current.src=Nt(v);return}_(!0),n&&To.add(n),zc(n,"passed"),b("ready"),j(null),S(null),p(),Ne.current=0;return}if(st.current&&!_e)return;const dt=Date.now(),kt=dt-Ne.current;if(kt<Ft){at(`[iframe-load] sandbox still down ${Math.round(kt/1e3)}s after recovery — holding skeleton (no re-fire)`),_(!1);try{I.current&&I.current.src!=="about:blank"&&(I.current.src="about:blank")}catch{}return}if(Ne.current=dt,_e){$t("[iframe-load]"),Ne.current=Date.now();return}at("[iframe-load] post-load probe says Vite is down — restarting sandbox"),_(!1);try{I.current&&(I.current.src="about:blank")}catch{}zo.delete(n),Nl.delete(n),xf.delete(n),kl.delete(n),await gt("restart"),Ne.current=Date.now()}catch{Y.current==="ready"&&v&&!st.current?(_(!0),n&&To.add(n)):_(!1)}})()},[n,at,gt,v,Nt,$t]);m.useEffect(()=>{var ye;if(!v||!I.current)return;const V=I.current;try{((ye=V.contentDocument)==null?void 0:ye.readyState)==="complete"&&Ke()}catch{}},[v,Ke]);const ie=m.useRef(null),we=m.useRef(null);m.useEffect(()=>{var V;if(!(!I.current||!v||!r)&&we.current!==r){we.current=r;try{(V=I.current.contentWindow)==null||V.postMessage({type:"sj-parent-nav",path:r},"*")}catch{}}},[r,v]);const Je=m.useCallback(()=>{var V;if(!(!I.current||!v))try{(V=I.current.contentWindow)==null||V.postMessage({type:l?"sj:visual-editor-on":"sj:visual-editor-off"},"*")}catch{}},[l,v]);if(m.useEffect(()=>{Je()},[Je]),m.useEffect(()=>{E&&Je()},[E,Je]),m.useEffect(()=>{if(!n||!v)return;let V=!1;const ye={current:!1},me=3,_e=10*60*1e3,dt=[];let kt=!1,wn=0;async function kn(){if(!(V||ye.current||kt)){ye.current=!0;try{const fe=await Pr({action:"health",projectId:n}),lt=ff(fe);if(V||$.current&&!lt||lt&&mf(Y.current))return;if(fe.transitional){if(!wn)wn=Date.now();else if(Date.now()-wn>12e4&&!$.current&&!st.current){at("[keep-alive] transitional >90s — forcing restart"),wn=0,_(!1);try{I.current&&(I.current.src="about:blank")}catch{}n&&(zo.delete(n),Nl.delete(n),kl.delete(n)),await gt("restart");return}if(!v&&(Y.current==="warming"||Y.current==="installing")){_(!1);try{I.current&&I.current.src!=="about:blank"&&(I.current.src="about:blank")}catch{}}return}wn=0;const yt=fe.ok!==!1;if(yt&&(I.current&&I.current.src==="about:blank"&&v&&(I.current.src=Nt(v)),Y.current==="ready"&&(_(!0),n&&To.add(n))),!yt){if(st.current&&!lt||!lt&&Date.now()-K.current<45e3)return;if(lt){$t("[keep-alive]");return}const zt=Date.now();for(;dt.length>0&&zt-dt[0]>_e;)dt.shift();if(dt.length>=me){kt=!0,at(`[keep-alive] ${me} restarts failed in ${_e/6e4}min — circuit open. Click Restart manually or check the sandbox logs.`),b("error"),j("Preview kept crashing after multiple auto-restarts. Likely an error in the latest code — check the sandbox logs (Logs button) for the Vite error, then click Restart when fixed.");return}dt.push(zt),at(`[keep-alive] sandbox not responding — restart ${dt.length}/${me} in window`),_(!1);try{I.current&&(I.current.src="about:blank")}catch{}n&&(zo.delete(n),Nl.delete(n),xf.delete(n),kl.delete(n)),await gt("restart")}}catch(fe){at(`[keep-alive] probe failed: ${fe.message}`)}finally{ye.current=!1}}}kn();const Ae=i?15*1e3:20*1e3,rt=window.setInterval(kn,Ae);return()=>{V=!0,window.clearInterval(rt)}},[n,v,gt,at,i,Nt,$t]),m.useEffect(()=>{if(!v||!n)return;const V=window.setInterval(()=>{var dt;if($.current)return;const ye=I.current;if(!ye)return;const me=ye.src||"";if((me==="about:blank"||me==="")&&v){const kt=((dt=ie.current)==null?void 0:dt.src)||Nt
5154(v);at("[watchdog] restoring iframe from about:blank"),ye.src=kt;return}!Z.current&&Date.now()-K.current>8e3&&Ke()},5e3);return()=>window.clearInterval(V)},[v,n,Nt,at,Ke]),m.useEffect(()=>{if(!n)return;function V(){var _e;const me=(_e=I.current)==null?void 0:_e.getBoundingClientRect();return me?{top:me.top,left:me.left}:{top:0,left:0}}function ye(me){var dt,kt,wn,kn,Ae;const _e=me==null?void 0:me.data;if(!(!_e||typeof _e!="object")){if(_e.type==="sj:visual-editor-ready"&&me.source===((dt=I.current)==null?void 0:dt.contentWindow)){try{(kt=me.source)==null||kt.postMessage({type:l?"sj:visual-editor-on":"sj:visual-editor-off"},"*")}catch{}return}if(_e.type==="sj:visual-edit-clicked"&&c&&_e.payload){const rt=V();c({..._e.payload,iframeOffset:rt})}else if(_e.type==="sj:visual-edit-multi"&&u&&((wn=_e.payload)!=null&&wn.items)){const rt=V();u(_e.payload.items.map(fe=>({...fe,iframeOffset:rt})))}else if(_e.type==="sj:hmr-up"){mt.current=!0,ln.current=0;try{(Ae=(kn=I.current)==null?void 0:kn.contentWindow)==null||Ae.postMessage({type:"sj-reset-reload-guard"},"*")}catch{}}else if((_e.type==="sj:hmr-down"||_e.type==="sj:hmr-disabled")&&(mt.current=!1,_e.type==="sj:hmr-disabled"&&(ln.current=(ln.current||0)+1,!($.current||st.current||Date.now()-K.current<3e4)&&ln.current>=3&&o))){const lt=`HMR_LOOP_ESCALATED: Vite kept reloading after compile errors (${typeof _e.reason=="string"?_e.reason:"reload-loop"}). The AI's last build likely has unresolved imports or syntax errors. Check the Vite log for details.`;console.error("[hmr-loop]",lt),o([lt]),ln.current=0}}}return window.addEventListener("message",ye),()=>window.removeEventListener("message",ye)},[c,u,n,l]),m.useEffect(()=>{const V=()=>{$.current||gt("restart")};return window.addEventListener("sj:auto-restart-preview",V),()=>window.removeEventListener("sj:auto-restart-preview",V)},[gt]),y==="error"&&!v)return a.jsxs("div",{className:"h-full flex flex-col bg-card",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b text-destructive",children:[a.jsx(is,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm font-semibold",children:"Preview unavailable"}),a.jsxs("button",{onClick:()=>gt("restart"),className:"ml-auto text-xs px-2 py-1 rounded border hover:bg-muted flex items-center gap-1",children:[a.jsx(zr,{className:"w-3 h-3"})," Restart"]}),a.jsx("button",{onClick:()=>gt("reinstall"),className:"text-xs px-2 py-1 rounded border hover:bg-muted",children:"Reinstall"})]}),a.jsx("div",{className:"flex-1 p-4 text-xs text-destructive whitespace-pre-wrap font-mono overflow-auto",children:N}),T.length>0&&a.jsx("div",{className:"border-t bg-muted/30 max-h-56 overflow-auto p-3 text-[10px] font-mono whitespace-pre-wrap",children:T.join(`
5155`)})]});const ot=(()=>{if(!v)return null;if(ie.current&&ie.current.proxyUrl===v)return ie.current.src;let V=v;try{const _e=new URL(v),dt=_e.pathname||"/";if(dt==="/"||dt==="")V=`${_e.origin}/`;else if(dt.endsWith("/"))V=`${_e.origin}${dt}`;else{const kt=dt.lastIndexOf("/"),wn=kt>=0?dt.slice(0,kt+1):"/";V=`${_e.origin}${wn}`}}catch{V=v.endsWith("/")?v:`${v}/`}const me=Nt(U(V,r&&r!=="/"?r:""));return ie.current={proxyUrl:v,src:me},me})();if(!v){const V=(x==null?void 0:x.trim())||"Your app",ye=y==="warming"?`Warming up the preview for ${V}`:y==="installing"?`Installing dependencies for ${V}`:y==="syncing"?"Syncing your latest changes":`Starting preview for ${V}`;return a.jsxs("div",{className:"h-full flex flex-col items-center justify-center px-6",children:[a.jsxs("div",{className:"w-full max-w-md rounded-2xl border bg-card/80 backdrop-blur-sm shadow-sm p-7 flex flex-col items-center text-center gap-4",children:[a.jsxs("div",{className:"relative w-16 h-16 rounded-2xl bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center",children:[a.jsx("span",{className:"absolute inset-0 rounded-2xl border border-primary/30 animate-[sj-card-pulse_2.2s_ease-out_infinite]"}),a.jsx("span",{className:"text-2xl font-semibold text-primary",children:(V[0]||"?").toUpperCase()})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:"Working…"}),a.jsx("div",{className:"text-[13px] text-muted-foreground leading-snug",children:ye})]}),a.jsx("style",{children:"@keyframes sj-card-pulse { 0% { transform: scale(1); opacity: 0.6; } 70% { transform: scale(1.18); opacity: 0; } 100% { transform: scale(1.18); opacity: 0; } }"})]}),T.length>0&&a.jsxs("details",{className:"mt-3 max-w-md w-full",children:[a.jsx("summary",{className:"cursor-pointer text-[10px] text-muted-foreground hover:text-foreground",children:"Show logs"}),a.jsx("div",{className:"mt-2 max-h-48 overflow-auto bg-muted/40 border rounded-lg p-3 text-[10px] font-mono whitespace-pre-wrap text-left",children:T.slice(-32).join(`
5156`)})]})]})}return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b bg-muted/30 text-[11px]",children:[a.jsx("span",{className:L("inline-block w-2 h-2 rounded-full",y==="ready"?"bg-green-500":y==="error"&&v?"bg-amber-500 animate-pulse":y==="error"?"bg-destructive":"bg-amber-500 animate-pulse")}),a.jsx("span",{className:"text-muted-foreground",children:y==="ready"?"Live · Vite HMR":y==="syncing"?"Syncing changes…":y==="installing"?"Installing…":y==="warming"?"Warming…":v?"Reconnecting…":"Error"}),a.jsxs("button",{onClick:()=>P(V=>!V),className:"ml-auto px-2 py-0.5 rounded hover:bg-muted flex items-center gap-1",title:"Toggle logs",children:[a.jsx(Yg,{className:"w-3 h-3"})," Logs"]}),a.jsxs("button",{onClick:Zt,className:"px-2 py-0.5 rounded hover:bg-muted flex items-center gap-1",title:"Hard reload",children:[a.jsx(zr,{className:"w-3 h-3"})," Reload"]}),a.jsx("button",{onClick:()=>gt("restart"),className:"px-2 py-0.5 rounded hover:bg-muted text-muted-foreground",title:"Restart dev server",children:"Restart"})]}),a.jsxs("div",{className:"relative flex-1 min-h-0",children:[a.jsx(pU,{mobile:s==="mobile",children:a.jsx("iframe",{ref:I,src:ot||v,className:s==="mobile"?"flex-1 w-full h-full border-0 bg-white":"w-full h-full border-0",sandbox:"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-storage-access-by-user-activation",credentialless:"",title:s==="mobile"?"Live preview (mobile)":"Live preview",onLoad:Ke,onError:()=>{try{window.postMessage({type:"sj-preview-sandbox-stopped",source:"iframe_onerror"},"*")}catch{}}})}),!E&&a.jsx("div",{className:"absolute inset-0 z-20 pointer-events-none",children:a.jsx(k7,{phase:y,isBuilding:!!i,hasLogs:T.length>0,onToggleLogs:()=>P(V=>!V),showLogs:A,minimal:!!v,projectName:x})}),h&&y==="ready"&&E&&a.jsx(N7,{toolCallHistory:f}),w&&y==="ready"&&a.jsxs("div",{className:"absolute top-2 left-2 right-2 z-30 rounded-lg border border-amber-500/40 bg-amber-500/10 backdrop-blur-sm px-3 py-2 text-[11px] text-amber-900 dark:text-amber-100 shadow-sm",children:[a.jsx("div",{className:"font-medium",children:"Preview component error"}),a.jsx("div",{className:"mt-0.5 opacity-90 line-clamp-3",children:w}),a.jsx("button",{type:"button",className:"mt-1.5 text-[10px] underline opacity-80 hover:opacity-100",onClick:()=>S(null),children:"Dismiss"})]}),A&&T.length>0&&a.jsx("div",{className:"absolute bottom-0 left-0 right-0 max-h-64 overflow-auto bg-card border-t shadow-lg p-3 text-[10px] font-mono whitespace-pre-wrap",children:T.join(`
5157`)})]})]})}function fU(e){return a.jsx("div",{className:"h-full w-full min-w-0 flex flex-col",children:a.jsx("div",{className:"flex-1 min-h-0",children:a.jsx(hU,{...e})})})}const em=3e4;function ax(e){return e.length<=em?e:e.slice(0,em)+`
5158
5159[truncated — ${e.length-em}
5159 more bytes]`}function mU(e){const t={},r=(n,s)=>{for(const i of n)if(i.type==="file")s[i.name]={file:{contents:i.content||""}};else if(i.type==="folder"&&i.children){s[i.name]||(s[i.name]={directory:{}});const o=s[i.name];r(i.children,o.directory)}};return r(e,t),t}async function gU(e){const t=e.getReader();let r="";for(;;){const{value:n,done:s}=await t.read();if(s||(r+=n,r.length>em*2))break}return r}async function s1(e,t,r){const n=await e.spawn(t,r),s=gU(n.output),i=await n.exit,o=await s;return{exit:i,output:o}}async function xU(e,t){const r=mU(t);await e.mount(r)}async function yU(e){const{exit:t,output:r}=await s1(e,"npx",["--yes","tsc","--noEmit","--pretty","false"]);if(t===0)return"✅ No type errors";const n=[];for(const l of r.split(`
5160`)){const c=l.match(/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/);c&&n.push({file:c[1],line:Number(c[2]),col:Number(c[3]),code:c[4],message:c[5]})}if(n.length===0)return ax(`❌ tsc exit ${t} (no parsed errors)
5161${r}`);const s=n.slice(0,30),i=s.map(l=>`- ${l.file}:${l.line}:${l.col} ${l.code} — ${l.message}`).join(`
5162`),o=n.length>s.length?`
5163…and ${n.length-s.length} more.`:"";return`❌ ${n.length} type error${n.length===1?"":"s"}:
5164${i}${o}`}async function bU(e){const{exit:t,output:r}=await s1(e,"npm",["run","build"]);return t===0?"✅ Build passed":ax(`❌ Build failed (exit ${t}):
5165${r}`)}async function vU(e,t){if(typeof document>"u")return"❌ SCREENSHOT_UNAVAILABLE: not in a browser context";const r=document.querySelector('iframe[title*="preview" i], iframe[data-webcontainer]');if(!r)return"❌ SCREENSHOT_UNAVAILABLE: no preview iframe found in DOM. Open the Build (Vite) tab to boot WebContainer first.";try{if(e&&e!=="/")try{const s=r.src||"",i=new URL(e,s||window.location.origin);r.src=i.toString(),await new Promise(o=>setTimeout(o,1500))}catch{}return`📸 Screenshot taken at ${e||"/"}${t==="mobile"?" (375×667 mobile)":t==="tablet"?" (768×1024 tablet)":" (1280×800 desktop)"}. Iframe was loaded — visual state captured for review (raster pass-through to vision model lands in a follow-up).`}catch(n){return`❌ Screenshot failed: ${n.message}`}}async function wU(e,t,r,n){if(!t||typeof t!="string")return"❌ add_package: missing package name";const s=new Set(["react-native","expo","expo-safe-area-context","react-native-safe-area-context","react-native-gesture-handler","react-native-reanimated","react-native-screens","react-native-svg","nativewind"]),i=["expo-","@expo/","react-native-","@react-native/","@react-navigation/"];if(s.has(t)||i.some(d=>t.startsWith(d)))return`❌ NATIVE_DEP_IN_WEB_APP: '${t}' is a React Native / Expo package and is not supported in the Vite web preview. Use responsive React + Tailwind/CSS instead.`;const o=r?`${t}@${r}`:t,l=["install",o,"--no-audit","--no-fund","--loglevel=error"];n&&l.push("--save-dev");const{exit:c,output:u}=await s1(e,"npm",l);return c===0?`✅ Installed ${o}${n?" (devDependency)":""}`:ax(`❌ Install failed (exit ${c}):
5166${u}`)}function jU(e){const t=r=>{for(const n of r){if(n.type==="file"&&n.name==="package.json"&&n.content)return n.content;if(n.type==="folder"&&n.children){const s=t(n.children);if(s)return s}}return null};return t(e)}function a3(e,t){return e.map(r=>r.type==="file"&&r.name==="package.json"?{...r,content:t}:r.type==="folder"&&r.children?{...r,children:a3(r.children,t)}:r)}function i3(e,t){if(!e.length||!e.every(c=>c.tool_name==="add_package"))return null;const r=jU(t);if(!r)return null;const n=e.map(c=>{var u;return String(((u=c.input)==null?void 0:u.name)||"").trim()}).filter(Boolean);if(!n.every(c=>sx[c]))return null;const{content:s,added:i}=e1(r,n),o=e.map(c=>{var d;const u=String(((d=c.input)==null?void 0:d.name)||"");return i.includes(u)?{tool_use_id:c.tool_use_id,content:`✅ Added ${u} to package.json (E2B sandbox will install on sync — skipped slow browser npm).`}:{tool_use_id:c.tool_use_id,content:`✅ ${u} already listed in package.json`}}),l=i.length>0?a3(t,s):t;return{results:o,files:l}}async function NU(e,t){var i,o,l,c,u;const r=i3(e,t);if(r)return r.results;let n;try{n=await t3(),await xU(n,t)}catch(d){const p=d instanceof Error?d.message:String(d);return e.map(h=>
5166({tool_use_id:h.tool_use_id,content:`⏭️ WebContainer unavailable (${p}). Continue without these results.`}))}const s=[];for(const d of e)try{let p="";if(d.tool_name==="validate_typescript")p=await yU(n);else if(d.tool_name==="run_build")p=await bU(n);else if(d.tool_name==="add_package"){const h=String(((i=d.input)==null?void 0:i.name)||""),f=(o=d.input)!=null&&o.version?String(d.input.version):void 0,x=!!((l=d.input)!=null&&l.dev);p=await wU(n,h,f,x)}else if(d.tool_name==="take_screenshot"){const h=String(((c=d.input)==null?void 0:c.route)||"/"),f=(u=d.input)!=null&&u.viewport?String(d.input.viewport):void 0;p=await vU(h,f)}else p=`⏭️ Unknown exec tool '${d.tool_name}' — skipped.`;s.push({tool_use_id:d.tool_use_id,content:p})}catch(p){const h=p instanceof Error?p.message:String(p);s.push({tool_use_id:d.tool_use_id,content:`❌ Execution threw: ${ax(h)}`})}return s}const uS={"package.json":"Wiring dependencies","package-lock.json":"Locking dependency tree","tsconfig.json":"Configuring TypeScript","tsconfig.node.json":"Configuring TypeScript","tsconfig.app.json":"Configuring TypeScript","vite.config.ts":"Configuring Vite","vite.config.js":"Configuring Vite","tailwind.config.ts":"Setting up Tailwind theme","tailwind.config.js":"Setting up Tailwind theme","postcss.config.js":"Configuring PostCSS","postcss.config.ts":"Configuring PostCSS",".eslintrc.cjs":"Configuring linting",".eslintrc.json":"Configuring linting",".prettierrc":"Configuring formatting",".gitignore":"Setting up version control","README.md":"Writing project README","index.html":"Setting up HTML entry","vercel.json":"Configuring Vercel deploy",".env.example":"Adding env template","schema.sql":"Designing database schema"};function Cu(e){return e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().trim()}function tm(e,t){let r=Cu(e).replace(/\spage$/i,"").trim();return r||(r="page"),(r==="home"||r==="index"||r==="")&&(r="home"),`${t} ${r} page`}function c0(e,t){let r=Cu(e);return r||(r="component"),/^(hero|header|footer|nav|navigation|navbar|sidebar|topbar)$/i.test(r.replace(/\s/g,""))?`${t==="Building"?"Crafting":t} ${r} section`:`${t} ${r} component`}function kU(e){const t=e.split("/").filter(Boolean).pop()||e,r=t.replace(/\.(tsx|ts|jsx|js|html|css|md|json|yaml|yml)$/i,"");if(/^src\/pages\//.test(e)||/^pages\//.test(e))return tm(r,"Editing").replace(/^Editing/i,"Updating");if(/^src\/components\//.test(e))return/layout/i.test(r)?"Updating shared layout":c0(r,"Editing").replace(/^(Editing|Crafting)/i,"Updating");if(/^src\/hooks\//.test(e))return`Updating ${Cu(r.replace(/^use/,""))||"hook"} hook`;if(/^src\/lib\//.test(e)||/^src\/utils\//.test(e)){const n=Cu(r)||t;return/store$/i.test(r)?`Updating ${n}`:`Updating ${n} utilities`}return/^src\/(App|main)\.(tsx|ts|jsx|js)$/i.test(e)?"Updating app routes":/layout/i.test(r)?"Updating shared layout":`Updating ${t}`}function SU(e,t,r=!1){const n=typeof(t==null?void 0:t.path)=="string"?t.path:"";if(r){if(e==="read_file"||e==="list_files")return"Preparing preview";if(e==="validate_typescript")return"Checking preview";if(e==="run_build")return"Building preview";if(e==="ask_next_phase")return"Preview ready — next steps";if(e==="write_file"&&n){const l=n.split("/").filter(Boolean).pop()||n;if(/tailwind|postcss|tsconfig|vite\.config|package\.json|utils\.ts/i.test(n))return"Preparing preview";if(/^src\/pages\//i.test(n)||/^pages\//i.test(n)){const c=l.replace(/\.(tsx|ts|jsx|js)$/i,"");return tm(c,"Building")}if(/^src\/components\//i.test(n)){const c=l.replace(/\.(tsx|ts|jsx|js)$/i,"");return c0(c,"Building")}if(/^src\/App\./i.test(n))return"Wiring routes";if(/index\.css$/i.test(n))return"Applying brand styles"}}let s=null;if(e==="write_file")s="Building";else if(e==="edit_file"||e==="str_replace")s="Editing";else if(e==="delete_file")s="Removing";else if(e==="read_file")s="Updating";else if(e==="add_package")return`Installing ${typeof(t==null?void 0:t.name)=="string"?t.name:"package"}`;
5166if(e==="list_files")return typeof(t==null?void 0:t.dir)=="string"&&t.dir&&`${t.dir}`,r?"Preparing preview":"Preparing project";if(e==="validate_typescript")return"Type-checking";if(e==="run_build")return"Running build";if(e==="take_screenshot")return`Previewing ${typeof(t==null?void 0:t.route)=="string"?t.route:"/"}`;if(e==="ask_next_phase")return"Wrapping up";if(e==="http_request"){const l=typeof(t==null?void 0:t.why)=="string"&&t.why?t.why:"";if(l)return`Calling API — ${l.slice(0,60)}`;try{const c=typeof(t==null?void 0:t.url)=="string"?new URL(t.url):null;return c?`Calling ${c.hostname}`:"Calling external API"}catch{return"Calling external API"}}if(!s||!n)return null;if(s==="Updating")return kU(n);const i=n.split("/").filter(Boolean).pop()||n;if(uS[i])return uS[i];if(/\.(css|scss|sass)$/i.test(i))return/\b(global|index|main|app)\b/i.test(i)?`${s==="Building"?"Crafting":s==="Editing"?"Polishing":"Removing"} global styles`:`${s==="Building"?"Crafting":s==="Editing"?"Polishing":"Removing"} styles`;if(/\.sql$/i.test(i))return s==="Building"?"Designing database schema":`${s} database schema`;if(/^supabase\/functions\//.test(n)){const l=n.split("/")[2]||"function";return`${s==="Building"?"Wiring":s} ${l.replace(/[-_]/g," ")} edge function`}if(/^src\/pages\//.test(n)){const l=i.replace(/\.(tsx|ts|jsx|js|html)$/i,"");if(s==="Building"||s==="Editing"||s==="Removing")return tm(l,s)}if(/^pages\//.test(n)){const l=i.replace(/\.(tsx|ts|jsx|js|html)$/i,"");if(s==="Building"||s==="Editing"||s==="Removing")return tm(l,s)}if(/^src\/components\//.test(n)){const l=i.replace(/\.(tsx|ts|jsx|js)$/i,"");if(s==="Building"||s==="Editing"||s==="Removing")return c0(l,s)}if(/^src\/hooks\//.test(n)){const l=i.replace(/\.(tsx|ts|jsx|js)$/i,"").replace(/^use/,"");return`${s==="Building"?"Adding":s} ${Cu(l)||"hook"} hook`}if(/^src\/lib\//.test(n)||/^src\/utils\//.test(n))return`${s==="Building"?"Adding":s} utilities`;if(/^src\/(App|main)\.(tsx|ts|jsx|js)$/i.test(n))return`${s==="Building"?"Wiring":s} app entry`;const o=i.replace(/\.(tsx|ts|jsx|js|html|css|md|json|yaml|yml)$/i,"");return`${s} ${Cu(o)||i}`}const CU=new Set(["ready","failed"]);function PU(e){if(e.phase==="ready"&&e.previewHealthy!==!1)return{kind:"ok"};if(e.phase==="failed"){const t=e.error||"Preview is not responding";return/recovery command was killed|preview isn't responding/i.test(t)?{kind:"retry"}:{kind:"failed",error:t}}return e.phase&&!CU.has(e.phase)?{kind:"retry"}:e.previewHealthy===!1?{kind:"retry"}:{kind:"retry"}}function nm(e){const t=e.phase||"",r=String(e.error||"");return!!(t==="dead"||t==="vite_dead"||t==="sandbox_missing"||/recovery command was killed|preview isn't responding|timeout\/latency/i.test(r)||/sandbox unreachable|sandbox not found|sandbox was reaped|\breaped\b/i.test(r))}function o3(e){const t=e.phase||"";return new Set(["installing","starting_vite","compiling","creating"]).has(t)?!1:!!(t==="sandbox_missing"||/sandbox unreachable|sandbox (?:not found|wasn'?t found|was not found|no longer exists|was reaped)|no longer exists|NotFoundError/i.test(err)||nm(e)||t==="failed"&&e.previewHealthy===!1||t==="ready"&&e.previewHealthy===!1)}function AU(e){if(e.skippedHandoff||e.buildCancelled||e.repairHandoff)return{notify:!1,success:!1,message:null};if(e.buildGeneration!==e.activeBuildGeneration)return{notify:!1,success:!1,message:null};const t=e.previewError!==null&&!/recovery command was killed|preview isn't responding/i.test(e.previewError||""),r=!e.featureComplete,n=e.autoStubCount>0,s=e.depCheckErrorCount>0&&t;if(r&&!e.planHasError&&!t&&!s&&!n)return{notify:!1,success:!1,message:"no substantive files were generated."};if(!(e.planHasError||t||r||s||n))return{notify:!0,success:!0,message:null};let o=null;return t?o=e.previewError:n?o=`${e.autoStubCount} placeholder file(s) still need real content.`:s?o=`${e.depCheckErrorCount} dependency/route issue(s) remain.`:r?o="no substantive files were generated.":o="finished with errors.",{notify:!0,success:!1,message:o}}function a1(){const[e,t]=m.useState(!1),[r,n]=m.useState(null);return{provision:m.useCallback(async(i,o,l,c)=>{var u;if(!l)return{success:!1,error:"Region required — show RegionPickerDialog before calling provision()."};t(!0),n(null);try{const p=((u=(await G.auth.getSession()).data.session)==null?void 0:u.access_token)||"",h=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/provision-supabase",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"},body:JSON.stringify({projectId:i,projectName:o,region:l,...c?{cloudProvider:c}:{}})});let f;try{f=await h.json()}
5166catch{const y={success:!1,error:`Invalid server response (HTTP ${h.status}). Please try again.`};return n(y),y}if(!h.ok){if(h.status===412&&(f==null?void 0:f.error)==="supabase_not_connected"){const y={success:!1,needs_connect:!0,error:f.message||"Connect your Supabase account to continue."};return n(y),y}if(h.status===300&&(f==null?void 0:f.error)==="multiple_orgs"){const y={success:!1,error:f.message||"Pick a Supabase organization.",org_choices:f.orgs};return n(y),y}const g={success:!1,error:(f==null?void 0:f.error)||`Provisioning failed (HTTP ${h.status})`,code:(f==null?void 0:f.code)||(f==null?void 0:f.error),message:f==null?void 0:f.message,billing_url:f==null?void 0:f.billing_url,dashboard_url:f==null?void 0:f.dashboard_url};return n(g),g}const x={success:!0,supabase_project_id:f.supabase_project_id,supabase_url:f.supabase_url,region:f.region,anon_key:f.anon_key,has_service_key:f.has_service_key,status:f.status};return n(x),x}catch(d){const p={success:!1,error:d.message||"Network error"};return n(p),p}finally{t(!1)}},[]),provisioning:e,provisionResult:r}}function _U(){const[e,t]=m.useState(!1),r=m.useRef(null),n=m.useCallback(()=>new Promise(o=>{r.current=o,t(!0)}),[]),s=m.useCallback(o=>{var l;(l=r.current)==null||l.call(r,o),r.current=null,t(!1)},[]),i=m.useCallback(()=>{var o;(o=r.current)==null||o.call(r,null),r.current=null,t(!1)},[]);return{askForRegion:n,regionPickerProps:{open:e,onClose:i,onConfirm:s}}}const Ty=[{value:"us-east-1",label:"US East (Virginia)",flag:"🇺🇸",hint:"Lowest latency for US East coast users"},{value:"us-west-1",label:"US West (N. California)",flag:"🇺🇸",hint:"Lowest latency for US West coast users"},{value:"eu-west-1",label:"EU West (Ireland)",flag:"🇮🇪",hint:"GDPR-friendly, EU data residency"},{value:"eu-central-1",label:"EU Central (Frankfurt)",flag:"🇩🇪",hint:"GDPR-friendly, fastest in central EU"},{value:"ap-southeast-1",label:"Asia Pacific (Singapore)",flag:"🇸🇬",hint:"Best for SE Asia / India"},{value:"ap-northeast-1",label:"Asia Pacific (Tokyo)",flag:"🇯🇵",hint:"Best for Japan / Korea"},{value:"ap-south-1",label:"Asia Pacific (Mumbai)",flag:"🇮🇳",hint:"Lowest latency in India"},{value:"sa-east-1",label:"South America (São Paulo)",flag:"🇧🇷",hint:"Lowest latency in South America"}];function i1({open:e,onClose:t,onConfirm:r,defaultRegion:n="us-east-1"}){var o,l;const[s,i]=m.useState(n);return a.jsx(yo,{open:e,onOpenChange:c=>!c&&t(),children:a.jsxs(Fi,{className:"sm:max-w-lg max-h-[85vh] overflow-y-auto",children:[a.jsxs(Bi,{children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center mb-2",children:a.jsx(Br,{className:"w-5 h-5 text-primary"})}),a.jsx(La,{children:"Choose your database region"}),a.jsxs(ol,{children:["Studio Jungle is about to provision a Supabase project for your app. Pick the region closest to your users — ",a.jsx("strong",{children:"this can't be changed later"}),"."]})]}),a.jsx("div",{className:"grid grid-cols-1 gap-1.5 my-2",children:Ty.map(c=>a.jsxs("button",{onClick:()=>i(c.value),className:L("flex items-center gap-3 px-3 py-2.5 rounded-lg border text-left transition-all",s===c.value?"border-primary bg-primary/5 ring-1 ring-primary/30":"border-border hover:bg-secondary/50"),children:[a.jsx("span",{className:"text-xl",children:c.flag}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium",children:c.label}),c.hint&&a.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:c.hint})]}),s===c.value&&a.jsx("div",{className:"w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:a.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-white"})})]},c.value))}),a.jsx("p",{className:"text-[11px] text-muted-foreground/80 italic",children:"Tip: Pick the region closest to where your users will be. Cross-region requests add 100-300ms of latency per call."}),a.jsxs(Ch,{className:"gap-2 sm:gap-2",children:[a.jsx(Q,{variant:"outline",onClick:t,size:"sm",children:"Cancel"}),a.jsxs(Q,{onClick:()=>r(s),size:"sm",className:"gap-1.5",children:[a.jsx(ya,{className:"w-3.5 h-3.5"}),"Provision in ",(o=Ty.find(c=>c.value===s))==null?void 0:o.flag," ",(l=Ty.find(c=>c.value===s))==null?void 0:l.label.split(" (")[0]]})]})]})})}function dS(e,t,r){const n=[],i=!!(t.url&&t.anonKey)?`import { createClient } from '@supabase/supabase-js';
5167
5168const supabaseUrl = '${t.url}';
5169const supabaseAnonKey = '${t.anonKey}';
5170
5171export const authClient = createClient(supabaseUrl, supabaseAnonKey, {
5172  auth: {
5173    storage: localStorage,
5174    persistSession: ${e.persistSession},
5175    autoRefreshToken: true,
5176  },
5177});`:`import { createClient } from '@supabase/supabase-js';
5178
5179const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
5180const supabaseAnonKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;
5181
5182export const authClient = createClient(supabaseUrl, supabaseAnonKey, {
5183  auth: {
5184    storage: localStorage,
5185    persistSession: ${e.persistSession},
5186    autoRefreshToken: true,
5187  },
5188});`;n.push({path:"src/lib/auth-client.ts",name:"auth-client.ts",content:i,language:"typescript"});const l=`import React, { createContext, useContext, useState, useEffect } from 'react';
5189import { authClient } from '../lib/auth-client';
5190
5191// Project-scoped email namespacing to isolate users per project
5192const PROJECT_SCOPE = '${r?r.substring(0,12):""}';
5193
5194function scopeEmail(email: string): string {
5195  if (!PROJECT_SCOPE) return email;
5196  const [local, domain] = email.split('@');
5197  return \`\${local}+p\${PROJECT_SCOPE}@\${domain}\`;
5198}
5199
5200function unscopeEmail(email: string): string {
5201  if (!PROJECT_SCOPE) return email;
5202  return email.replace(\`+p\${PROJECT_SCOPE}\`, '');
5203}
5204
5205interface User {
5206  id: string;
5207  email: string;
5208  displayName?: string;
5209}
5210
5211interface AuthContextType {
5212  user: User | null;
5213  loading: boolean;
5214  signIn: (email: string, password: string) => Promise<{ error?: string }>;
5215  signUp: (email: string, password: string, displayName?: string) => Promise<{ error?: string }>;
5216  signOut: () => Promise<void>;
5217  resetPassword: (email: string) => Promise<{ error?: string }>;
5218}
5219
5220const AuthContext = createContext<AuthContextType | null>(null);
5221
5222export function useAuth() {
5223  const ctx = useContext(AuthContext);
5224  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
5225  return ctx;
5226}
5227
5228export function AuthProvider({ children }: { children: React.ReactNode }) {
5229  const [user, setUser] = useState<User | null>(null);
5230  const [loading, setLoading] = useState(true);
5231
5232  useEffect(() => {
5233    // Listen for auth state changes
5234    const { data: { subscription } } = authClient.auth.onAuthStateChange(
5235      (_event, session) => {
5236        if (session?.user) {
5237          setUser({
5238            id: session.user.id,
5239            email: unscopeEmail(session.user.email || ''),
5240            displayName: session.user.user_metadata?.display_name,
5241          });
5242        } else {
5243          setUser(null);
5244        }
5245        setLoading(false);
5246      }
5247    );
5248
5249    // Check existing session
5250    authClient.auth.getSession().then(({ data: { session } }) => {
5251      if (session?.user) {
5252        setUser({
5253          id: session.user.id,
5254          email: unscopeEmail(session.user.email || ''),
5255          displayName: session.user.user_metadata?.display_name,
5256        });
5257      }
5258      setLoading(false);
5259    });
5260
5261    return () => subscription.unsubscribe();
5262  }, []);
5263
5264  const signIn = async (email: string, password: string) => {
5265    const { error } = await authClient.auth.signInWithPassword({ email: scopeEmail(email), password });
5266    return { error: error?.message };
5267  };
5268
5269  const signUp = async (email: string, password: string, displayName?: string) => {
5270    const { error } = await authClient.auth.signUp({
5271      email: scopeEmail(email),
5272      password,
5273      options: {
5274        data: { display_name: displayName, original_email: email },
5275        emailRedirectTo: window.location.origin,
5276      },
5277    });
5278    return { error: error?.message };
5279  };
5280
5281  const signOut = async () => {
5282    await authClient.auth.signOut();
5283    setUser(null);
5284  };
5285
5286  const resetPassword = async (email: string) => {
5287    const { error } = await authClient.auth.resetPasswordForEmail(scopeEmail(email), {
5288      redirectTo: \`\${window.location.origin}/reset-password\`,
5289    });
5290    return { error: error?.message };
5291  };
5292
5293  return (
5294    <AuthContext.Provider value={{ user, loading, signIn, signUp, signOut, resetPassword }}>
5295      {children}
5296    </AuthContext.Provider>
5297  );
5298}`;if(n.push({path:"src/contexts/AppAuthContext.tsx",name:"AppAuthContext.tsx",content:l,language:"tsx"}),e.loginPage){const u=`import React, { useState } from 'react';
5299import { useAuth } from '../contexts/AppAuthContext';
5300
5301export function LoginPage({ onSwitchToSignup, onForgotPassword }: { 
5302  onSwitchToSignup?: () => void;
5303  onForgotPassword?: () => void;
5304}) {
5305  const { signIn } = useAuth();
5306  const [email, setEmail] = useState('');
5307  const [password, setPassword] = useState('');
5308  const [error, setError] = useState('');
5309  const [loading, setLoading] = useState(false);
5310
5311  const handleSubmit = async (e: React.FormEvent) => {
5312    e.preventDefault();
5313    setError('');
5314    setLoading(true);
5315    const result = await signIn(email, password);
5316    if (result.error) setError(result.error);
5317    setLoading(false);
5318  };
5319
5320  return (
5321    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5322      <div style={{ width: '100%', maxWidth: 400, padding: 32, background: 'white', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
5323        <h1 style={{ fontSize: 24, fontWeight: 700, textAlign: 'center', marginBottom: 8 }}>Welcome Back</h1>
5324        <p style={{ fontSize: 14, color: '#64748b', textAlign: 'center', marginBottom: 24 }}>Sign in to your account</p>
5325        
5326        <form onSubmit={handleSubmit}>
5327          <div style={{ marginBottom: 16 }}>
5328            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>Email</label>
5329            <input type="email" value={email} onChange={e => setEmail(e.target.value)} required
5330              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5331          </div>
5332          <div style={{ marginBottom: 8 }}>
5333            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>Password</label>
5334            <input type="password" value={password} onChange={e => setPassword(e.target.value)} required
5335              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5336          </div>
5337          ${e.resetPassword?`{onForgotPassword && (
5338            <button type="button" onClick={onForgotPassword} style={{ fontSize: 12, color: '#6366f1', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 16, display: 'block' }}>
5339              Forgot password?
5340            </button>
5341          )}`:""}
5342          {error && <p style={{ fontSize: 12, color: '#ef4444', marginBottom: 12 }}>{error}</p>}
5343          <button type="submit" disabled={loading}
5344            style={{ width: '100%', padding: '10px', background: '#6366f1', color: 'white', border: 'none', borderRadius: 6, fontSize: 14, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}>
5345            {loading ? 'Signing in...' : 'Sign In'}
5346          </button>
5347        </form>
5348        
5349        {onSwitchToSignup && (
5350          <p style={{ fontSize: 12, textAlign: 'center', marginTop: 16, color: '#64748b' }}>
5351            Don't have an account? <button onClick={onSwitchToSignup} style={{ color: '#6366f1', background: 'none', border: 'none', cursor: 'pointer', fontWeight: 500 }}>Sign up</button>
5352          </p>
5353        )}
5354      </div>
5355    </div>
5356  );
5357}`;n.push({path:"src/pages/LoginPage.tsx",name:"LoginPage.tsx",content:u,language:"tsx"})}return e.signupPage&&n.push({path:"src/pages/SignupPage.tsx",name:"SignupPage.tsx",content:`import React, { useState } from 'react';
5358import { useAuth } from '../contexts/AppAuthContext';
5359
5360export function SignupPage({ onSwitchToLogin }: { onSwitchToLogin?: () => void }) {
5361  const { signUp } = useAuth();
5362  const [name, setName] = useState('');
5363  const [email, setEmail] = useState('');
5364  const [password, setPassword] = useState('');
5365  const [error, setError] = useState('');
5366  const [loading, setLoading] = useState(false);
5367  const [success, setSuccess] = useState(false);
5368
5369  const handleSubmit = async (e: React.FormEvent) => {
5370    e.preventDefault();
5371    setError('');
5372    if (password.length < 6) { setError('Password must be at least 6 characters'); return; }
5373    setLoading(true);
5374    const result = await signUp(email, password, name);
5375    if (result.error) { setError(result.error); }
5376    else { setSuccess(true); }
5377    setLoading(false);
5378  };
5379
5380  if (success) {
5381    return (
5382      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5383        <div style={{ width: '100%', maxWidth: 400, padding: 32, background: 'white', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.1)', textAlign: 'center' }}>
5384          <h2 style={{ fontSize: 20, fontWeight: 700, marginBottom: 8 }}>Check your email</h2>
5385          <p style={{ fontSize: 14, color: '#64748b' }}>We sent a confirmation link to <strong>{email}</strong></p>
5386        </div>
5387      </div>
5388    );
5389  }
5390
5391  return (
5392    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5393      <div style={{ width: '100%', maxWidth: 400, padding: 32, background: 'white', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
5394        <h1 style={{ fontSize: 24, fontWeight: 700, textAlign: 'center', marginBottom: 8 }}>Create Account</h1>
5395        <p style={{ fontSize: 14, color: '#64748b', textAlign: 'center', marginBottom: 24 }}>Get started for free</p>
5396        
5397        <form onSubmit={handleSubmit}>
5398          <div style={{ marginBottom: 16 }}>
5399            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>Display Name</label>
5400            <input type="text" value={name} onChange={e => setName(e.target.value)}
5401              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5402          </div>
5403          <div style={{ marginBottom: 16 }}>
5404            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>Email</label>
5405            <input type="email" value={email} onChange={e => setEmail(e.target.value)} required
5406              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5407          </div>
5408          <div style={{ marginBottom: 16 }}>
5409            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>Password</label>
5410            <input type="password" value={password} onChange={e => setPassword(e.target.value)} required
5411              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5412          </div>
5413          {error && <p style={{ fontSize: 12, color: '#ef4444', marginBottom: 12 }}>{error}</p>}
5414          <button type="submit" disabled={loading}
5415            style={{ width: '100%', padding: '10px', background: '#6366f1', color: 'white', border: 'none', borderRadius: 6, fontSize: 14, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}>
5416            {loading ? 'Creating account...' : 'Sign Up'}
5417          </button>
5418        </form>
5419        
5420        {onSwitchToLogin && (
5421          <p style={{ fontSize: 12, textAlign: 'center', marginTop: 16, color: '#64748b' }}>
5422            Already have an account? <button onClick={onSwitchToLogin} style={{ color: '#6366f1', background: 'none', border: 'none', cursor: 'pointer', fontWeight: 500 }}>Sign in</button>
5423          </p>
5424        )}
5425      </div>
5426    </div>
5427  );
5428}`,language:"tsx"}),e.resetPassword&&n.push({path:"src/pages/ResetPasswordPage.tsx",name:"ResetPasswordPage.tsx",content:`import React, { useState, useEffect } from 'react';
5429import { authClient } from '../lib/auth-client';
5430
5431export function ResetPasswordPage() {
5432  const [password, setPassword] = useState('');
5433  const [confirmPassword, setConfirmPassword] = useState('');
5434  const [error, setError] = useState('');
5435  const [success, setSuccess] = useState(false);
5436  const [loading, setLoading] = useState(false);
5437  const [isRecovery, setIsRecovery] = useState(false);
5438
5439  useEffect(() => {
5440    // Check if this is a recovery flow
5441    const hash = window.location.hash;
5442    if (hash.includes('type=recovery')) {
5443      setIsRecovery(true);
5444    }
5445  }, []);
5446
5447  const handleSubmit = async (e: React.FormEvent) => {
5448    e.preventDefault();
5449    setError('');
5450    if (password !== confirmPassword) { setError('Passwords do not match'); return; }
5451    if (password.length < 6) { setError('Password must be at least 6 characters'); return; }
5452    setLoading(true);
5453    const { error } = await authClient.auth.updateUser({ password });
5454    if (error) { setError(error.message); }
5455    else { setSuccess(true); }
5456    setLoading(false);
5457  };
5458
5459  if (!isRecovery) {
5460    return (
5461      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5462        <div style={{ padding: 32, textAlign: 'center' }}>
5463          <p style={{ color: '#64748b' }}>Invalid or expired reset link.</p>
5464        </div>
5465      </div>
5466    );
5467  }
5468
5469  if (success) {
5470    return (
5471      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5472        <div style={{ width: '100%', maxWidth: 400, padding: 32, background: 'white', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.1)', textAlign: 'center' }}>
5473          <h2 style={{ fontSize: 20, fontWeight: 700, marginBottom: 8, color: '#10b981' }}>Password Updated!</h2>
5474          <p style={{ fontSize: 14, color: '#64748b' }}>Your password has been reset successfully. You can now sign in with your new password.</p>
5475        </div>
5476      </div>
5477    );
5478  }
5479
5480  return (
5481    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5482      <div style={{ width: '100%', maxWidth: 400, padding: 32, background: 'white', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }}>
5483        <h1 style={{ fontSize: 24, fontWeight: 700, textAlign: 'center', marginBottom: 8 }}>Reset Password</h1>
5484        <p style={{ fontSize: 14, color: '#64748b', textAlign: 'center', marginBottom: 24 }}>Enter your new password</p>
5485        
5486        <form onSubmit={handleSubmit}>
5487          <div style={{ marginBottom: 16 }}>
5488            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>New Password</label>
5489            <input type="password" value={password} onChange={e => setPassword(e.target.value)} required
5490              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5491          </div>
5492          <div style={{ marginBottom: 16 }}>
5493            <label style={{ fontSize: 12, fontWeight: 500, display: 'block', marginBottom: 4 }}>Confirm Password</label>
5494            <input type="password" value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)} required
5495              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 14, outline: 'none' }} />
5496          </div>
5497          {error && <p style={{ fontSize: 12, color: '#ef4444', marginBottom: 12 }}>{error}</p>}
5498          <button type="submit" disabled={loading}
5499            style={{ width: '100%', padding: '10px', background: '#6366f1', color: 'white', border: 'none', borderRadius: 6, fontSize: 14, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}>
5500            {loading ? 'Updating...' : 'Update Password'}
5501          </button>
5502        </form>
5503      </div>
5504    </div>
5505  );
5506}`,language:"tsx"}),e.authGuard&&n.push({path:"src/components/ProtectedRoute.tsx",name:"ProtectedRoute.tsx",content:`import React from 'react';
5507import { useAuth } from '../contexts/AppAuthContext';
5508
5509/**
5510 * Wrap any component with ProtectedRoute to require authentication.
5511 * Usage: <ProtectedRoute><Dashboard /></ProtectedRoute>
5512 * Or:    <ProtectedRoute fallback={<LoginPage />}><Dashboard /></ProtectedRoute>
5513 */
5514export function ProtectedRoute({ children, fallback }: { 
5515  children: React.ReactNode;
5516  fallback?: React.ReactNode;
5517}) {
5518  const { user, loading } = useAuth();
5519
5520  if (loading) {
5521    return (
5522      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
5523        <div style={{ width: 24, height: 24, border: '3px solid #e2e8f0', borderTopColor: '#6366f1', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
5524        <style>{\`@keyframes spin { to { transform: rotate(360deg); } }\`}</style>
5525      </div>
5526    );
5527  }
5528
5529  if (!user) {
5530    return fallback || (
5531      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc' }}>
5532        <div style={{ textAlign: 'center', padding: 32 }}>
5533          <h2 style={{ fontSize: 20, fontWeight: 700, marginBottom: 8 }}>Authentication Required</h2>
5534          <p style={{ fontSize: 14, color: '#64748b' }}>Please sign in to access this page.</p>
5535        </div>
5536      </div>
5537    );
5538  }
5539
5540  return <>{children}</>;
5541}`,language:"tsx"}),n.push({path:"src/auth-setup-guide.ts",name:"auth-setup-guide.ts",content:`/*
5542 * AUTH SETUP - Add this to your App.tsx
5543 * 
5544 * 1. Wrap your app with AuthProvider:
5545 * 
5546 *    import { AuthProvider } from './contexts/AppAuthContext';
5547 *    
5548 *    function App() {
5549 *      return (
5550 *        <AuthProvider>
5551 *          <Router>...</Router>
5552 *        </AuthProvider>
5553 *      );
5554 *    }
5555 *
5556 * 2. Protect routes that need auth:
5557 *
5558 *    import { ProtectedRoute } from './components/ProtectedRoute';
5559 *    import { LoginPage } from './pages/LoginPage';
5560 *    
5561 *    <Route path="/dashboard" element={
5562 *      <ProtectedRoute fallback={<LoginPage />}>
5563 *        <Dashboard />
5564 *      </ProtectedRoute>
5565 *    } />
5566 *
5567 * 3. Use auth in components:
5568 *
5569 *    import { useAuth } from './contexts/AppAuthContext';
5570 *    
5571 *    function Navbar() {
5572 *      const { user, signOut } = useAuth();
5573 *      return user ? <button onClick={signOut}>Logout</button> : <Link to="/login">Login</Link>;
5574 *    }
5575 *
5576 * 4. Public routes (no auth needed):
5577 *    - Landing page
5578 *    - Login / Signup pages
5579 *    - Reset password page
5580 *    - About / Contact / Pricing
5581 *
5582 * 5. Protected routes (auth required):
5583 *    - Dashboard
5584 *    - Profile / Settings
5585 *    - Any CRUD pages
5586 *    - Admin panels
5587 */
5588export {};`,language:"typescript"}),n}function l3({open:e,onOpenChange:t,autoGenerate:r=!1,onGenerated:n}){const{project:s}=gn(),i=(s==null?void 0:s.id)||null,[o,l]=m.useState({}),[c,u]=m.useState(!1),[d,p]=m.useState(!1),[h,f]=m.useState({loginPage:!0,signupPage:!0,resetPassword:!0,protectedRoutes:!0,authGuard:!0,persistSession:!0});m.useEffect(()=>{i&&e&&G.from("projects").select("custom_supabase_url, custom_supabase_anon_key").eq("id",i).single().then(({data:T})=>{T&&l({url:T.custom_supabase_url,anonKey:T.custom_supabase_anon_key})})},[i,e]);const x=!!(o.url&&o.anonKey),{provision:g}=a1(),{askForRegion:y,regionPickerProps:b}=_U(),[v,k]=m.useState(!1),N=m.useCallback(async()=>{if(i){k(!0);try{const{data:T}=await G.from("project_cloud_config").select("region").eq("project_id",i).maybeSingle();let C=(T==null?void 0:T.region)||"";if(!C&&(C=await y()||"",!C))return;const A=await g(i,(s==null?void 0:s.name)||"app",C,"managed");if(!A.success||!A.supabase_url||!A.anon_key){A.code==="supabase_free_tier_limit"?W.error(A.message||"Studio Jungle’s managed org hit the Supabase free-tier limit (2 projects).",{duration:12e3,action:A.billing_url?{label:"Upgrade to Pro",onClick:()=>window.open(A.billing_url,"_blank")}:void 0}):W.error(`Managed database setup failed: ${A.message||A.error||"unknown error"}`);return}await G.from("projects").update({custom_supabase_url:A.supabase_url,custom_supabase_anon_key:A.anon_key}).eq("id",i),await G.from("project_cloud_config").update({cloud_provider:"managed",backend_mode:"studiojungle"}).eq("project_id",i),l({url:A.supabase_url,anonKey:A.anon_key}),W.success("Dedicated managed database provisioned — auth will use it.")}catch(T){W.error(`Managed database setup failed: ${T.message}`)}finally{k(!1)}}},[i,s==null?void 0:s.name,g]),j=m.useCallback(async()=>{if(i){u(!0);try{const T=dS(h,o,i);for(const C of T)await G.from("project_files").delete().eq("project_id",i).eq("path",C.path),await G.from("project_files").insert({project_id:i,name:C.name,path:C.path,content:C.content,language:C.language});p(!0),n==null||n(),W.success(`Auth scaffold created — ${T.length} files generated!`)}catch(T){W.error(`Failed to generate: ${T.message}`)}finally{u(!1)}}},[i,h,o,n]);m.useEffect(()=>{!e||!r||d||c||j()},[e,r,d,c,j]);const w=[{key:"loginPage",label:"Login Page",icon:y$,desc:"Email/password sign in form"},{key:"signupPage",label:"Signup Page",icon:tT,desc:"Registration with email confirmation"},{key:"resetPassword",label:"Password Reset",icon:Ri,desc:"Forgot password + reset flow"},{key:"authGuard",label:"Protected Routes",icon:Bs,desc:"Auth guard component for private pages"},{key:"persistSession",label:"Persist Session",icon:Ep,desc:"Remember login across browser sessions"}],S=dS(h,o,i).length;return a.jsxs(a.Fragment,{children:[a.jsx(yo,{open:e,onOpenChange:t,children:a.jsxs(Fi,{className:"max-w-lg",children:[a.jsx(Bi,{children:a.jsxs(La,{className:"flex items-center gap-2",children:[a.jsx(os,{className:"w-5 h-5 text-primary"}),"Add Authentication"]})}),a.jsx($r,{className:"max-h-[60vh]",children:a.jsxs("div",{className:"space-y-4 pr-2",children:[a.jsxs("div",{className:L("p-3 rounded-lg border text-xs space-y-1",x?"bg-primary/5 border-primary/20":"bg-muted border-border"),children:[a.jsx("div",{className:"flex items-center gap-2",children:x?a.jsxs(a.Fragment,{children:[a.jsx(Wn,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"font-semibold text-primary",children:"Connected to BYOS"})]}):a.jsxs(a.Fragment,{children:[a.jsx(no,{className:"w-4 h-4 text-muted-foreground"}),a.jsx("span",{className:"font-medium text-muted-foreground",children:"Using Managed DB"})]})}),a.jsx("p",{className:"text-muted-foreground",children:x?`Auth will use your Supabase instance (${new URL(o.url).hostname.split(".")[0]}). Users will be stored in your Supabase Auth.`:"Real per-project auth needs a dedicated database. Set up a Studio Jungle managed one (no Supabase account needed), or connect your own via BYOS."}),!x&&a.jsx("button",{type:"button",onClick:N,disabled:v,className:"mt-2 inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[11px] font-semibold bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-60",children:v?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"})," Provisioning dedicated database…"]}):a.jsxs(a.Fragment,{children:[a.jsx(os,{className:"w-3 h-3"})," Set up dedicated managed database (+$10/mo)"]})})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Auth Features"}),w.map(T=>a.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[a.jsx(Xl,{checked:h[T.key],onCheckedChange:C=>f({...h,[T.key]:C}),className:"mt-0.5 scale-[0.85]"}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(T.icon,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-xs font-medium text-foreground",children:T.label})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:T.desc})]})]},T.key))]}),a.jsxs("div",{className:"p-3 bg-secondary/30 rounded-lg space-y-1.5",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Files to Generate"}),a.jsxs("div",{className:"space-y-1",children:[a.jsx(Sl,{name:"src/lib/auth-client.ts",desc:"Supabase auth client setup"}),a.jsx(Sl,{name:"src/contexts/AppAuthContext.tsx",desc:"Auth provider + hooks"}),h.loginPage&&a.jsx(Sl,{name:"src/pages/LoginPage.tsx",desc:"Login form"}),h.signupPage&&a.jsx(Sl,{name:"src/pages/SignupPage.tsx",desc:"Registration form"}),h.resetPassword&&a.jsx(Sl,{name:"src/pages/ResetPasswordPage.tsx",desc:"Password reset"}),h.authGuard&&a.jsx(Sl,{name:"src/components/ProtectedRoute.tsx",desc:"Auth guard"}),a.jsx(Sl,{name:"src/auth-setup-guide.ts",desc:"Integration guide"})]})]}),d&&a.jsxs("div",{className:"p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Wn,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs font-semibold text-primary",children:"Auth files generated!"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Check the Files tab to see all generated auth code. Follow the setup guide in auth-setup-guide.ts."})]})]})}),a.jsxs(Ch,{children:[a.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),a.jsx(Q,{size:"sm",onClick:j,disabled:c||!h.loginPage&&!h.signupPage,className:"gap-1.5",children:c?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"})," Generating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(os,{className:"w-3.5 h-3.5"})," Generate ",S," Files"]})})]})]})}),a.jsx(i1,{...b})]})}function Sl({name:e,desc:t}){return a.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[a.jsx(Ge,{variant:"secondary",className:"text-[9px] px-1.5 py-0 font-mono",children:".tsx"}
vendor: 4,517 bytes, line 5588
5588),a.jsx("span",{className:"font-mono text-foreground/80 flex-1 truncate",children:e}),a.jsx("span",{className:"text-muted-foreground",children:t})]})}function TU(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const EU=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,IU=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,OU={};function pS(e,t){return(OU.jsx?IU:EU).test(e)}const RU=/[ \t\n\f\r]/g;function DU(e){return typeof e=="object"?e.type==="text"?hS(e.value):!1:hS(e)}function hS(e){return e.replace(RU,"")===""}class _h{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}_h.prototype.normal={};_h.prototype.property={};_h.prototype.space=void 0;function c3(e,t){const r={},n={};for(const s of e)Object.assign(r,s.property),Object.assign(n,s.normal);return new _h(r,n,t)}function u0(e){return e.toLowerCase()}class la{constructor(t,r){this.attribute=r,this.property=t}}la.prototype.attribute="";la.prototype.booleanish=!1;la.prototype.boolean=!1;la.prototype.commaOrSpaceSeparated=!1;la.prototype.commaSeparated=!1;la.prototype.defined=!1;la.prototype.mustUseProperty=!1;la.prototype.number=!1;la.prototype.overloadedBoolean=!1;la.prototype.property="";la.prototype.spaceSeparated=!1;la.prototype.space=void 0;let MU=0;const bn=kc(),ss=kc(),d0=kc(),Re=kc(),kr=kc(),mu=kc(),da=kc();function kc(){return 2**++MU}const p0=Object.freeze(Object.defineProperty({__proto__:null,boolean:bn,booleanish:ss,commaOrSpaceSeparated:da,commaSeparated:mu,number:Re,overloadedBoolean:d0,spaceSeparated:kr},Symbol.toStringTag,{value:"Module"})),Ey=Object.keys(p0);class o1 extends la{constructor(t,r,n,s){let i=-1;if(super(t,r),fS(this,"space",s),typeof n=="number")for(;++i<Ey.length;){const o=Ey[i];fS(this,Ey[i],(n&p0[o])===p0[o])}}}o1.prototype.defined=!0;function fS(e,t,r){r&&(e[t]=r)}function cd(e){const t={},r={};for(const[n,s]of Object.entries(e.properties)){const i=new o1(n,e.transform(e.attributes||{},n),s,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[u0(n)]=n,r[u0(i.attribute)]=n}return new _h(t,r,e.space)}const u3=cd({properties:{ariaActiveDescendant:null,ariaAtomic:ss,ariaAutoComplete:null,ariaBusy:ss,ariaChecked:ss,ariaColCount:Re,ariaColIndex:Re,ariaColSpan:Re,ariaControls:kr,ariaCurrent:null,ariaDescribedBy:kr,ariaDetails:null,ariaDisabled:ss,ariaDropEffect:kr,ariaErrorMessage:null,ariaExpanded:ss,ariaFlowTo:kr,ariaGrabbed:ss,ariaHasPopup:null,ariaHidden:ss,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:kr,ariaLevel:Re,ariaLive:null,ariaModal:ss,ariaMultiLine:ss,ariaMultiSelectable:ss,ariaOrientation:null,ariaOwns:kr,ariaPlaceholder:null,ariaPosInSet:Re,ariaPressed:ss,ariaReadOnly:ss,ariaRelevant:null,ariaRequired:ss,ariaRoleDescription:kr,ariaRowCount:Re,ariaRowIndex:Re,ariaRowSpan:Re,ariaSelected:ss,ariaSetSize:Re,ariaSort:null,ariaValueMax:Re,ariaValueMin:Re,ariaValueNow:Re,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function d3(e,t){return t in e?e[t]:t}function p3(e,t){return d3(e,t.toLowerCase())}const LU=cd({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:mu,acceptCharset:kr,accessKey:kr,action:null,allow:null,allowFullScreen:bn,allowPaymentRequest:bn,allowUserMedia:bn,alt:null,as:null,async:bn,autoCapitalize:null,autoComplete:kr,autoFocus:bn,autoPlay:bn,blocking:kr,capture:null,charSet:null,checked:bn,cite:null,className:kr,cols:Re,colSpan:null,content:null,contentEditable:ss,controls:bn,controlsList:kr,coords:Re|mu,crossOrigin:null,data:null,dateTime:null,decoding:null,default:bn,defer:bn,dir:null,dirName:null,disabled:bn,download:d0,draggable:ss,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:bn,formTarget:null,headers:kr,height:Re,hidden:d0,high:Re,href:null,hrefLang:null,htmlFor:kr,httpEquiv:kr,id:null,imageSizes:null,imageSrcSet:null,inert:bn,inputMode:null,integrity:null,is:null,isMap:bn,itemId:null,itemProp:kr,itemRef:kr,itemScope:bn,itemType:kr,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:bn,low:Re,manifest:null,max:null,maxLength:Re,media:null,method:null,min:null,minLength:Re,multiple:bn,muted:bn,name:null,nonce:null,noModule:bn,noValidate:bn,onAbort:null,onAfterPrint:null,onAuxCl
5588ick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:bn,optimum:Re,pattern:null,ping:kr,placeholder:null,playsInline:bn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:bn,referrerPolicy:null,rel:kr,required:bn,reversed:bn,rows:Re,rowSpan:Re,sandbox:kr,scope:null,scoped:bn,seamless:bn,selected:bn,shadowRootClonable:bn,shadowRootDelegatesFocus:bn,shadowRootMode:null,shape:null,size:Re,sizes:null,slot:null,span:Re,spellCheck:ss,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Re,step:null,style:null,tabIndex:Re,target:null,title:null,translate:null,type:null,typeMustMatch:bn,useMap:null,value:ss,width:Re,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:kr,axis:null,background:null,bgColor:null,border:Re,borderColor:null,bottomMargin:Re,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:bn,declare:bn,event:null,face:null,frame:null,frameBorder:null,hSpace:Re,leftMargin:Re,link:null,longDesc:null,lowSrc:null,marginHeight:Re,marginWidth:Re,noResize:bn,noHref:bn,noShade:bn,noWrap:bn,object:null,profile:null,prompt:null,rev:null,rightMargin:Re,rules:null,scheme:null,scrolling:ss,standby:null,summary:null,text:null,topMargin:Re,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Re,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:bn,disableRemotePlayback:bn,prefix:null,property:null,results:Re,security:null,unselectable:null},space:"html",transform:p3}),$U=cd({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav
5588-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:da,accentHeight:Re,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Re,amplitude:Re,arabicForm:null,ascent:Re,attributeName:null,attributeType:null,azimuth:Re,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Re,by:null,calcMode:null,capHeight:Re,className:kr,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Re,diffuseConstant:Re,direction:null,display:null,dur:null,divisor:Re,dominantBaseline:null,download:bn,dx:null,dy:null,edgeMode:null,editable:null,elevation:Re,enableBackground:null,end:null,event:null,exponent:Re,externalResourcesRequired:null,fill:null,fillOpacity:Re,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:mu,g2:mu,glyphName:mu,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Re,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Re,horizOriginX:Re,horizOriginY:Re,id:null,ideographic:Re,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Re,k:Re,k1:Re,k2:Re,k3:Re,k4:Re,kernelMatrix:da,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Re,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Re,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,on
vendor: 5,302 bytes, lines 5588-5589
5588Zoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Re,overlineThickness:Re,paintOrder:null,panose1:null,path:null,pathLength:Re,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:kr,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Re,pointsAtY:Re,pointsAtZ:Re,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:da,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:da,rev:da,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:da,requiredFeatures:da,requiredFonts:da,requiredFormats:da,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Re,specularExponent:Re,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Re,strikethroughThickness:Re,string:null,stroke:null,strokeDashArray:da,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Re,strokeOpacity:Re,strokeWidth:null,style:null,surfaceScale:Re,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:da,tabIndex:Re,tableValues:null,target:null,targetX:Re,targetY:Re,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:da,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Re,underlineThickness:Re,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Re,values:null,vAlphabetic:Re,vMathematical:Re,vectorEffect:null,vHanging:Re,vIdeographic:Re,version:null,vertAdvY:Re,vertOriginX:Re,vertOriginY:Re,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Re,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:d3}),h3=cd({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),f3=cd({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:p3}),m3=cd({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),FU={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},BU=/[A-Z]/g,mS=/-[a-z]/g,UU=/^data[-\w.:]+$/i;function zU(e,t){const r=u0(t);let n=t,s=la;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&UU.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(mS,HU);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!mS.test(i)){let o=i.replace(BU,qU);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}s=o1}return new s(n,t)}function qU(e){return"-"+e.toLowerCase()}function HU(e){return e.charAt(1).toUpperCase()}const WU=c3([u3,LU,h3,f3,m3],"html"),l1=c3([u3,$U,h3,f3,m3],"svg");function VU(e){return e.join(" ").trim()}var c1={},gS=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,GU=/\n/g,KU=/^\s*/,YU=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,JU=/^:\s*/,XU=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,ZU=/^[;\s]*/,QU=/^\s+|\s+$/g,ez=`
5589`,xS="/",yS="*",Ll="",tz="comment",nz="declaration";function rz(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var r=1,n=1;function s(x){var g=x.match(GU);g&&(r+=g.length);var y=x.lastIndexOf(ez);n=~y?x.length-y:n+x.length}function i(){var x={line:r,column:n};return function(g){return g.position=new o(x),u(),g}}function o(x){this.start=x,this.end={line:r,column:n},this.source=t.source}o.prototype.content=e;function l(x){var g=new Error(t.source+":"+r+":"+n+": "+x);if(g.reason=x,g.filename=t.source,g.line=r,g.column=n,g.source=e,!t.silent)throw g}function c(x){var g=x.exec(e);if(g){var y=g[0];return s(y),e=e.slice(y.length),g}}function u(){c(KU)}function d(x){var g;for(x=x||[];g=p();)g!==!1&&x.push(g);return x}function p(){var x=i();if(!(xS!=e.charAt(0)||yS!=e.charAt(1))){for(var g=2;Ll!=e.charAt(g)&&(yS!=e.charAt(g)||xS!=e.charAt(g+1));)++g;if(g+=2,Ll===e.charAt(g-1))return l("End of comment missing");var y=e.slice(2,g-2);return n+=2,s(y),e=e.slice(g),n+=2,x({type:tz,comment:y})}}function h(){var x=i(),g=c(YU);if(g){if(p(),!c(JU))return l("property missing ':'");var y=c(XU),b=x({type:nz,property:bS(g[0].replace(gS,Ll)),value:y?bS(y[0].replace(gS,Ll)):Ll});return c(ZU),b}}function f(){var x=[];d(x);for(var g;g=h();)g!==!1&&(x.push(g),d(x));return x}return u(),f()}function bS(e){return e?e.replace(QU,Ll):Ll}var sz=rz,az=gm&&gm.__importDefault||function(e){return e&&e.__esMo
vendor: 3,641 bytes, line 5589
5589dule?e:{default:e}};Object.defineProperty(c1,"__esModule",{value:!0});c1.default=oz;const iz=az(sz);function oz(e,t){let r=null;if(!e||typeof e!="string")return r;const n=(0,iz.default)(e),s=typeof t=="function";return n.forEach(i=>{if(i.type!=="declaration")return;const{property:o,value:l}=i;s?t(o,l,i):l&&(r=r||{},r[o]=l)}),r}var ix={};Object.defineProperty(ix,"__esModule",{value:!0});ix.camelCase=void 0;var lz=/^--[a-zA-Z0-9_-]+$/,cz=/-([a-z])/g,uz=/^[^-]+$/,dz=/^-(webkit|moz|ms|o|khtml)-/,pz=/^-(ms)-/,hz=function(e){return!e||uz.test(e)||lz.test(e)},fz=function(e,t){return t.toUpperCase()},vS=function(e,t){return"".concat(t,"-")},mz=function(e,t){return t===void 0&&(t={}),hz(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(pz,vS):e=e.replace(dz,vS),e.replace(cz,fz))};ix.camelCase=mz;var gz=gm&&gm.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},xz=gz(c1),yz=ix;function h0(e,t){var r={};return!e||typeof e!="string"||(0,xz.default)(e,function(n,s){n&&s&&(r[(0,yz.camelCase)(n,t)]=s)}),r}h0.default=h0;var bz=h0;const vz=zs(bz),g3=x3("end"),u1=x3("start");function x3(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function wz(e){const t=u1(e),r=g3(e);if(t&&r)return{start:t,end:r}}function xp(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?wS(e.position):"start"in e||"end"in e?wS(e):"line"in e||"column"in e?f0(e):""}function f0(e){return jS(e&&e.line)+":"+jS(e&&e.column)}function wS(e){return f0(e&&e.start)+"-"+f0(e&&e.end)}function jS(e){return e&&typeof e=="number"?e:1}class qs extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let s="",i={},o=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i={...r}),typeof t=="string"?s=t:!i.cause&&t&&(o=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const c=n.indexOf(":");c===-1?i.ruleId=n:(i.source=n.slice(0,c),i.ruleId=n.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const l=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=l?l.line:void 0,this.name=xp(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}qs.prototype.file="";qs.prototype.name="";qs.prototype.reason="";qs.prototype.message="";qs.prototype.stack="";qs.prototype.column=void 0;qs.prototype.line=void 0;qs.prototype.ancestors=void 0;qs.prototype.cause=void 0;qs.prototype.fatal=void 0;qs.prototype.place=void 0;qs.prototype.ruleId=void 0;qs.prototype.source=void 0;const d1={}.hasOwnProperty,jz=new Map,Nz=/[A-Z]/g,kz=new Set(["table","tbody","thead","tfoot","tr"]),Sz=new Set(["td","th"]),y3="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Cz(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=Rz(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");
vendor: 7,369 bytes, line 5589
5589if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=Oz(r,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?l1:WU,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=b3(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function b3(e,t,r){if(t.type==="element")return Pz(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Az(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Tz(e,t,r);if(t.type==="mdxjsEsm")return _z(e,t);if(t.type==="root")return Ez(e,t,r);if(t.type==="text")return Iz(e,t)}function Pz(e,t,r){const n=e.schema;let s=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(s=l1,e.schema=s),e.ancestors.push(t);const i=w3(e,t.tagName,!1),o=Dz(e,t);let l=h1(e,t);return kz.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!DU(c):!0})),v3(e,o,i,t),p1(o,l),e.ancestors.pop(),e.schema=n,e.create(t,i,o,r)}function Az(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}Lp(e,t.position)}function _z(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Lp(e,t.position)}function Tz(e,t,r){const n=e.schema;let s=n;t.name==="svg"&&n.space==="html"&&(s=l1,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:w3(e,t.name,!0),o=Mz(e,t),l=h1(e,t);return v3(e,o,i,t),p1(o,l),e.ancestors.pop(),e.schema=n,e.create(t,i,o,r)}function Ez(e,t,r){const n={};return p1(n,h1(e,t)),e.create(t,e.Fragment,n,r)}function Iz(e,t){return t.value}function v3(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function p1(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function Oz(e,t,r){return n;function n(s,i,o,l){const u=Array.isArray(o.children)?r:t;return l?u(i,o,l):u(i,o)}}function Rz(e,t){return r;function r(n,s,i,o){const l=Array.isArray(i.children),c=u1(n);return t(s,i,o,l,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function Dz(e,t){const r={};let n,s;for(s in t.properties)if(s!=="children"&&d1.call(t.properties,s)){const i=Lz(e,s,t.properties[s]);if(i){const[o,l]=i;e.tableCellAlignToStyle&&o==="align"&&typeof l=="string"&&Sz.has(t.tagName)?n=l:r[o]=l}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function Mz(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const o=i.expression;o.type;const l=o.properties[0];l.type,Object.assign(r,e.evaluater.evaluateExpression(l.argument))}else Lp(e,t.position);else{const s=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const l=n.value.data.estree.body[0];l.type,i=e.evaluater.evaluateExpression(l.expression)}else Lp(e,t.position);else i=n.value===null?!0:n.value;r[s]=i}return r}function h1(e,t){const r=[];let n=-1;const s=e.passKeys?new Map:jz;for(;++n<t.children.length;){const i=t.children[n];let o;if(e.passKeys){const c=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(c){const u=s.get(c)||0;o=c+"-"+u,s.set(c,u+1)}}const l=b3(e,i,o);l!==void 0&&r.push(l)}return r}function Lz(e,t,r){const n=zU(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?TU(r):VU(r)),n.property==="style"){let s=typeof r=="object"?r:$z(e,String(r));return e.stylePropertyNameCase==="css"&&(s=Fz(s)),["style",s]}return[e.elementAttributeNameCase==="react"&&n.space?FU[n.property]||n.property:n.attribute,r]}}function $z(e,t){try{return vz(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,s=new qs("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=y3+"#cannot-parse-style-attribute",s}}function w3(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const s=t.split(".");let i=-1,o;for(;++i<s.length;){const l=pS(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};o=o?{type:"MemberExpression",object:o,property:l,computed:!!(i&&l.type==="Literal"),optional:!1}:l}n=o}else n=pS(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const s=n.value;return d1.call(e.components,s)?e.components[s]:s}if(e.evaluater)return e.evaluater.evaluateExpression(n);Lp(e)}function Lp(e,t){const r=new qs("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=y3+"#cannot-handle-mdx-estrees-without-createevaluater",r}function Fz(e){const t={};let r;for(r in e)d1.call(e,r)&&(t[Bz(r)]=e[r]);return t}function Bz(e){let t=e.replace(Nz,Uz);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Uz(e){return"-"+e.toLowerCase()}const Iy={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},zz={};function f1(e,t){const r=zz,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,s=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return j3(e,n,s)}function j3(e,t,r){if(qz(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return NS(e.children,t,r)}return Array.isArray(e)?NS(e,t,r):""}function NS(e,t,r){const n=[];let s=-1;for(;++s<e.length;)n[s]=j3(e[s],t,r);return n.join("")}function qz(e){return!!(e&&typeof e=="object")}const kS=document.createElement("i");function m1(e){const t="&"+e+";";kS.innerHTML=t;const r=kS.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function va(e,t,r,n){const s=e.length;let i=0,o;if(t<0?t=-t>s?0:s+t:t=t>s?s:t,r=r>0?r:0,n.length<1e4)o=Array.from(n),o.unshift(t,r),e.splice(...o);else for(r&&e.splice(t,r);i<n.length;)o=n.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function Ia(e,t){return e.length>0?(va(e,e.length,0,t),e):t}const SS={}.hasOwnProperty;function N3(e){const t={};let r=-1;for(;++r<e.length;)Hz(t,e[r]);return t}function Hz(e,t){let r;for(r in t){const s=(SS.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let o;if(i)for(o in i){SS.call(s,o)||(s[o]=[]);const l=i[o];Wz(s[o],Array.isArray(l)?l:l?[l]:[])}}}function Wz(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);va(e,0,0,n)}function k3(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function oi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}
vendor: 9,813 bytes, line 5589
5589const Ys=ul(/[A-Za-z]/),Fs=ul(/[\dA-Za-z]/),Vz=ul(/[#-'*+\--9=?A-Z^-~]/);function Em(e){return e!==null&&(e<32||e===127)}const m0=ul(/\d/),Gz=ul(/[\dA-Fa-f]/),Kz=ul(/[!-/:-@[-`{-~]/);function Lt(e){return e!==null&&e<-2}function br(e){return e!==null&&(e<0||e===32)}function _n(e){return e===-2||e===-1||e===32}const ox=ul(new RegExp("\\p{P}|\\p{S}","u")),mc=ul(/\s/);function ul(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function ud(e){const t=[];let r=-1,n=0,s=0;for(;++r<e.length;){const i=e.charCodeAt(r);let o="";if(i===37&&Fs(e.charCodeAt(r+1))&&Fs(e.charCodeAt(r+2)))s=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const l=e.charCodeAt(r+1);i<56320&&l>56319&&l<57344?(o=String.fromCharCode(i,l),s=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(n,r),encodeURIComponent(o)),n=r+s+1,o=""),s&&(r+=s,s=0)}return t.join("")+e.slice(n)}function zn(e,t,r,n){const s=n?n-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(c){return _n(c)?(e.enter(r),l(c)):t(c)}function l(c){return _n(c)&&i++<s?(e.consume(c),l):(e.exit(r),t(c))}}const Yz={tokenize:Jz};function Jz(e){const t=e.attempt(this.parser.constructs.contentInitial,n,s);let r;return t;function n(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),zn(e,t,"linePrefix")}function s(l){return e.enter("paragraph"),i(l)}function i(l){const c=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=c),r=c,o(l)}function o(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return Lt(l)?(e.consume(l),e.exit("chunkText"),i):(e.consume(l),o)}}const Xz={tokenize:Zz},CS={tokenize:Qz};function Zz(e){const t=this,r=[];let n=0,s,i,o;return l;function l(k){if(n<r.length){const N=r[n];return t.containerState=N[1],e.attempt(N[0].continuation,c,u)(k)}return u(k)}function c(k){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const N=t.events.length;let j=N,w;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){w=t.events[j][1].end;break}b(n);let S=N;for(;S<t.events.length;)t.events[S][1].end={...w},S++;return va(t.events,j+1,0,t.events.slice(N)),t.events.length=S,u(k)}return l(k)}function u(k){if(n===r.length){if(!s)return h(k);if(s.currentConstruct&&s.currentConstruct.concrete)return x(k);t.interrupt=!!(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(CS,d,p)(k)}function d(k){return s&&v(),b(n),h(k)}function p(k){return t.parser.lazy[t.now().line]=n!==r.length,o=t.now().offset,x(k)}function h(k){return t.containerState={},e.attempt(CS,f,x)(k)}function f(k){return n++,r.push([t.currentConstruct,t.containerState]),h(k)}function x(k){if(k===null){s&&v(),b(0),e.consume(k);return}return s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),g(k)}function g(k){if(k===null){y(e.exit("chunkFlow"),!0),b(0),e.consume(k);return}return Lt(k)?(e.consume(k),y(e.exit("chunkFlow")),n=0,t.interrupt=void 0,l):(e.consume(k),g)}function y(k,N){const j=t.sliceStream(k);if(N&&j.push(null),k.previous=i,i&&(i.next=k),i=k,s.defineSkip(k.start),s.write(j),t.parser.lazy[k.start.line]){let w=s.events.length;for(;w--;)if(s.events[w][1].start.offset<o&&(!s.events[w][1].end||s.events[w][1].end.offset>o))return;const S=t.events.length;let T=S,C,A;for(;T--;)if(t.events[T][0]==="exit"&&t.events[T][1].type==="chunkFlow"){if(C){A=t.events[T][1].end;break}C=!0}for(b(n),w=S;w<t.events.length;)t.events[w][1].end={...A},w++;va(t.events,T+1,0,t.events.slice(S)),t.events.length=w}}function b(k){let N=r.length;for(;N-- >k;){const j=r[N];t.containerState=j[1],j[0].exit.call(t,e)}r.length=k}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function Qz(e,t,r){return zn(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Pu(e){if(e===null||br(e)||mc(e))return 1;if(ox(e))return 2}function lx(e,t,r){const n=[];let s=-1;for(;++s<e.length;){const i=e[s].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const g0={name:"attention",resolveAll:eq,tokenize:tq};function eq(e,t){let r=-1,n,s,i,o,l,c,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;c=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const p={...e[n][1].end},h={...e[r][1].start};PS(p,-c),PS(h,c),o={type:c>1?"strongSequence":"emphasisSequence",start:p,end:{...e[n][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...e[r][1].start},end:h},i={type:c>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[r][1].start}},s={type:c>1?"strong":"emphasis",start:{...o.start},end:{...l.end}},e[n][1].end={...o.start},e[r][1].start={...l.end},u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=Ia(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=Ia(u,[["enter",s,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=Ia(u,lx(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=Ia(u,[["exit",i,t],["enter",l,t],["exit",l,t],["exit",s,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=Ia(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,va(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function tq(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,s=Pu(n);let i;return o;function o(c){return i=c,e.enter("attentionSequence"),l(c)}function l(c){if(c===i)return e.consume(c),l;const u=e.exit("attentionSequence"),d=Pu(c),p=!d||d===2&&s||r.includes(c),h=!s||s===2&&d||r.includes(n);return u._open=!!(i===42?p:p&&(s||!h)),u._close=!!(i===42?h:h&&(d||!p)),t(c)}}function PS(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const nq={name:"autolink",tokenize:rq};function rq(e,t,r){let n=0;return s;function s(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return Ys(f)?(e.consume(f),o):f===64?r(f):u(f)}function o(f){return f===43||f===45||f===46||Fs(f)?(n=1,l(f)):u(f)}function l(f){return f===58?(e.consume(f),n=0,c):(f===43||f===45||f===46||Fs(f))&&n++<32?(e.consume(f),l):(n=0,u(f))}function c(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||Em(f)?r(f):(e.consume(f),c)}function u(f){return f===64?(e.consume(f),d):Vz(f)?(e.consume(f),u):r(f)}function d(f){return Fs(f)?p(f):r(f)}function p(f){return f===46?(e.consume(f),n=0,d):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):h(f)}function h(f){if((f===45||Fs(f))&&n++<63){const x=f===45?h:p;return e.consume(f),x}return r(f)}}const Th={partial:!0,tokenize:sq};function sq(e,t,r){return n;function n(i){return _n(i)?zn(e,s,"linePrefix")(i):s(i)}function s(i){return i===null||Lt(i)?t(i):r(i)}}const S3={continuation:{tokenize:iq},exit:oq,name:"blockQuote",tokenize:aq};function aq(e,t,r){const n=this;return s;function s(o){if(o===62){const l=n.containerState;return l.open||(e.enter("blockQuote",{_container:!0}),l.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return r(o)}function i(o){return _n(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function iq(e,t,r){const n=this;return s;function s(o){return _n(o)?zn(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(S3,t,r)(o)}}function oq(e){e.exit("blockQuote")}const C3={name:"characterEscape",tokenize:lq};function lq(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),s}function s(i){return Kz(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const P3={name:"characterReference",tokenize:cq};function cq(e,t,r){const n=this;let s=0,i,o;return l;function l(p){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),c}function c(p){return p===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(p),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,o=Fs,d(p))}function u(p){return p===88||p===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(p),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,o=Gz,d):(e.enter("characterReferenceValue"),i=7,o=m0,d(p))}function d(p){if(p===59&&s){const h=e.exit("characterReferenceValue");return o===Fs&&!m1(n.sliceSerialize(h))?r(p):(e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(p)&&s++<i?(e.consume(p),d):r(p)}}const AS={partial:!0,tokenize:dq},_S={concrete:!0,name:"codeFenced",tokenize:uq};function uq(e,t,r){const n=this,s={partial:!0,tokenize:j};let i=0,o=0,l;return c;function c(w){return u(w)}function u(w){const S=n.events[n.events.length-1];return i=S&&S[1].type==="linePrefix"?S[2].sliceSerialize(S[1],!0).length:0,l=w,e.enter("co
5589deFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(w)}function d(w){return w===l?(o++,e.consume(w),d):o<3?r(w):(e.exit("codeFencedFenceSequence"),_n(w)?zn(e,p,"whitespace")(w):p(w))}function p(w){return w===null||Lt(w)?(e.exit("codeFencedFence"),n.interrupt?t(w):e.check(AS,g,N)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(w))}function h(w){return w===null||Lt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),p(w)):_n(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),zn(e,f,"whitespace")(w)):w===96&&w===l?r(w):(e.consume(w),h)}function f(w){return w===null||Lt(w)?p(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),x(w))}function x(w){return w===null||Lt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),p(w)):w===96&&w===l?r(w):(e.consume(w),x)}function g(w){return e.attempt(s,N,y)(w)}function y(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return i>0&&_n(w)?zn(e,v,"linePrefix",i+1)(w):v(w)}function v(w){return w===null||Lt(w)?e.check(AS,g,N)(w):(e.enter("codeFlowValue"),k(w))}function k(w){return w===null||Lt(w)?(e.exit("codeFlowValue"),v(w)):(e.consume(w),k)}function N(w){return e.exit("codeFenced"),t(w)}function j(w,S,T){let C=0;return A;function A(D){return w.enter("lineEnding"),w.consume(D),w.exit("lineEnding"),P}function P(D){return w.enter("codeFencedFence"),_n(D)?zn(w,E,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):E(D)}function E(D){return D===l?(w.enter("codeFencedFenceSequence"),_(D)):T(D)}function _(D){return D===l?(C++,w.consume(D),_):C>=o?(w.exit("codeFencedFenceSequence"),_n(D)?zn(w,I,"whitespace")(D):I(D)):T(D)}function I(D){return D===null||Lt(D)?(w.exit("codeFencedFence"),S(D)):T(D)}}}function dq(e,t,r){const n=this;return s;function s(o){return o===null?r(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return n.parser.lazy[n.now().line]?r(o):t(o)}}const Oy={name:"codeIndented",tokenize:hq},pq={partial:!0,tokenize:fq};function hq(e,t,r){const n=this;return s;function s(u){return e.enter("codeIndented"),zn(e,i,"linePrefix",5)(u)}function i(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?o(u):r(u)}function o(u){return u===null?c(u):Lt(u)?e.attempt(pq,o,c)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||Lt(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),l)}function c(u){return e.exit("codeIndented"),t(u)}}function fq(e,t,r){const n=this;return s;function s(o){return n.parser.lazy[n.now().line]?r(o):Lt(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):zn(e,i,"linePrefix",5)(o)}function i(o){const l=n.events[n.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(o):Lt(o)?s(o):r(o)}}const mq={name:"codeText",previous:xq,resolve:gq,tokenize:yq};function gq(e){let t=e.length-4,r=3,n,s;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)s===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(s=n):(n===t||e[n][1].type==="lineEnding")&&(e[s][1].type="codeTextData",n!==s+2&&(e[s][1].end=e[n-1][1].end,e.splice(s+2,n-s-2),t-=n-s-2,n=s+2),s=void 0);return e}function xq(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function yq(e,t,r){let n=0,s,i;return o;function o(p){return e.enter("codeText"),e.enter("codeTextSequence"),l(p)}function l(p){return p===96?(e.consume(p),n++,l):(e.exit("codeTextSequence"),c(p))}function c(p){return p===null?r(p):p===32?(e.enter("space"),e.consume(p),e.exit("space"),c):p===96?(i=e.enter("codeTextSequence"),s=0,d(p)):Lt(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(p))}function u(p){return p===null||p===32||p===96||Lt(p)?(e.exit("codeTextData"),c(p)):(e.consume(p),u)}function d(p){return p===96?(e.consume(p),s++,d):s===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(p)):(i.type="codeTextData",u(p))}}class bq{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const s=r||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return n&&Md(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Md(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Md(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);Md(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Md(this.left,r.reverse())}}}function Md(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function A3(e){const t={};let r=-1,n,s,i,o,l,c,u;const d=new bq(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(c=n[1]._tokenizer.events,i=0,i<c.length&&c[i][1].type==="lineEndingBlank"&&(i+=2),i<c.length&&c[i][1].type==="content"))for(;++i<c.length&&c[i][1].type!=="content";)c[i][1].type==="chunkText"&&(c[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,vq(d,r)),r=t[r],u=!0);else if(n[1]._container){for(i=r,s=void 0;i--;)if(o=d.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(s&&(d.get(s)[1].type="lineEndingBlank"),o[1].type="lineEnding",s=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;s&&(n[1].end={...d.get(s)[1].start},l=d.slice(s,r),l.unshift(n),d.splice(s,r-s+1,l))}}return va(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function vq(e,t){const r=e.get(t)[1],n=e.get(t)[2];let s=t-1;const i=[];let o=r._tokenizer;o||(o=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const l=o.events,c=[],u={};let d,p,h=-1,f=r,x=0,g=0;const y=[g];for(;f;){for(;e.get(++s)[1]!==f;);i.push(s),f._tokenizer||(d=n.sliceStream(f),f.next||d.push(null),p&&o.defineSki
vendor: 18,560 bytes, line 5589
5589p(f.start),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),p=f,f=f.next}for(f=r;++h<l.length;)l[h][0]==="exit"&&l[h-1][0]==="enter"&&l[h][1].type===l[h-1][1].type&&l[h][1].start.line!==l[h][1].end.line&&(g=h+1,y.push(g),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(o.events=[],f?(f._tokenizer=void 0,f.previous=void 0):y.pop(),h=y.length;h--;){const b=l.slice(y[h],y[h+1]),v=i.pop();c.push([v,v+b.length-1]),e.splice(v,2,b)}for(c.reverse(),h=-1;++h<c.length;)u[x+c[h][0]]=x+c[h][1],x+=c[h][1]-c[h][0]-1;return u}const wq={resolve:Nq,tokenize:kq},jq={partial:!0,tokenize:Sq};function Nq(e){return A3(e),e}function kq(e,t){let r;return n;function n(l){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),s(l)}function s(l){return l===null?i(l):Lt(l)?e.check(jq,o,i)(l):(e.consume(l),s)}function i(l){return e.exit("chunkContent"),e.exit("content"),t(l)}function o(l){return e.consume(l),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,s}}function Sq(e,t,r){const n=this;return s;function s(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),zn(e,i,"linePrefix")}function i(o){if(o===null||Lt(o))return r(o);const l=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(o):e.interrupt(n.parser.constructs.flow,r,t)(o)}}function _3(e,t,r,n,s,i,o,l,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return p;function p(b){return b===60?(e.enter(n),e.enter(s),e.enter(i),e.consume(b),e.exit(i),h):b===null||b===32||b===41||Em(b)?r(b):(e.enter(n),e.enter(o),e.enter(l),e.enter("chunkString",{contentType:"string"}),g(b))}function h(b){return b===62?(e.enter(i),e.consume(b),e.exit(i),e.exit(s),e.exit(n),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),f(b))}function f(b){return b===62?(e.exit("chunkString"),e.exit(l),h(b)):b===null||b===60||Lt(b)?r(b):(e.consume(b),b===92?x:f)}function x(b){return b===60||b===62||b===92?(e.consume(b),f):f(b)}function g(b){return!d&&(b===null||b===41||br(b))?(e.exit("chunkString"),e.exit(l),e.exit(o),e.exit(n),t(b)):d<u&&b===40?(e.consume(b),d++,g):b===41?(e.consume(b),d--,g):b===null||b===32||b===40||Em(b)?r(b):(e.consume(b),b===92?y:g)}function y(b){return b===40||b===41||b===92?(e.consume(b),g):g(b)}}function T3(e,t,r,n,s,i){const o=this;let l=0,c;return u;function u(f){return e.enter(n),e.enter(s),e.consume(f),e.exit(s),e.enter(i),d}function d(f){return l>999||f===null||f===91||f===93&&!c||f===94&&!l&&"_hiddenFootnoteSupport"in o.parser.constructs?r(f):f===93?(e.exit(i),e.enter(s),e.consume(f),e.exit(s),e.exit(n),t):Lt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),p(f))}function p(f){return f===null||f===91||f===93||Lt(f)||l++>999?(e.exit("chunkString"),d(f)):(e.consume(f),c||(c=!_n(f)),f===92?h:p)}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,p):p(f)}}function E3(e,t,r,n,s,i){let o;return l;function l(h){return h===34||h===39||h===40?(e.enter(n),e.enter(s),e.consume(h),e.exit(s),o=h===40?41:h,c):r(h)}function c(h){return h===o?(e.enter(s),e.consume(h),e.exit(s),e.exit(n),t):(e.enter(i),u(h))}function u(h){return h===o?(e.exit(i),c(o)):h===null?r(h):Lt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),zn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===o||h===null||Lt(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?p:d)}function p(h){return h===o||h===92?(e.consume(h),d):d(h)}}function yp(e,t){let r;return n;function n(s){return Lt(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),r=!0,n):_n(s)?zn(e,n,r?"linePrefix":"lineSuffix")(s):t(s)}}const Cq={name:"definition",tokenize:Aq},Pq={partial:!0,tokenize:_q};function Aq(e,t,r){const n=this;let s;return i;function i(f){return e.enter("definition"),o(f)}function o(f){return T3.call(n,e,l,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function l(f){return s=oi(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):r(f)}function c(f){return br(f)?yp(e,u)(f):u(f)}function u(f){return _3(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(Pq,p,p)(f)}function p(f){return _n(f)?zn(e,h,"whitespace")(f):h(f)}function h(f){return f===null||Lt(f)?(e.exit("definition"),n.parser.defined.push(s),t(f)):r(f)}}function _q(e,t,r){return n;function n(l){return br(l)?yp(e,s)(l):r(l)}function s(l){return E3(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return _n(l)?zn(e,o,"whitespace")(l):o(l)}function o(l){return l===null||Lt(l)?t(l):r(l)}}const Tq={name:"hardBreakEscape",tokenize:Eq};function Eq(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return Lt(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const Iq={name:"headingAtx",resolve:Oq,tokenize:Rq};function Oq(e,t){let r=e.length-2,n=3,s,i;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(s={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},va(e,n,r-n+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function Rq(e,t,r){let n=0;return s;function s(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),o(d)}function o(d){return d===35&&n++<6?(e.consume(d),o):d===null||br(d)?(e.exit("atxHeadingSequence"),l(d)):r(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||Lt(d)?(e.exit("atxHeading"),t(d)):_n(d)?zn(e,l,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),l(d))}function u(d){return d===null||d===35||br(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),u)}}const Dq=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],TS=["pre","script","style","textarea"],Mq={concrete:!0,name:"htmlFlow",resolveTo:Fq,tokenize:Bq},Lq={partial:!0,tokenize:zq},$q={partial:!0,tokenize:Uq};function Fq(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Bq(e,t,r){const n=this;let s,i,o,l,c;return u;function u(O){return d(O)}function d(O){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(O),p}function p(O){return O===33?(e.consume(O),h):O===47?(e.consume(O),i=!0,g):O===63?(e.consume(O),s=3,n.interrupt?t:R):Ys(O)?(e.consume(O),o=String.fromCharCode(O),y):r(O)}function h(O){return O===45?(e.consume(O),s=2,f):O===91?(e.consume(O),s=5,l=0,x):Ys(O)?(e.consume(O),s=4,n.interrupt?t:R):r(O)}function f(O){return O===45?(e.consume(O),n.interrupt?t:R):r(O)}function x(O){const ne="CDATA[";return O===ne.charCodeAt(l++)?(e.consume(O),l===ne.length?n.interrupt?t:E:x):r(O)}function g(O){return Ys(O)?(e.consume(O),o=String.fromCharCode(O),y):r(O)}function y(O){if(O===null||O===47||O===62||br(O)){const ne=O===47,oe=o.toLowerCase();return!ne&&!i&&TS.includes(oe)?(s=1,n.interrupt?t(O):E(O)):Dq.includes(o.toLowerCase())?(s=6,ne?(e.consume(O),b):n.interrupt?t(O):E(O)):(s=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(O):i?v(O):k(O))}return O===45||Fs(O)?(e.consume(O),o+=String.fromCharCode(O),y):r(O)}function b(O){return O===62?(e.consume(O),n.interrupt?t:E):r(O)}function v(O){return _n(O)?(e.consume(O),v):A(O)}function k(O){return O===47?(e.consume(O),A):O===58||O===95||Ys(O)?(e.consume(O),N):_n(O)?(e.consume(O),k):A(O)}function N(O){return O===45||O===46||O===58||O===95||Fs(O)?(e.consume(O),N):j(O)}function j(O){return O===61?(e.consume(O),w):_n(O)?(e.consume(O),j):k(O)}function w(O){return O===null||O===60||O===61||O===62||O===96?r(O):O===34||O===39?(e.consume(O),c=O,S):_n(O)?(e.consume(O),w):T(O)}function S(O){return O===c?(e.consume(O),c=null,C):O===null||Lt(O)?r(O):(e.consume(O),S)}function T(O){return O===null||O===34||O===39||O===47||O===60||O===61||O===62||O===96||br(O)?j(O):(e.consume(O),T)}function C(O){return O===47||O===62||_n(O)?k(O):r(O)}function A(O){return O===62?(e.consume(O),P):r(O)}function P(O){return O===null||Lt(O)?E(O):_n(O)?(e.consume(O),P):r(O)}function E(O){return O===45&&s===2?(e.consume(O),M):O===60&&s===1?(e.consume(O),B):O===62&&s===4?(e.consume(O),Y):O===63&&s===3?(e.consume(O),R):O===93&&s===5?(e.consume(O),K):Lt(O)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(Lq,Z,_)(O)):O===null||Lt(O)?(e.exit("htmlFlowData"),_(O)):(e.consume(O),E)}function _(O){return e.check($q,I,Z)(O)}function I(O){return e.enter("lineEnding"),e.consume(O),e.exit("lineEnding"),D}function D(O){return O===null||Lt(O)?_(O):(e.enter("htmlFlowData"),E(O))}function M(O){return O===45?(e.consume(O),R):E(O)}function B(O){return O===47?(e.consume(O),o="",$):E(O)}function $(O){if(O===62){const ne=o.toLowerCase();return TS.includes(ne)?(e.consume(O),Y):E(O)}return Ys(O)&&o.length<8?(e.consume(O),o+=String.fromCharCode(O),$):E(O)}function K(O){return O===93?(e.consume(O),R):E(O)}function R(O){return O===62?(e.consume(O),Y):O===45&&s===2?(e.consume(O),R):E(O)}function Y(O){return O===null||Lt(O)?(e.exit("htmlFlowData"),Z(O)):(e.consume(O),Y)}function Z(O){return e.exit("htmlFlow"),t(O)}}function Uq(e,t,r){const n=this;return s;function s(o){return Lt(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):r(o)}function i(o){return n.parser.lazy[n.now().line]?r(o):t(o)}}function zq(e,t,r){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Th,t,r)}}const qq={name:"htmlText",tokenize:Hq};function Hq(e,t,r){const n=this;let s,i,o;return l;function l(R){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(R),c}function c(R){return R===33?(e.consume(R),u):R===47?(e.consume(R),j):R===63?(e.consume(R),k):Ys(R)?(e.consume(R),T):r(R)}function u(R){return R===45?(e.consume(R),d):R===91?(e.consume(R),i=0,x):Ys(R)?(e.consume(R),v):r(R)}function d(R){return R===45?(e.consume(R),f):r(R)}function p(R){return R===null?r(R):R===45?(e.consume(R),h):Lt(R)?(o=p,B(R)):(e.consume(R),p)}function h(R){return R===45?(e.consume(R),f):p(R)}function f(R){return R===62?M(R):R===45?h(R):p(R)}function x(R){const Y="CDATA[";return R===Y.charCodeAt(i++)?(e.consume(R),i===Y.length?g:x):r(R)}function g(R){return R===null?r(R):R===93?(e.consume(R),y):Lt(R)?(o=g,B(R)):(e.consume(R),g)}function y(R){return R===93?(e.consume(R),b):g(R)}function b(R){return R===62?M(R):R===93?(e.consume(R),b):g(R)}function v(R){return R===null||R===62?M(R):Lt(R)?(o=v,B(R)):(e.consume(R),v)}function k(R){return R===null?r(R):R===63?(e.consume(R),N):Lt(R)?(o=k,B(R)):(e.consume(R),k)}function N(R){return R===62?M(R):k(R)}function j(R){return Ys(R)?(e.consume(R),w):r(R)}function w(R){return R===45||Fs(R)?(e.consume(R),w):S(R)}function S(R){return Lt(R)?(o=S,B(R)):_n(R)?(e.consume(R),S):M(R)}function T(R){return R===45||Fs(R)?(e.consume(R),T):R===47||R===62||br(R)?C(R):r(R)}function C(R){return R===47?(e.consume(R),M):R===58||R===95||Ys(R)?(e.consume(R),A):Lt(R)?(o=C,B(R)):_n(R)?(e.consume(R),C):M(R)}function A(R){return R===45||R===46||R===58||R===95||Fs(R)?(e.consume(R),A):P(R)}function P(R){return R===61?(e.consume(R),E):Lt(R)?(o=P,B(R)):_n(R)?(e.consume(R),P):C(R)}function E(R){return R===null||R===60||R===61||R===62||R===96?r(R):R===34||R===39?(e.consume(R),s=R,_):Lt(R)?(o=E,B(R)):_n(R)?(e.consume(R),E):(e.consume(R),I)}function _(R){return R===s?(e.consume(R),s=void 0,D):R===null?r(R):Lt(R)?(o=_,B(R)):(e.consume(R),_)}function I(R){return R===null||R===34||R===39||R===60||R===61||R===96?r(R):R===47||R===62||br(R)?C(R):(e.consume(R),I)}function D(R){return R===47||R===62||br(R)?C(R):r(R)}function M(R){return R===62?(e.consume(R),e.exit("htmlTextData"),e.exit("htmlText"),t):r(R)}function B(R){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(R),e.exit("lineEnding"),$}function $(R){return _n(R)?zn(e,K,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):K(R)}function K(R){return e.enter("htmlTextData"),o(R)}}const g1={name:"labelEnd",resolveAll:Kq,resolveTo:Yq,tokenize:Jq},Wq={tokenize:Xq},Vq={tokenize:Zq},Gq={tokenize:Qq};function Kq(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const s=n.type==="labelImage"?4:2;n.type="data",t+=s}}return e.length!==r.length&&va(e,0,e.length,r),e}function Yq(e,t){let r=e.length,n=0,s,i,o,l;for(;r--;)if(s=e[r][1],i){if(s.type==="link"||s.type==="labelLink"&&s._inactive)break;e[r][0]==="enter"&&s.type==="labelLink"&&(s._inactive=!0)}else if(o){if(e[r][0]==="enter"&&(s.type==="labelImage"||s.type==="labelLink")&&!s._balanced&&(i=r,s.type!=="labelLink")){n=2;break}}else s.type==="labelEnd"&&(o=r);const c={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[o][1].end}},d={type:"labelText",start:{...e[i+n+2][1].end},end:{...e[o-2][1].start}};return l=[["enter",c,t],["enter",u,t]],l=Ia(l,e.slice(i+1,i+n+3)),l=Ia(l,[["enter",d,t]]),l=Ia(l,lx(t.parser.constructs.insideSpan.null,e.slice(i+n+4,o-3),t)),l=Ia(l,[["exit",d,t],e[o-2],e[o-1],["exit",u,t]]),l=Ia(l,e.slice(o+1)),l=Ia(l,[["exit",c,t]]),va(e,i,e.length,l),e}function Jq(e,t,r){const n=this;let s=n.events.length,i,o;for(;s--;)if((n.events[s][1].type==="labelImage"||n.events[s][1].type==="labelLink")&&!n.events[s][1]._balanced){i=n.events[s][1];break}return l;function l(h){return i?i._inactive?p(h):(o=n.parser.defined.includes(oi(n.sliceSerialize({start:i.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),c):r(h)}function c(h){return h===40?e.attempt(Wq,d,o?d:p)(h):h===91?e.attempt(Vq,d,o?u:p)(h):o?d(h):p(h)}function u(h){return e.attempt(Gq,d,p)(h)}function d(h){return t(h)}function p(h){return i._balanced=!0,r(h)}}function Xq(e,t,r){return n;function n(p){return e.enter("resource"),e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),s}function s(p){return br(p)?yp(e,i)(p):i(p)}function i(p){return p===41?d(p):_3(e,o,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function o(p){return br(p)?yp(e,c)(p):d(p)}function l(p){return r(p)}function c(p){return p===34||p===39||p===40?E3(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):d(p)}function u(p){return br(p)?yp(e,d)(p):d(p)}function d(p){return p===41?(e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),e.exit("resource"),t):r(p)}}function Zq(e,t,r){const n=this;return s;function s(l){return T3.call(n,e,i,o,"reference","referenceMarker","referenceString")(l)}function i(l){return n.parser.defined.includes(oi(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(l):r(l)}function o(l){return r(l)}}function Qq(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),s}function s(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const eH={name:"labelStartImage",resolveAll:g1.resolveAll,tokenize:tH};function tH(e,t,r){const n=this;return s;function s(l){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(l),e.exit("labelImageMarker"),i}function i(l){return l===91?(e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelImage"),o):r(l)}function o(l){return l===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(l):t(l)}}const nH={name:"labelStartLink",resolveAll:g1.resolveAll,tokenize:rH};function rH(e,t,r){const n=this;return s;function s(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const Ry={name:"lineEnding",tokenize:sH};function sH(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),zn(e,t,"linePrefix")}}const rm={name:"thematicBreak",tokenize:aH};function aH(e,t,r){let n=0,s;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return s=u,l(u)}function l(u){return u===s?(e.enter("thematicBreakSequence"),c(u)):n>=3&&(u===null||Lt(u))?(e.exit("thematicBreak"),t(u)):r(u)}function c(u){return u===s?(e.consume(u),n++,c):(e.exit("thematicBreakSequence"),_n(u)?zn(e,l,"whitespace")(u):l(u))}}const ea={continuation:{tokenize:cH},exit:dH,name:"list",tokenize:lH},iH={partial:!0,tokenize:pH},oH={partial:!0,tokenize:uH};function lH(e,t,r){const n=this,s=n.events[n.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,o=0;return l;function l(f){const x=n.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(x==="listUnordered"?!n.containerState.marker||f===n.containerState.marker:m0(f)){if(n.containerState.type||(n.containerState.type=x,e.enter(x,{_container:!0})),x==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(rm,r,u)(f):u(f);if(!n.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return r(f)}function c(f){return m0(f)&&++o<10?(e.consume(f),c):(!n.interrupt||o<2)&&(n.containerState.marker?f===n.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):r(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||f,e.check(Th,n.interrupt?r:d,e.attempt(iH,h,p))}
vendor: 7,347 bytes, line 5589
5589function d(f){return n.containerState.initialBlankLine=!0,i++,h(f)}function p(f){return _n(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),h):r(f)}function h(f){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function cH(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(Th,s,i);function s(l){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,zn(e,t,"listItemIndent",n.containerState.size+1)(l)}function i(l){return n.containerState.furtherBlankLines||!_n(l)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,o(l)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(oH,t,o)(l))}function o(l){return n.containerState._closeFlow=!0,n.interrupt=void 0,zn(e,e.attempt(ea,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function uH(e,t,r){const n=this;return zn(e,s,"listItemIndent",n.containerState.size+1);function s(i){const o=n.events[n.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===n.containerState.size?t(i):r(i)}}function dH(e){e.exit(this.containerState.type)}function pH(e,t,r){const n=this;return zn(e,s,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const o=n.events[n.events.length-1];return!_n(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const ES={name:"setextUnderline",resolveTo:hH,tokenize:fH};function hH(e,t){let r=e.length,n,s,i;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(s=r)}else e[r][1].type==="content"&&e.splice(r,1),!i&&e[r][1].type==="definition"&&(i=r);const o={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",o,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end={...e[i][1].end}):e[n][1]=o,e.push(["exit",o,t]),e}function fH(e,t,r){const n=this;let s;return i;function i(u){let d=n.events.length,p;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){p=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||p)?(e.enter("setextHeadingLine"),s=u,o(u)):r(u)}function o(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===s?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),_n(u)?zn(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||Lt(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const mH={tokenize:gH};function gH(e){const t=this,r=e.attempt(Th,n,e.attempt(this.parser.constructs.flowInitial,s,zn(e,e.attempt(this.parser.constructs.flow,s,e.attempt(wq,s)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const xH={resolveAll:O3()},yH=I3("string"),bH=I3("text");function I3(e){return{resolveAll:O3(e==="text"?vH:void 0),tokenize:t};function t(r){const n=this,s=this.parser.constructs[e],i=r.attempt(s,o,l);return o;function o(d){return u(d)?i(d):l(d)}function l(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),c}function c(d){return u(d)?(r.exit("data"),i(d)):(r.consume(d),c)}function u(d){if(d===null)return!0;const p=s[d];let h=-1;if(p)for(;++h<p.length;){const f=p[h];if(!f.previous||f.previous.call(n,n.previous))return!0}return!1}}}function O3(e){return t;function t(r,n){let s=-1,i;for(;++s<=r.length;)i===void 0?r[s]&&r[s][1].type==="data"&&(i=s,s++):(!r[s]||r[s][1].type!=="data")&&(s!==i+2&&(r[i][1].end=r[s-1][1].end,r.splice(i+2,s-i-2),s=i+2),i=void 0);return e?e(r,n):r}}function vH(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],s=t.sliceStream(n);let i=s.length,o=-1,l=0,c;for(;i--;){const u=s[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)l++,o--;if(o)break;o=-1}else if(u===-2)c=!0,l++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(l=0),l){const u={type:r===e.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:n.start._bufferIndex+o,_index:n.start._index+i,line:n.end.line,column:n.end.column-l,offset:n.end.offset-l},end:{...n.end}};n.end={...u.start},n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const wH={42:ea,43:ea,45:ea,48:ea,49:ea,50:ea,51:ea,52:ea,53:ea,54:ea,55:ea,56:ea,57:ea,62:S3},jH={91:Cq},NH={[-2]:Oy,[-1]:Oy,32:Oy},kH={35:Iq,42:rm,45:[ES,rm],60:Mq,61:ES,95:rm,96:_S,126:_S},SH={38:P3,92:C3},CH={[-5]:Ry,[-4]:Ry,[-3]:Ry,33:eH,38:P3,42:g0,60:[nq,qq],91:nH,92:[Tq,C3],93:g1,95:g0,96:mq},PH={null:[g0,xH]},AH={null:[42,95]},_H={null:[]},TH=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:AH,contentInitial:jH,disable:_H,document:wH,flow:kH,flowInitial:NH,insideSpan:PH,string:SH,text:CH},Symbol.toStringTag,{value:"Module"}));function EH(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const s={},i=[];let o=[],l=[];const c={attempt:S(j),check:S(w),consume:v,enter:k,exit:N,interrupt:S(w,{interrupt:!0})},u={code:null,containerState:{},defineSkip:g,events:[],now:x,parser:e,previous:null,sliceSerialize:h,sliceStream:f,write:p};let d=t.tokenize.call(u,c);return t.resolveAll&&i.push(t),u;function p(P){return o=Ia(o,P),y(),o[o.length-1]!==null?[]:(T(t,0),u.events=lx(i,u.events,u),u.events)}function h(P,E){return OH(f(P),E)}function f(P){return IH(o,P)}function x(){const{_bufferIndex:P,_index:E,line:_,column:I,offset:D}=n;return{_bufferIndex:P,_index:E,line:_,column:I,offset:D}}function g(P){s[P.line]=P.column,A()}function y(){let P;for(;n._index<o.length;){const E=o[n._index];if(typeof E=="string")for(P=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===P&&n._bufferIndex<E.length;)b(E.charCodeAt(n._bufferIndex));else b(E)}}function b(P){d=d(P)}function v(P){Lt(P)?(n.line++,n.column=1,n.offset+=P===-3?2:1,A()):P!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===o[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=P}function k(P,E){const _=E||{};return _.type=P,_.start=x(),u.events.push(["enter",_,u]),l.push(_),_}function N(P){const E=l.pop();return E.end=x(),u.events.push(["exit",E,u]),E}function j(P,E){T(P,E.from)}function w(P,E){E.restore()}function S(P,E){return _;function _(I,D,M){let B,$,K,R;return Array.isArray(I)?Z(I):"tokenize"in I?Z([I]):Y(I);function Y(he){return ae;function ae(ve){const re=ve!==null&&he[ve],se=ve!==null&&he.null,le=[...Array.isArray(re)?re:re?[re]:[],...Array.isArray(se)?se:se?[se]:[]];return Z(le)(ve)}}function Z(he){return B=he,$=0,he.length===0?M:O(he[$])}function O(he){return ae;function ae(ve){return R=C(),K=he,he.partial||(u.currentConstruct=he),he.name&&u.parser.constructs.disable.null.includes(he.name)?oe():he.tokenize.call(E?Object.assign(Object.create(u),E):u,c,ne,oe)(ve)}}function ne(he){return P(K,R),D}
vendor: 11,716 bytes, lines 5589-5591
5589function oe(he){return R.restore(),++$<B.length?O(B[$]):M}}}function T(P,E){P.resolveAll&&!i.includes(P)&&i.push(P),P.resolve&&va(u.events,E,u.events.length-E,P.resolve(u.events.slice(E),u)),P.resolveTo&&(u.events=P.resolveTo(u.events,u))}function C(){const P=x(),E=u.previous,_=u.currentConstruct,I=u.events.length,D=Array.from(l);return{from:I,restore:M};function M(){n=P,u.previous=E,u.currentConstruct=_,u.events.length=I,l=D,A()}}function A(){n.line in s&&n.column<2&&(n.column=s[n.line],n.offset+=s[n.line]-1)}}function IH(e,t){const r=t.start._index,n=t.start._bufferIndex,s=t.end._index,i=t.end._bufferIndex;let o;if(r===s)o=[e[r].slice(n,i)];else{if(o=e.slice(r,s),n>-1){const l=o[0];typeof l=="string"?o[0]=l.slice(n):o.shift()}i>0&&o.push(e[s].slice(0,i))}return o}function OH(e,t){let r=-1;const n=[];let s;for(;++r<e.length;){const i=e[r];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
5590`;break}case-3:{o=`\r
5591`;break}case-2:{o=t?" ":"	";break}case-1:{if(!t&&s)continue;o=" ";break}default:o=String.fromCharCode(i)}s=i===-2,n.push(o)}return n.join("")}function RH(e){const n={constructs:N3([TH,...(e||{}).extensions||[]]),content:s(Yz),defined:[],document:s(Xz),flow:s(mH),lazy:{},string:s(yH),text:s(bH)};return n;function s(i){return o;function o(l){return EH(n,i,l)}}}function DH(e){for(;!A3(e););return e}const IS=/[\0\t\n\r]/g;function MH(){let e=1,t="",r=!0,n;return s;function s(i,o,l){const c=[];let u,d,p,h,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(o||void 0).decode(i)),p=0,t="",r&&(i.charCodeAt(0)===65279&&p++,r=void 0);p<i.length;){if(IS.lastIndex=p,u=IS.exec(i),h=u&&u.index!==void 0?u.index:i.length,f=i.charCodeAt(h),!u){t=i.slice(p);break}if(f===10&&p===h&&n)c.push(-3),n=void 0;else switch(n&&(c.push(-5),n=void 0),p<h&&(c.push(i.slice(p,h)),e+=h-p),f){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:n=!0,e=1}p=h+1}return l&&(n&&c.push(-5),t&&c.push(t),c.push(null)),c}}const LH=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function $H(e){return e.replace(LH,FH)}function FH(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const s=r.charCodeAt(1),i=s===120||s===88;return k3(r.slice(i?2:1),i?16:10)}return m1(r)||e}const R3={}.hasOwnProperty;function BH(e,t,r){return typeof t!="string"&&(r=t,t=void 0),UH(r)(DH(RH(r).document().write(MH()(e,t,!0))))}function UH(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(on),autolinkProtocol:C,autolinkEmail:C,atxHeading:i(Te),blockQuote:i(se),characterEscape:C,characterReference:C,codeFenced:i(le),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:i(le,o),codeText:i(te,o),codeTextData:C,data:C,codeFlowValue:C,definition:i(We),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:i(Me),hardBreakEscape:i(Ee),hardBreakTrailing:i(Ee),htmlFlow:i(st,o),htmlFlowData:C,htmlText:i(st,o),htmlTextData:C,image:i(xt),label:o,link:i(on),listItem:i(mt),listItemValue:h,listOrdered:i(Yt,p),listUnordered:i(Yt),paragraph:i(ln),reference:O,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:i(Te),strong:i(at),thematicBreak:i($t)},exit:{atxHeading:c(),atxHeadingSequence:j,autolink:c(),autolinkEmail:re,autolinkProtocol:ve,blockQuote:c(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:oe,characterReferenceMarkerNumeric:oe,characterReferenceValue:he,characterReference:ae,codeFenced:c(y),codeFencedFence:g,codeFencedFenceInfo:f,codeFencedFenceMeta:x,codeFlowValue:A,codeIndented:c(b),codeText:c(D),codeTextData:A,data:A,definition:c(),definitionDestinationString:N,definitionLabelString:v,definitionTitleString:k,emphasis:c(),hardBreakEscape:c(E),hardBreakTrailing:c(E),htmlFlow:c(_),htmlFlowData:A,htmlText:c(I),htmlTextData:A,image:c(B),label:K,labelText:$,lineEnding:P,link:c(M),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:ne,resourceDestinationString:R,resourceTitleString:Y,resource:Z,setextHeading:c(T),setextHeadingLineSequence:S,setextHeadingText:w,strong:c(),thematicBreak:c()}};D3(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(ue){let je={type:"root",children:[]};const ct={stack:[je],tokenStack:[],config:t,enter:l,exit:u,buffer:o,resume:d,data:r},it=[];let q=-1;for(;++q<ue.length;)if(ue[q][1].type==="listOrdered"||ue[q][1].type==="listUnordered")if(ue[q][0]==="enter")it.push(q);else{const Nt=it.pop();q=s(ue,Nt,q)}for(q=-1;++q<ue.length;){const Nt=t[ue[q][0]];R3.call(Nt,ue[q][1].type)&&Nt[ue[q][1].type].call(Object.assign({sliceSerialize:ue[q][2].sliceSerialize},ct),ue[q][1])}if(ct.tokenStack.length>0){const Nt=ct.tokenStack[ct.tokenStack.length-1];(Nt[1]||OS).call(ct,void 0,Nt[0])}for(je.position={start:Eo(ue.length>0?ue[0][1].start:{line:1,column:1,offset:0}),end:Eo(ue.length>0?ue[ue.length-2][1].end:{line:1,column:1,offset:0})},q=-1;++q<t.transforms.length;)je=t.transforms[q](je)||je;return je}function s(ue,je,ct){let it=je-1,q=-1,Nt=!1,U,Ne,Ft,Zt;for(;++it<=ct;){const Ke=ue[it];switch(Ke[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ke[0]==="enter"?q++:q--,Zt=void 0;break}case"lineEndingBlank":{Ke[0]==="enter"&&(U&&!Zt&&!q&&!Ft&&(Ft=it),Zt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Zt=void 0}if(!q&&Ke[0]==="enter"&&Ke[1].type==="listItemPrefix"||q===-1&&Ke[0]==="exit"&&(Ke[1].type==="listUnordered"||Ke[1].type==="listOrdered")){if(U){let ie=it;for(Ne=void 0;ie--;){const we=ue[ie];if(we[1].type==="lineEnding"||we[1].type==="lineEndingBlank"){if(we[0]==="exit")continue;Ne&&(ue[Ne][1].type="lineEndingBlank",Nt=!0),we[1].type="lineEnding",Ne=ie}else if(!(we[1].type==="linePrefix"||we[1].type==="blockQuotePrefix"||we[1].type==="blockQuotePrefixWhitespace"||we[1].type==="blockQuoteMarker"||we[1].type==="listItemIndent"))break}Ft&&(!Ne||Ft<Ne)&&(U._spread=!0),U.end=Object.assign({},Ne?ue[Ne][1].start:Ke[1].end),ue.splice(Ne||it,0,["exit",U,Ke[2]]),it++,ct++}if(Ke[1].type==="listItemPrefix"){const ie={type:"listItem",_spread:!1,start:Object.assign({},Ke[1].start),end:void 0};U=ie,ue.splice(it,0,["enter",ie,Ke[2]]),it++,ct++,Ft=void 0,Zt=!0}}}return ue[je][1]._spread=Nt,ct}function i(ue,je){return ct;function ct(it){l.call(this,ue(it),it),je&&je.call(this,it)}}function o(){this.stack.push({type:"fragment",children:[]})}function l(ue,je,ct){this.stack[this.stack.length-1].children.push(ue),this.stack.push(ue),this.tokenStack.push([je,ct||void 0]),ue.position={start:Eo(je.start),end:void 0}}function c(ue){return je;function je(ct){ue&&ue.call(this,ct),u.call(this,ct)}}function u(ue,je){const ct=this.stack.pop(),it=this.tokenStack.pop();if(it)it[0].type!==ue.type&&(je?je.call(this,ue,it[0]):(it[1]||OS).call(this,ue,it[0]));else throw new Error("Cannot close `"+ue.type+"` ("+xp({start:ue.start,end:ue.end})+"): it’s not open");ct.position.end=Eo(ue.end)}function d(){return f1(this.stack.pop())}function p(){this.data.expectingFirstListItemValue=!0}function h(ue){if(this.data.expectingFirstListItemValue){const je=this.stack[this.stack.length-2];je.start=Number.parseInt(this.sliceSerialize(ue),10),this.data.expectingFirstListItemValue=void 0}}function f(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.lang=ue}function x(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.meta=ue}function g(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.value=ue.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.value=ue.replace(/(\r?\n|\r)$/g,"")}function v(ue){const je=this.resume(),ct=this.stack[this.stack.length-1];ct.label=je,ct.identifier=oi(this.sliceSerialize(ue)).toLowerCase()}function k(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.title=ue}function N(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.url=ue}function j(ue){const je=this.stack[this.stack.length-1];if(!je.depth){const ct=this.sliceSerialize(ue).length;je.depth=ct}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function S(ue){const je=this.stack[this.stack.length-1];je.depth=this.sliceSerialize(ue).codePointAt(0)===61?1:2}function T(){this.data.setextHeadingSlurpLineEnding=void 0}function C(ue){const ct=this.stack[this.stack.length-1].children;let it=ct[ct.length-1];(!it||it.type!=="text")&&(it=gt(),it.position={start:Eo(ue.start),end:void 0},ct.push(it)),this.stack.push(it)}function A(ue){const je=this.stack.pop();je.value+=this.sliceSerialize(ue),je.position.end=Eo(ue.end)}function P(ue){const je=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ct=je.children[je.children.length-1];ct.position.end=Eo(ue.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(je.type)&&(C.call(this,ue),A.call(this,ue))}function E(){this.data.atHardBreak=!0}function _(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.value=ue}function I(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.value=ue}function D(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.value=ue}function M(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=je,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function B(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=je,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function $(ue){const je=this.sliceSerialize(ue),ct=this.stack[this.stack.length-2];ct.label=$H(je),ct.identifier=oi(je).toLowerCase()}function K(){const ue=this.stack[this.stack.length-1],je=this.resume(),ct=this.stack[this.stack.length-1];if(this.data.inReference=!0,ct.type==="link"){const it=ue.children;ct.children=it}else ct.alt=je}function R(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.url=ue}function Y(){const ue=this.resume(),je=this.stack[this.stack.length-1];je.title=ue}function Z(){this.data.inReference=void 0}function O(){this.data.referenceType="collapsed"}function ne(ue){const je=this.resume(),ct=this.stack[this.stack.length-1];ct.label=je,ct.identifier=oi(this.sliceSerialize(ue)).toLowerCase(),this.data.referenceType="full"}function oe(ue){this.data.characterReferenceType=ue.type}function he(ue){const je=this.sliceSerialize(ue),ct=this.data.characterReferenceType;let it;ct?(it=k3(je,ct==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):it=m1(je);const q=this.stack[this.stack.length-1];q.value+=it}function ae(ue){const je=this.stack.pop();je.position.end=Eo(ue.end)}function ve(ue){A.call(this,ue);const je=this.stack[this.stack.length-1];je.url=this.sliceSerialize(ue)}function re(ue){A.call(this,ue);const je=this.stack[this.stack.length-1];je.url="mailto:"+this.sliceSerialize(ue)}function se(){return{type:"blockquote",children:[]}}function le(){return{type:"code",lang:null,meta:null,value:""}}function te(){return{type:"inlineCode",value:""}}function We(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Me(){return{type:"emphasis",children:[]}}function Te(){return{type:"heading",depth:0,children:[]}}function Ee(){return{type:"break"}}function st(){return{type:"html",value:""}}
vendor: 10,149 bytes, lines 5591-5595
5591function xt(){return{type:"image",title:null,url:"",alt:null}}function on(){return{type:"link",title:null,url:"",children:[]}}function Yt(ue){return{type:"list",ordered:ue.type==="listOrdered",start:null,spread:ue._spread,children:[]}}function mt(ue){return{type:"listItem",spread:ue._spread,checked:null,children:[]}}function ln(){return{type:"paragraph",children:[]}}function at(){return{type:"strong",children:[]}}function gt(){return{type:"text",value:""}}function $t(){return{type:"thematicBreak"}}}function Eo(e){return{line:e.line,column:e.column,offset:e.offset}}function D3(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?D3(e,n):zH(e,n)}}function zH(e,t){let r;for(r in t)if(R3.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function OS(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+xp({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+xp({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+xp({start:t.start,end:t.end})+") is still open")}function qH(e){const t=this;t.parser=r;function r(n){return BH(n,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function HH(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function WH(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
5592`}]}function VH(e,t){const r=t.value?t.value+`
5593`:"",n={},s=t.lang?t.lang.split(/\s+/):[];s.length>0&&(n.className=["language-"+s[0]]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function GH(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function KH(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function YH(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),s=ud(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let o,l=e.footnoteCounts.get(n);l===void 0?(l=0,e.footnoteOrder.push(n),o=e.footnoteOrder.length):o=i+1,l+=1,e.footnoteCounts.set(n,l);const c={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+s,id:r+"fnref-"+s+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function JH(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function XH(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function M3(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const s=e.all(t),i=s[0];i&&i.type==="text"?i.value="["+i.value:s.unshift({type:"text",value:"["});const o=s[s.length-1];return o&&o.type==="text"?o.value+=n:s.push({type:"text",value:n}),s}function ZH(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return M3(e,t);const s={src:ud(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(t,i),e.applyData(t,i)}function QH(e,t){const r={src:ud(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function eW(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function tW(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return M3(e,t);const s={href:ud(n.url||"")};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function nW(e,t){const r={href:ud(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function rW(e,t,r){const n=e.all(t),s=r?sW(r):L3(t),i={},o=[];if(typeof t.checked=="boolean"){const d=n[0];let p;d&&d.type==="element"&&d.tagName==="p"?p=d:(p={type:"element",tagName:"p",properties:{},children:[]},n.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let l=-1;for(;++l<n.length;){const d=n[l];(s||l!==0||d.type!=="element"||d.tagName!=="p")&&o.push({type:"text",value:`
5594`}),d.type==="element"&&d.tagName==="p"&&!s?o.push(...d.children):o.push(d)}const c=n[n.length-1];c&&(s||c.type!=="element"||c.tagName!=="p")&&o.push({type:"text",value:`
5595`});const u={type:"element",tagName:"li",properties:i,children:o};return e.patch(t,u),e.applyData(t,u)}function sW(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=L3(r[n])}return t}function L3(e){const t=e.spread;return t??e.children.length>1}function aW(e,t){const r={},n=e.all(t);let s=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++s<n.length;){const o=n[s];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function iW(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function oW(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function lW(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function cW(e,t){const r=e.all(t),n=r.shift(),s=[];if(n){const o={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],o),s.push(o)}if(r.length>0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},l=u1(t.children[1]),c=g3(t.children[t.children.length-1]);l&&c&&(o.position={start:l,end:c}),s.push(o)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function uW(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",o=r&&r.type==="table"?r.align:void 0,l=o?o.length:t.children.length;let c=-1;const u=[];for(;++c<l;){const p=t.children[c],h={},f=o?o[c]:void 0;f&&(h.align=f);let x={type:"element",tagName:i,properties:h,children:[]};p&&(x.children=e.all(p),e.patch(p,x),x=e.applyData(p,x)),u.push(x)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function dW(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const RS=9,DS=32;function pW(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),s=0;const i=[];for(;n;)i.push(MS(t.slice(s,n.index),s>0,!0),n[0]),s=n.index+n[0].length,n=r.exec(t);return i.push(MS(t.slice(s),s>0,!1)),i.join("")}function MS(e,t,r){let n=0,s=e.length;if(t){let i=e.codePointAt(n);for(;i===RS||i===DS;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(s-1);for(;i===RS||i===DS;)s--,i=e.codePointAt(s-1)}return s>n?e.slice(n,s):""}function hW(e,t){const r={type:"text",value:pW(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function fW(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const mW={blockquote:HH,break:WH,code:VH,delete:GH,emphasis:KH,footnoteReference:YH,heading:JH,html:XH,imageReference:ZH,image:QH,inlineCode:eW,linkReference:tW,link:nW,listItem:rW,list:aW,paragraph:iW,root:oW,strong:lW,table:cW,tableCell:dW,tableRow:uW,text:hW,thematicBreak:fW,toml:yf,yaml:yf,definition:yf,footnoteDefinition:yf};function yf(){}const $3=-1,cx=0,bp=1,Im=2,x1=3,y1=4,b1=5,v1=6,F3=7,B3=8,LS=typeof self=="object"?self:globalThis,gW=(e,t)=>{const r=(s,i)=>(e.set(i,s),s),n=s=>{if(e.has(s))return e.get(s);const[i,o]=t[s];switch(i){case cx:case $3:return r(o,s);case bp:{const l=r([],s);for(const c of o)l.push(n(c));return l}case Im:{const l=r({},s);for(const[c,u]of o)l[n(c)]=n(u);return l}case x1:return r(new Date(o),s);case y1:{const{source:l,flags:c}=o;return r(new RegExp(l,c),s)}case b1:{const l=r(new Map,s);for(const[c,u]of o)l.set(n(c),n(u));return l}case v1:{const l=r(new Set,s);for(const c of o)l.add(n(c));return l}case F3:{const{name:l,message:c}=o;return r(new LS[l](c),s)}case B3:return r(BigInt(o),s);case"BigInt":return r(Object(BigInt(o)),s);case"ArrayBuffer":return r(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:l}=new Uint8Array(o);return r(new DataView(l),o)}}return r(new LS[i](o),s)};return n},$S=e=>gW(new Map,e)(0),qc="",{toString:xW}={},{keys:yW}=Object,Ld=e=>{const t=typeof e;if(t!=="object"||!e)return[cx,t];const r=xW.call(e).slice(8,-1);switch(r){case"Array":return[bp,qc];case"Object":return[Im,qc];case"Date":return[x1,qc];case"RegExp":return[y1,qc];case"Map":return[b1,qc];case"Set":return[v1,qc];case"DataView":return[bp,r]}return r.includes("Array")?[bp,r]:r.includes("Error")?[F3,r]:[Im,r]},bf=([e,t])=>e===cx&&(t==="function"||t==="symbol"),bW=(e,t,r,n)=>{const s=(o,l)=>{const c=n.push(o)-1;return r.set(l,c),c},i=o=>
vendor: 4,097 bytes, lines 5595-5597
5595{if(r.has(o))return r.get(o);let[l,c]=Ld(o);switch(l){case cx:{let d=o;switch(c){case"bigint":l=B3,d=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return s([$3],o)}return s([l,d],o)}case bp:{if(c){let h=o;return c==="DataView"?h=new Uint8Array(o.buffer):c==="ArrayBuffer"&&(h=new Uint8Array(o)),s([c,[...h]],o)}const d=[],p=s([l,d],o);for(const h of o)d.push(i(h));return p}case Im:{if(c)switch(c){case"BigInt":return s([c,o.toString()],o);case"Boolean":case"Number":case"String":return s([c,o.valueOf()],o)}if(t&&"toJSON"in o)return i(o.toJSON());const d=[],p=s([l,d],o);for(const h of yW(o))(e||!bf(Ld(o[h])))&&d.push([i(h),i(o[h])]);return p}case x1:return s([l,o.toISOString()],o);case y1:{const{source:d,flags:p}=o;return s([l,{source:d,flags:p}],o)}case b1:{const d=[],p=s([l,d],o);for(const[h,f]of o)(e||!(bf(Ld(h))||bf(Ld(f))))&&d.push([i(h),i(f)]);return p}case v1:{const d=[],p=s([l,d],o);for(const h of o)(e||!bf(Ld(h)))&&d.push(i(h));return p}}const{message:u}=o;return s([l,{name:c,message:u}],o)};return i},FS=(e,{json:t,lossy:r}={})=>{const n=[];return bW(!(t||r),!!t,new Map,n)(e),n},Om=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?$S(FS(e,t)):structuredClone(e):(e,t)=>$S(FS(e,t));function vW(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function wW(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function jW(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||vW,n=e.options.footnoteBackLabel||wW,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let c=-1;for(;++c<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),p=String(u.identifier).toUpperCase(),h=ud(p.toLowerCase());let f=0;const x=[],g=e.footnoteCounts.get(p);for(;g!==void 0&&++f<=g;){x.length>0&&x.push({type:"text",value:" "});let v=typeof r=="string"?r:r(c,f);typeof v=="string"&&(v={type:"text",value:v}),x.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+h+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(c,f),className:["data-footnote-backref"]},children:Array.isArray(v)?v:[v]})}const y=d[d.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const v=y.children[y.children.length-1];v&&v.type==="text"?v.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...x)}else d.push(...x);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+h},children:e.wrap(d,!0)};e.patch(u,b),l.push(b)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...Om(o),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:`
5596`},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:`
5597`}]}}const ux=function(e){if(e==null)return CW;if(typeof e=="function")return dx(e);if(typeof e=="object")return Array.isArray(e)?NW(e):kW(e);if(typeof e=="string")return SW(e);throw new Error("Expected function, string, or object as test")};function NW(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=ux(e[r]);return dx(n);function n(...s){let i=-1;for(;++i<t.length;)if(t[i].apply(this,s))return!0;return!1}}function kW(e){const t=e;return dx(r);function r(n){const s=n;let i;for(i in e)if(s[i]!==t[i])return!1;return!0}}function SW(e){return dx(t);function t(r){return r&&r.type===e}}function dx(e){return t;function t(r,n,s){return!!(PW(r)&&e.call(this,r,typeof n=="number"?n:void 0,s||void 0))}}function CW(){return!0}function PW(e){return e!==null&&typeof e=="object"&&"type"in e}const U3=[],AW=!0,x0=!1,_W="skip";function z3(e,t,r,n){let s;typeof t=="function"&&typeof r!="function"?(n=r,r=t):s=t;const i=ux(s),o=n?-1:1;l(e,void 0,[])();function l(c,u,d){const p=c&&typeof c=="object"?c:{};
vendor: 20,145 bytes, lines 5597-5601
5597if(typeof p.type=="string"){const f=typeof p.tagName=="string"?p.tagName:typeof p.name=="string"?p.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(c.type+(f?"<"+f+">":""))+")"})}return h;function h(){let f=U3,x,g,y;if((!t||i(c,u,d[d.length-1]||void 0))&&(f=TW(r(c,d)),f[0]===x0))return f;if("children"in c&&c.children){const b=c;if(b.children&&f[0]!==_W)for(g=(n?b.children.length:-1)+o,y=d.concat(b);g>-1&&g<b.children.length;){const v=b.children[g];if(x=l(v,g,y)(),x[0]===x0)return x;g=typeof x[1]=="number"?x[1]:g+o}}return f}}}function TW(e){return Array.isArray(e)?e:typeof e=="number"?[AW,e]:e==null?U3:[e]}function w1(e,t,r,n){let s,i,o;typeof t=="function"&&typeof r!="function"?(i=void 0,o=t,s=r):(i=t,o=r,s=n),z3(e,i,l,s);function l(c,u){const d=u[u.length-1],p=d?d.children.indexOf(c):void 0;return o(c,p,d)}}const y0={}.hasOwnProperty,EW={};function IW(e,t){const r=t||EW,n=new Map,s=new Map,i=new Map,o={...mW,...r.handlers},l={all:u,applyData:RW,definitionById:n,footnoteById:s,footnoteCounts:i,footnoteOrder:[],handlers:o,one:c,options:r,patch:OW,wrap:MW};return w1(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const p=d.type==="definition"?n:s,h=String(d.identifier).toUpperCase();p.has(h)||p.set(h,d)}}),l;function c(d,p){const h=d.type,f=l.handlers[h];if(y0.call(l.handlers,h)&&f)return f(l,d,p);if(l.options.passThrough&&l.options.passThrough.includes(h)){if("children"in d){const{children:g,...y}=d,b=Om(y);return b.children=l.all(d),b}return Om(d)}return(l.options.unknownHandler||DW)(l,d,p)}function u(d){const p=[];if("children"in d){const h=d.children;let f=-1;for(;++f<h.length;){const x=l.one(h[f],d);if(x){if(f&&h[f-1].type==="break"&&(!Array.isArray(x)&&x.type==="text"&&(x.value=BS(x.value)),!Array.isArray(x)&&x.type==="element")){const g=x.children[0];g&&g.type==="text"&&(g.value=BS(g.value))}Array.isArray(x)?p.push(...x):p.push(x)}}}return p}}function OW(e,t){e.position&&(t.position=wz(e))}function RW(e,t){let r=t;if(e&&e.data){const n=e.data.hName,s=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const o="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:o}}r.type==="element"&&i&&Object.assign(r.properties,Om(i)),"children"in r&&r.children&&s!==null&&s!==void 0&&(r.children=s)}return r}function DW(e,t){const r=t.data||{},n="value"in t&&!(y0.call(r,"hProperties")||y0.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function MW(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
5598`});++n<e.length;)n&&r.push({type:"text",value:`
5599`}),r.push(e[n]);return t&&e.length>0&&r.push({type:"text",value:`
5600`}),r}function BS(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function US(e,t){const r=IW(e,t),n=r.one(e,void 0),s=jW(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return s&&i.children.push({type:"text",value:`
5601`},s),i}function LW(e,t){return e&&"run"in e?async function(r,n){const s=US(r,{file:n,...t});await e.run(s,n)}:function(r,n){return US(r,{file:n,...e||t})}}function zS(e){if(e)throw e}var sm=Object.prototype.hasOwnProperty,q3=Object.prototype.toString,qS=Object.defineProperty,HS=Object.getOwnPropertyDescriptor,WS=function(t){return typeof Array.isArray=="function"?Array.isArray(t):q3.call(t)==="[object Array]"},VS=function(t){if(!t||q3.call(t)!=="[object Object]")return!1;var r=sm.call(t,"constructor"),n=t.constructor&&t.constructor.prototype&&sm.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!n)return!1;var s;for(s in t);return typeof s>"u"||sm.call(t,s)},GS=function(t,r){qS&&r.name==="__proto__"?qS(t,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):t[r.name]=r.newValue},KS=function(t,r){if(r==="__proto__")if(sm.call(t,r)){if(HS)return HS(t,r).value}else return;return t[r]},$W=function e(){var t,r,n,s,i,o,l=arguments[0],c=1,u=arguments.length,d=!1;for(typeof l=="boolean"&&(d=l,l=arguments[1]||{},c=2),(l==null||typeof l!="object"&&typeof l!="function")&&(l={});c<u;++c)if(t=arguments[c],t!=null)for(r in t)n=KS(l,r),s=KS(t,r),l!==s&&(d&&s&&(VS(s)||(i=WS(s)))?(i?(i=!1,o=n&&WS(n)?n:[]):o=n&&VS(n)?n:{},GS(l,{name:r,newValue:e(d,o,s)})):typeof s<"u"&&GS(l,{name:r,newValue:s}));return l};const Dy=zs($W);function b0(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function FW(){const e=[],t={run:r,use:n};return t;function r(...s){let i=-1;const o=s.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);l(null,...s);function l(c,...u){const d=e[++i];let p=-1;if(c){o(c);return}for(;++p<s.length;)(u[p]===null||u[p]===void 0)&&(u[p]=s[p]);s=u,d?BW(d,l)(...u):o(null,...u)}}function n(s){if(typeof s!="function")throw new TypeError("Expected `middelware` to be a function, not "+s);return e.push(s),t}}function BW(e,t){let r;return n;function n(...o){const l=e.length>o.length;let c;l&&o.push(s);try{c=e.apply(this,o)}catch(u){const d=u;if(l&&r)throw d;return s(d)}l||(c&&c.then&&typeof c.then=="function"?c.then(i,s):c instanceof Error?s(c):i(c))}function s(o,...l){r||(r=!0,t(o,...l))}function i(o){s(null,o)}}const ji={basename:UW,dirname:zW,extname:qW,join:HW,sep:"/"};function UW(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Eh(e);let r=0,n=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){r=s+1;break}}else n<0&&(i=!0,n=s+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let o=-1,l=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){r=s+1;break}}else o<0&&(i=!0,o=s+1),l>-1&&(e.codePointAt(s)===t.codePointAt(l--)?l<0&&(n=s):(l=-1,n=o));return r===n?n=o:n<0&&(n=e.length),e.slice(r,n)}function zW(e){if(Eh(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function qW(e){Eh(e);let t=e.length,r=-1,n=0,s=-1,i=0,o;for(;t--;){const l=e.codePointAt(t);if(l===47){if(o){n=t+1;break}continue}r<0&&(o=!0,r=t+1),l===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||r<0||i===0||i===1&&s===r-1&&s===n+1?"":e.slice(s,r)}function HW(...e){let t=-1,r;for(;++t<e.length;)Eh(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":WW(r)}function WW(e){Eh(e);const t=e.codePointAt(0)===47;let r=VW(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function VW(e,t){let r="",n=0,s=-1,i=0,o=-1,l,c;for(;++o<=e.length;){if(o<e.length)l=e.codePointAt(o);else{if(l===47)break;l=47}if(l===47){if(!(s===o-1||i===1))if(s!==o-1&&i===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(c=r.lastIndexOf("/"),c!==r.length-1){c<0?(r="",n=0):(r=r.slice(0,c),n=r.length-1-r.lastIndexOf("/")),s=o,i=0;continue}}else if(r.length>0){r="",n=0,s=o,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(s+1,o):r=e.slice(s+1,o),n=o-s-1;s=o,i=0}else l===46&&i>-1?i++:i=-1}return r}function Eh(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const GW={cwd:KW};function KW(){return"/"}function v0(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function YW(e){if(typeof e=="string")e=new URL(e);else if(!v0(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return JW(e)}function JW(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const s=new TypeError("File URL path must not include encoded / characters");throw s.code="ERR_INVALID_FILE_URL_PATH",s}}return decodeURIComponent(t)}const My=["history","path","basename","stem","extname","dirname"];class H3{constructor(t){let r;t?v0(t)?r={path:t}:typeof t=="string"||XW(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":GW.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<My.length;){const i=My[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let s;for(s in r)My.includes(s)||(this[s]=r[s])}get basename(){return typeof this.path=="string"?ji.basename(this.path):void 0}set basename(t){$y(t,"basename"),Ly(t,"basename"),this.path=ji.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?ji.dirname(this.path):void 0}set dirname(t){YS(this.basename,"dirname"),this.path=ji.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?ji.extname(this.path):void 0}set extname(t){if(Ly(t,"extname"),YS(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=ji.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){v0(t)&&(t=YW(t)),$y(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?ji.basename(this.path,this.extname):void 0}set stem(t){$y(t,"stem"),Ly(t,"stem"),this.path=ji.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const s=this.message(t,r,n);throw s.fatal=!0,s}info(t,r,n){const s=this.message(t,r,n);return s.fatal=void 0,s}message(t,r,n){const s=new qs(t,r,n);return this.path&&(s.name=this.path+":"+s.name,s.file=this.path),s.fatal=!1,this.messages.push(s),s}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Ly(e,t){if(e&&e.includes(ji.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+ji.sep+"`")}function $y(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function YS(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function XW(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ZW=function(e){const n=this.constructor.prototype,s=n[e],i=function(){return s.apply(i,arguments)};return Object.setPrototypeOf(i,n),i},QW={}.hasOwnProperty;class j1 extends ZW{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=FW()}copy(){const t=new j1;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Dy(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(Uy("data",this.frozen),this.namespace[t]=r,this):QW.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Uy("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const s=r.call(t,...n);typeof s=="function"&&this.transformers.use(s)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=vf(t),n=this.parser||this.Parser;return Fy("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),Fy("process",this.parser||this.Parser),By("process",this.compiler||this.Compiler),r?s(void 0,r):new Promise(s);function s(i,o){const l=vf(t),c=n.parse(l);n.run(c,l,function(d,p,h){if(d||!p||!h)return u(d);const f=p,x=n.stringify(f,h);nV(x)?h.value=x:h.result=x,u(d,h)});function u(d,p){d||!p?o(d):i?i(p):r(void 0,p)}}}processSync(t){let r=!1,n;return this.freeze(),Fy("processSync",this.parser||this.Parser),By("processSync",this.compiler||this.Compiler),this.process(t,s),XS("processSync","process",r),n;function s(i,o){r=!0,zS(i),n=o}}run(t,r,n){JS(t),this.freeze();const s=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(o,l){const c=vf(r);s.run(t,c,u);function u(d,p,h){const f=p||t;d?l(d):o?o(f):n(void 0,f,h)}}}runSync(t,r){let n=!1,s;return this.run(t,r,i),XS("runSync","run",n),s;function i(o,l){zS(o),s=l,n=!0}}stringify(t,r){this.freeze();const n=vf(r),s=this.compiler||this.Compiler;return By("stringify",s),JS(t),s(t,n)}use(t,...r){const n=this.attachers,s=this.namespace;if(Uy("use",this.frozen),t!=null)if(typeof t=="function")c(t,r);else if(typeof t=="object")Array.isArray(t)?l(t):o(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...p]=u;c(d,p)}else o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(s.settings=Dy(!0,s.settings,u.settings))}function l(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const p=u[d];i(p)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let p=-1,h=-1;for(;++p<n.length;)if(n[p][0]===u){h=p;break}if(h===-1)n.push([u,...d]);else if(d.length>0){let[f,...x]=d;const g=n[h][1];b0(g)&&b0(f)&&(f=Dy(!0,g,f)),n[h]=[u,f,...x]}}}}const eV=new j1().freeze();function Fy(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function By(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Uy(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function JS(e){if(!b0(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function XS(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function vf(e){return tV(e)?e:new H3(e)}function tV(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function nV(e){return typeof e=="string"||rV(e)}function rV(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const sV="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ZS=[],QS={allowDangerousHtml:!0},aV=/^(https?|ircs?|mailto|xmpp)$/i,iV=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function oV(e){const t=lV(e),r=cV(e);return uV(t.runSync(t.parse(r),r),e)}function lV(e){const t=e.rehypePlugins||ZS,r=e.remarkPlugins||ZS,n=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...QS}:QS;return eV().use(qH).use(r).use(LW,n).use(t)}function cV(e){const t=e.children||"",r=new H3;return typeof t=="string"&&(r.value=t),r}function uV(e,t){const r=t.allowedElements,n=t.allowElement,s=t.components,i=t.disallowedElements,o=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||dV;for(const d of iV)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+sV+d.id,void 0);return w1(e,u),Cz(e,{Fragment:a.Fragment,components:s,ignoreInvalidStyle:!0,jsx:a.jsx,jsxs:a.jsxs,passKeys:!0,passNode:!0});function u(d,p,h){if(d.type==="raw"&&h&&typeof p=="number")return o?h.children.splice(p,1):h.children[p]={type:"text",value:d.value},p;if(d.type==="element"){let f;for(f in Iy)if(Object.hasOwn(Iy,f)&&Object.hasOwn(d.properties,f)){const x=d.properties[f],g=Iy[f];(g===null||g.includes(d.tagName))&&(d.properties[f]=c(String(x||""),f,d))}}if(d.type==="element"){let f=r?!r.includes(d.tagName):i?i.includes(d.tagName):!1;if(!f&&n&&typeof p=="number"&&(f=!n(d,p,h)),f&&h&&typeof p=="number")return l&&d.children?h.children.splice(p,1,...d.children):h.children.splice(p,1),p}}}function dV(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),s=e.indexOf("/");return t===-1||s!==-1&&t>s||r!==-1&&t>r||n!==-1&&t>n||aV.test(e.slice(0,t))?e:""}function e2(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,s=r.indexOf(t);for(;s!==-1;)n++,s=r.indexOf(t,s+t.length);return n}function pV(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function hV(e,t,r){const s=ux((r||{}).ignore||[]),i=fV(t);let o=-1;for(;++o<i.length;)z3(e,"text",l);function l(u,d){let p=-1,h;for(;++p<d.length;){const f=d[p],x=h?h.children:void 0;if(s(f,x?x.indexOf(f):void 0,h))return;h=f}if(h)return c(u,d)}function c(u,d){const p=d[d.length-1],h=i[o][0],f=i[o][1];let x=0;const y=p.children.indexOf(u);let b=!1,v=[];h.lastIndex=0;let k=h.exec(u.value);for(;k;){const N=k.index,j={index:k.index,input:k.input,stack:[...d,u]};let w=f(...k,j);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?h.lastIndex=N+1:(x!==N&&v.push({type:"text",value:u.value.slice(x,N)}),Array.isArray(w)?v.push(...w):w&&v.push(w),x=N+k[0].length,b=!0),!h.global)break;k=h.exec(u.value)}return b?(x<u.value.length&&v.push({type:"text",value:u.value.slice(x)}),p.children.splice(y,1,...v)):v=[u],y+v.length}}function fV(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const s=r[n];t.push([mV(s[0]),gV(s[1])])}return t}function mV(e){return typeof e=="string"?new RegExp(pV(e),"g"):e}function gV(e){return typeof e=="function"?e:function(){return e}}const zy="phrasing",qy=["autolink","link","image","label"];function xV(){return{transforms:[kV],enter:{literalAutolink:bV,literalAutolinkEmail:Hy,literalAutolinkHttp:Hy,literalAutolinkWww:Hy},exit:{literalAutolink:NV,literalAutolinkEmail:jV,literalAutolinkHttp:vV,literalAutolinkWww:wV}}}function yV(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:zy,notInConstruct:qy},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:zy,notInConstruct:qy},{character:":",before:"[ps]",after:"\\/",inConstruct:zy,notInConstruct:qy}]}}function bV(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Hy(e){this.config.enter.autolinkProtocol.call(this,e)}function vV(e){this.config.exit.autolinkProtocol.call(this,e)}function wV(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function jV(e){this.config.exit.autolinkEmail.call(this,e)}function NV(e){this.exit(e)}function kV(e){hV(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,SV],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S}
5601)([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),CV]],{ignore:["link","linkReference"]})}function SV(e,t,r,n,s){let i="";if(!W3(s)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!PV(r)))return!1;const o=AV(r+n);if(!o[0])return!1;const l={type:"link",title:null,url:i+t+o[0],children:[{type:"text",value:t+o[0]}]};return o[1]?[l,{type:"text",value:o[1]}]:l}function CV(e,t,r,n){return!W3(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function PV(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function AV(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const s=e2(e,"(");let i=e2(e,")");for(;n!==-1&&s>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function W3(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||mc(r)||ox(r))&&(!t||r!==47)}V3.peek=LV;function _V(){this.buffer()}function TV(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function EV(){this.buffer()}function IV(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function OV(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=oi(this.sliceSerialize(e)).toLowerCase(),r.label=t}function RV(e){this.exit(e)}function DV(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=oi(this.sliceSerialize(e)).toLowerCase(),r.label=t}function MV(e){this.exit(e)}function LV(){return"["}function V3(e,t,r,n){const s=r.createTracker(n);let i=s.move("[^");const o=r.enter("footnoteReference"),l=r.enter("reference");return i+=s.move(r.safe(r.associationId(e),{after:"]",before:i})),l(),o(),i+=s.move("]"),i}function $V(){return{enter:{gfmFootnoteCallString:_V,gfmFootnoteCall:TV,gfmFootnoteDefinitionLabelString:EV,gfmFootnoteDefinition:IV},exit:{gfmFootnoteCallString:OV,gfmFootnoteCall:RV,gfmFootnoteDefinitionLabelString:DV,gfmFootnoteDefinition:MV}}}function FV(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:V3},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,s,i,o){const l=i.createTracker(o);let c=l.move("[^");const u=i.enter("footnoteDefinition"),d=i.enter("label");return c+=l.move(i.safe(i.associationId(n),{before:c,after:"]"})),d(),c+=l.move("]:"),n.children&&n.children.length>0&&(l.shift(4),c+=l.move((t?`
5602`:" ")+i.indentLines(i.containerFlow(n,l.current()),t?G3:BV))),u(),c}}function BV(e,t,r){return t===0?e:G3(e,t,r)}function G3(e,t,r){return(r?"":"    ")+e}const UV=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];K3.peek=VV;function zV(){return{canContainEols:["delete"],enter:{strikethrough:HV},exit:{strikethrough:WV}}}function qV(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:UV}],handlers:{delete:K3}}}function HV(e){this.enter({type:"delete",children:[]},e)}function WV(e){this.exit(e)}function K3(e,t,r,n){const s=r.createTracker(n),i=r.enter("strikethrough");let o=s.move("~~");return o+=r.containerPhrasing(e,{...s.current(),before:o,after:"~"}),o+=s.move("~~"),i(),o}function VV(){return"~"}function GV(e){return e.length}function KV(e,t){const r=t||{},n=(r.align||[]).concat(),s=r.stringLength||GV,i=[],o=[],l=[],c=[];let u=0,d=-1;for(;++d<e.length;){const g=[],y=[];let b=-1;for(e[d].length>u&&(u=e[d].length);++b<e[d].length;){const v=YV(e[d][b]);if(r.alignDelimiters!==!1){const k=s(v);y[b]=k,(c[b]===void 0||k>c[b])&&(c[b]=k)}g.push(v)}o[d]=g,l[d]=y}let p=-1;if(typeof n=="object"&&"length"in n)for(;++p<u;)i[p]=t2(n[p]);else{const g=t2(n);for(;++p<u;)i[p]=g}p=-1;const h=[],f=[];for(;++p<u;){const g=i[p];let y="",b="";g===99?(y=":",b=":"):g===108?y=":":g===114&&(b=":");let v=r.alignDelimiters===!1?1:Math.max(1,c[p]-y.length-b.length);const k=y+"-".repeat(v)+b;r.alignDelimiters!==!1&&(v=y.length+v+b.length,v>c[p]&&(c[p]=v),f[p]=v),h[p]=k}o.splice(1,0,h),l.splice(1,0,f),d=-1;const x=[];for(;++d<o.length;){const g=o[d],y=l[d];p=-1;const b=[];for(;++p<u;){const v=g[p]||"";let k="",N="";if(r.alignDelimiters!==!1){const j=c[p]-(y[p]||0),w=i[p];w===114?k=" ".repeat(j):w===99?j%2?(k=" ".repeat(j/2+.5),N=" ".repeat(j/2-.5)):(k=" ".repeat(j/2),N=k):N=" ".repeat(j)}r.delimiterStart!==!1&&!p&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&v==="")&&(r.delimiterStart!==!1||p)&&b.push(" "),r.alignDelimiters!==!1&&b.push(k),b.push(v),r.alignDelimiters!==!1&&b.push(N),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||p!==u-1)&&b.push("|")}x.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return x.join(`
5603`)}function YV(e){return e==null?"":String(e)}function t2(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function JV(e,t,r,n){const s=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const o=r.indentLines(r.containerFlow(e,i.current()),XV);return s(),o}function XV(e,t,r){return">"+(r?"":" ")+e}function ZV(e,t){return n2(e,t.inConstruct,!0)&&!n2(e,t.notInConstruct,!1)}function n2(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function r2(e,t,r,n){let s=-1;for(;++s<r.unsafe.length;)if(r.unsafe[s].character===`
5604`&&ZV(r.stack,r.unsafe[s]))return/[ \t]/.test(n.before)?"":" ";return`\\
5605`}function QV(e,t){const r=String(e);let n=r.indexOf(t),s=n,i=0,o=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===s?++i>o&&(o=i):i=1,s=n+t.length,n=r.indexOf(t,s);return o}function eG(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function tG(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function nG(e,t,r,n){const s=tG(r),i=e.value||"",o=s==="`"?"GraveAccent":"Tilde";
vendor: 10,339 bytes, lines 5605-5614
5605if(eG(e,r)){const p=r.enter("codeIndented"),h=r.indentLines(i,rG);return p(),h}const l=r.createTracker(n),c=s.repeat(Math.max(QV(i,s)+1,3)),u=r.enter("codeFenced");let d=l.move(c);if(e.lang){const p=r.enter(`codeFencedLang${o}`);d+=l.move(r.safe(e.lang,{before:d,after:" ",encode:["`"],...l.current()})),p()}if(e.lang&&e.meta){const p=r.enter(`codeFencedMeta${o}`);d+=l.move(" "),d+=l.move(r.safe(e.meta,{before:d,after:`
5606`,encode:["`"],...l.current()})),p()}return d+=l.move(`
5607`),i&&(d+=l.move(i+`
5608`)),d+=l.move(c),u(),d}function rG(e,t,r){return(r?"":"    ")+e}function N1(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function sG(e,t,r,n){const s=N1(r),i=s==='"'?"Quote":"Apostrophe",o=r.enter("definition");let l=r.enter("label");const c=r.createTracker(n);let u=c.move("[");return u+=c.move(r.safe(r.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),l(),!e.url||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(r.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(l=r.enter("destinationRaw"),u+=c.move(r.safe(e.url,{before:u,after:e.title?" ":`
5609`,...c.current()}))),l(),e.title&&(l=r.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(r.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),l()),o(),u}function aG(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function $p(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Rm(e,t,r){const n=Pu(e),s=Pu(t);return n===void 0?s===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Y3.peek=iG;function Y3(e,t,r,n){const s=aG(r),i=r.enter("emphasis"),o=r.createTracker(n),l=o.move(s);let c=o.move(r.containerPhrasing(e,{after:s,before:l,...o.current()}));const u=c.charCodeAt(0),d=Rm(n.before.charCodeAt(n.before.length-1),u,s);d.inside&&(c=$p(u)+c.slice(1));const p=c.charCodeAt(c.length-1),h=Rm(n.after.charCodeAt(0),p,s);h.inside&&(c=c.slice(0,-1)+$p(p));const f=o.move(s);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},l+c+f}function iG(e,t,r){return r.options.emphasis||"*"}function oG(e,t){let r=!1;return w1(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,x0}),!!((!e.depth||e.depth<3)&&f1(e)&&(t.options.setext||r))}function lG(e,t,r,n){const s=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(oG(e,r)){const d=r.enter("headingSetext"),p=r.enter("phrasing"),h=r.containerPhrasing(e,{...i.current(),before:`
5610`,after:`
5611`});return p(),d(),h+`
5612`+(s===1?"=":"-").repeat(h.length-(Math.max(h.lastIndexOf("\r"),h.lastIndexOf(`
5613`))+1))}const o="#".repeat(s),l=r.enter("headingAtx"),c=r.enter("phrasing");i.move(o+" ");let u=r.containerPhrasing(e,{before:"# ",after:`
5614`,...i.current()});return/^[\t ]/.test(u)&&(u=$p(u.charCodeAt(0))+u.slice(1)),u=u?o+" "+u:o,r.options.closeAtx&&(u+=" "+o),c(),l(),u}J3.peek=cG;function J3(e){return e.value||""}function cG(){return"<"}X3.peek=uG;function X3(e,t,r,n){const s=N1(r),i=s==='"'?"Quote":"Apostrophe",o=r.enter("image");let l=r.enter("label");const c=r.createTracker(n);let u=c.move("![");return u+=c.move(r.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(r.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(l=r.enter("destinationRaw"),u+=c.move(r.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),l(),e.title&&(l=r.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(r.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),l()),u+=c.move(")"),o(),u}function uG(){return"!"}Z3.peek=dG;function Z3(e,t,r,n){const s=e.referenceType,i=r.enter("imageReference");let o=r.enter("label");const l=r.createTracker(n);let c=l.move("![");const u=r.safe(e.alt,{before:c,after:"]",...l.current()});c+=l.move(u+"]["),o();const d=r.stack;r.stack=[],o=r.enter("reference");const p=r.safe(r.associationId(e),{before:c,after:"]",...l.current()});return o(),r.stack=d,i(),s==="full"||!u||u!==p?c+=l.move(p+"]"):s==="shortcut"?c=c.slice(0,-1):c+=l.move("]"),c}function dG(){return"!"}Q3.peek=pG;function Q3(e,t,r){let n=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(n);)s+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++i<r.unsafe.length;){const o=r.unsafe[i],l=r.compilePattern(o);let c;if(o.atBreak)for(;c=l.exec(n);){let u=c.index;n.charCodeAt(u)===10&&n.charCodeAt(u-1)===13&&u--,n=n.slice(0,u)+" "+n.slice(c.index+1)}}return s+n+s}function pG(){return"`"}function eI(e,t){const r=f1(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}tI.peek=hG;function tI(e,t,r,n){const s=N1(r),i=s==='"'?"Quote":"Apostrophe",o=r.createTracker(n);let l,c;if(eI(e,r)){const d=r.stack;r.stack=[],l=r.enter("autolink");let p=o.move("<");return p+=o.move(r.containerPhrasing(e,{before:p,after:">",...o.current()})),p+=o.move(">"),l(),r.stack=d,p}l=r.enter("link"),c=r.enter("label");let u=o.move("[");return u+=o.move(r.containerPhrasing(e,{before:u,after:"](",...o.current()})),u+=o.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=r.enter("destinationLiteral"),u+=o.move("<"),u+=o.move(r.safe(e.url,{before:u,after:">",...o.current()})),u+=o.move(">")):(c=r.enter("destinationRaw"),u+=o.move(r.safe(e.url,{before:u,after:e.title?" ":")",...o.current()}))),c(),e.title&&(c=r.enter(`title${i}`),u+=o.move(" "+s),u+=o.move(r.safe(e.title,{before:u,after:s,...o.current()})),u+=o.move(s),c()),u+=o.move(")"),l(),u}function hG(e,t,r){return eI(e,r)?"<":"["}nI.peek=fG;function nI(e,t,r,n){const s=e.referenceType,i=r.enter("linkReference");let o=r.enter("label");const l=r.createTracker(n);let c=l.move("[");const u=r.containerPhrasing(e,{before:c,after:"]",...l.current()});c+=l.move(u+"]["),o();const d=r.stack;r.stack=[],o=r.enter("reference");const p=r.safe(r.associationId(e),{before:c,after:"]",...l.current()});return o(),r.stack=d,i(),s==="full"||!u||u!==p?c+=l.move(p+"]"):s==="shortcut"?c=c.slice(0,-1):c+=l.move("]"),c}function fG(){return"["}function k1(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function mG(e){const t=k1(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function gG(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function rI(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function xG(e,t,r,n){const s=r.enter("list"),i=r.bulletCurrent;let o=e.ordered?gG(r):k1(r);const l=e.ordered?o==="."?")":".":mG(r);let c=t&&r.bulletLastUsed?o===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((o==="*"||o==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(c=!0),rI(r)===o&&d){let p=-1;for(;++p<e.children.length;){const h=e.children[p];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){c=!0;break}}}}c&&(o=l),r.bulletCurrent=o;const u=r.containerFlow(e,n);return r.bulletLastUsed=o,r.bulletCurrent=i,s(),u}function yG(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function bG(e,t,r,n){const s=yG(r);let i=r.bulletCurrent||k1(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let o=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);const l=r.createTracker(n);l.move(i+" ".repeat(o-i.length)),l.shift(o);const c=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,l.current()),d);return c(),u;function d(p,h,f){return h?(f?"":" ".repeat(o))+p:(f?i:i+" ".repeat(o-i.length))+p}}function vG(e,t,r,n){const s=r.enter("paragraph"),i=r.enter("phrasing"),o=r.containerPhrasing(e,n);return i(),s(),o}const wG=ux(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function jG(e,t,r,n){return(e.children.some(function(o){return wG(o)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function NG(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}sI.peek=kG;function sI(e,t,r,n){const s=NG(r),i=r.enter("strong"),o=r.createTracker(n),l=o.move(s+s);let c=o.move(r.containerPhrasing(e,{after:s,before:l,...o.current()}));const u=c.charCodeAt(0),d=Rm(n.before.charCodeAt(n.before.length-1),u,s);d.inside&&(c=$p(u)+c.slice(1));const p=c.charCodeAt(c.length-1),h=Rm(n.after.charCodeAt(0),p,s);h.inside&&(c=c.slice(0,-1)+$p(p));const f=o.move(s+s);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},l+c+f}function kG(e,t,r){return r.options.strong||"*"}
vendor: 6,868 bytes, lines 5614-5616
5614function SG(e,t,r,n){return r.safe(e.value,n)}function CG(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function PG(e,t,r){const n=(rI(r)+(r.options.ruleSpaces?" ":"")).repeat(CG(r));return r.options.ruleSpaces?n.slice(0,-1):n}const aI={blockquote:JV,break:r2,code:nG,definition:sG,emphasis:Y3,hardBreak:r2,heading:lG,html:J3,image:X3,imageReference:Z3,inlineCode:Q3,link:tI,linkReference:nI,list:xG,listItem:bG,paragraph:vG,root:jG,strong:sI,text:SG,thematicBreak:PG};function AG(){return{enter:{table:_G,tableData:s2,tableHeader:s2,tableRow:EG},exit:{codeText:IG,table:TG,tableData:Wy,tableHeader:Wy,tableRow:Wy}}}function _G(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function TG(e){this.exit(e),this.data.inTable=void 0}function EG(e){this.enter({type:"tableRow",children:[]},e)}function Wy(e){this.exit(e)}function s2(e){this.enter({type:"tableCell",children:[]},e)}function IG(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,OG));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function OG(e,t){return t==="|"?t:e}function RG(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,s=t.stringLength,i=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
5615`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[	 :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:h,table:o,tableCell:c,tableRow:l}};function o(f,x,g,y){return u(d(f,g,y),f.align)}function l(f,x,g,y){const b=p(f,g,y),v=u([b]);return v.slice(0,v.indexOf(`
5616`))}function c(f,x,g,y){const b=g.enter("tableCell"),v=g.enter("phrasing"),k=g.containerPhrasing(f,{...y,before:i,after:i});return v(),b(),k}function u(f,x){return KV(f,{align:x,alignDelimiters:n,padding:r,stringLength:s})}function d(f,x,g){const y=f.children;let b=-1;const v=[],k=x.enter("table");for(;++b<y.length;)v[b]=p(y[b],x,g);return k(),v}function p(f,x,g){const y=f.children;let b=-1;const v=[],k=x.enter("tableRow");for(;++b<y.length;)v[b]=c(y[b],f,x,g);return k(),v}function h(f,x,g){let y=aI.inlineCode(f,x,g);return g.stack.includes("tableCell")&&(y=y.replace(/\|/g,"\\$&")),y}}function DG(){return{exit:{taskListCheckValueChecked:a2,taskListCheckValueUnchecked:a2,paragraph:LG}}}function MG(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:$G}}}function a2(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function LG(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const s=t.children;let i=-1,o;for(;++i<s.length;){const l=s[i];if(l.type==="paragraph"){o=l;break}}o===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function $G(e,t,r,n){const s=e.children[0],i=typeof e.checked=="boolean"&&s&&s.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",l=r.createTracker(n);i&&l.move(o);let c=aI.listItem(e,t,r,{...n,...l.current()});return i&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),c;function u(d){return d+o}}function FG(){return[xV(),$V(),zV(),AG(),DG()]}function BG(e){return{extensions:[yV(),FV(e),qV(),RG(e),MG()]}}const UG={tokenize:GG,partial:!0},iI={tokenize:KG,partial:!0},oI={tokenize:YG,partial:!0},lI={tokenize:JG,partial:!0},zG={tokenize:XG,partial:!0},cI={name:"wwwAutolink",tokenize:WG,previous:dI},uI={name:"protocolAutolink",tokenize:VG,previous:pI},bo={name:"emailAutolink",tokenize:HG,previous:hI},Ui={};function qG(){return{text:Ui}}let Cl=48;for(;Cl<123;)Ui[Cl]=bo,Cl++,Cl===58?Cl=65:Cl===91&&(Cl=97);Ui[43]=bo;Ui[45]=bo;Ui[46]=bo;Ui[95]=bo;Ui[72]=[bo,uI];Ui[104]=[bo,uI];Ui[87]=[bo,cI];Ui[119]=[bo,cI];function HG(e,t,r){const n=this;let s,i;return o;function o(p){return!w0(p)||!hI.call(n,n.previous)||S1(n.events)?r(p):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),l(p))}function l(p){return w0(p)?(e.consume(p),l):p===64?(e.consume(p),c):r(p)}function c(p){return p===46?e.check(zG,d,u)(p):p===45||p===95||Fs(p)?(i=!0,e.consume(p),c):d(p)}function u(p){return e.consume(p),s=!0,c}function d(p){return i&&s&&Ys(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(p)):r(p)}}function WG(e,t,r){const n=this;return s;function s(o){return o!==87&&o!==119||!dI.call(n,n.previous)||S1(n.events)?r(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(UG,e.attempt(iI,e.attempt(oI,i),r),r)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function VG(e,t,r){const n=this;let s="",i=!1;return o;function o(p){return(p===72||p===104)&&pI.call(n,n.previous)&&!S1(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(p),e.consume(p),l):r(p)}function l(p){if(Ys(p)&&s.length<5)return s+=String.fromCodePoint(p),e.consume(p),l;if(p===58){const h=s.toLowerCase();if(h==="http"||h==="https")return e.consume(p),c}return r(p)}function c(p){return p===47?(e.consume(p),i?u:(i=!0,c)):r(p)}function u(p){return p===null||Em(p)||br(p)||mc(p)||ox(p)?r(p):e.attempt(iI,e.attempt(oI,d),r)(p)}function d(p){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(p)}}function GG(e,t,r){let n=0;return s;function s(o){return(o===87||o===119)&&n<3?(n++,e.consume(o),s):o===46&&n===3?(e.consume(o),i):r(o)}function i(o){return o===null?r(o):t(o)}}function KG(e,t,r){let n,s,i;return o;function o(u){return u===46||u===95?e.check(lI,c,l)(u):u===null||br(u)||mc(u)||u!==45&&ox(u)?c(u):(i=!0,e.consume(u),o)}function l(u){return u===95?n=!0:(s=n,n=void 0),e.consume(u),o}function c(u){return s||n||!i?r(u):t(u)}}function YG(e,t){let r=0,n=0;return s;function s(o){return o===40?(r++,e.consume(o),s):o===41&&n<r?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(lI,t,i)(o):o===null||br(o)||mc(o)?t(o):(e.consume(o),s)}function i(o){return o===41&&n++,e.consume(o),s}}function JG(e,t,r){return n;function n(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(e.consume(l),n):l===38?(e.consume(l),i):l===93?(e.consume(l),s):l===60||l===null||br(l)||mc(l)?t(l):r(l)}function s(l){return l===null||l===40||l===91||br(l)||mc(l)?t(l):n(l)}function i(l){return Ys(l)?o(l):r(l)}function o(l){return l===59?(e.consume(l),n):Ys(l)?(e.consume(l),o):r(l)}}
vendor: 6,062 bytes, line 5616
5616function XG(e,t,r){return n;function n(i){return e.consume(i),s}function s(i){return Fs(i)?r(i):t(i)}}function dI(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||br(e)}function pI(e){return!Ys(e)}function hI(e){return!(e===47||w0(e))}function w0(e){return e===43||e===45||e===46||e===95||Fs(e)}function S1(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const ZG={tokenize:iK,partial:!0};function QG(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:rK,continuation:{tokenize:sK},exit:aK}},text:{91:{name:"gfmFootnoteCall",tokenize:nK},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:eK,resolveTo:tK}}}}function eK(e,t,r){const n=this;let s=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let o;for(;s--;){const c=n.events[s][1];if(c.type==="labelImage"){o=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return l;function l(c){if(!o||!o._balanced)return r(c);const u=oi(n.sliceSerialize({start:o.end,end:n.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?r(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function tK(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},l=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...l),e}function nK(e,t,r){const n=this,s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,o;return l;function l(p){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),c}function c(p){return p!==94?r(p):(e.enter("gfmFootnoteCallMarker"),e.consume(p),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(p){if(i>999||p===93&&!o||p===null||p===91||br(p))return r(p);if(p===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return s.includes(oi(n.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(p)}return br(p)||(o=!0),i++,e.consume(p),p===92?d:u}function d(p){return p===91||p===92||p===93?(e.consume(p),i++,u):u(p)}}function rK(e,t,r){const n=this,s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,o=0,l;return c;function c(x){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(x){return x===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(x)}function d(x){if(o>999||x===93&&!l||x===null||x===91||br(x))return r(x);if(x===93){e.exit("chunkString");const g=e.exit("gfmFootnoteDefinitionLabelString");return i=oi(n.sliceSerialize(g)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return br(x)||(l=!0),o++,e.consume(x),x===92?p:d}function p(x){return x===91||x===92||x===93?(e.consume(x),o++,d):d(x)}function h(x){return x===58?(e.enter("definitionMarker"),e.consume(x),e.exit("definitionMarker"),s.includes(i)||s.push(i),zn(e,f,"gfmFootnoteDefinitionWhitespace")):r(x)}function f(x){return t(x)}}function sK(e,t,r){return e.check(Th,t,e.attempt(ZG,t,r))}function aK(e){e.exit("gfmFootnoteDefinition")}function iK(e,t,r){const n=this;return zn(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const o=n.events[n.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):r(i)}}function oK(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:s};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function s(o,l){let c=-1;for(;++c<o.length;)if(o[c][0]==="enter"&&o[c][1].type==="strikethroughSequenceTemporary"&&o[c][1]._close){let u=c;for(;u--;)if(o[u][0]==="exit"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._open&&o[c][1].end.offset-o[c][1].start.offset===o[u][1].end.offset-o[u][1].start.offset){o[c][1].type="strikethroughSequence",o[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},o[u][1].start),end:Object.assign({},o[c][1].end)},p={type:"strikethroughText",start:Object.assign({},o[u][1].end),end:Object.assign({},o[c][1].start)},h=[["enter",d,l],["enter",o[u][1],l],["exit",o[u][1],l],["enter",p,l]],f=l.parser.constructs.insideSpan.null;f&&va(h,h.length,0,lx(f,o.slice(u+1,c),l)),va(h,h.length,0,[["exit",p,l],["enter",o[c][1],l],["exit",o[c][1],l],["exit",d,l]]),va(o,u-1,c-u+3,h),c=u+h.length-2;break}}for(c=-1;++c<o.length;)o[c][1].type==="strikethroughSequenceTemporary"&&(o[c][1].type="data");return o}function i(o,l,c){const u=this.previous,d=this.events;let p=0;return h;function h(x){return u===126&&d[d.length-1][1].type!=="characterEscape"?c(x):(o.enter("strikethroughSequenceTemporary"),f(x))}function f(x){const g=Pu(u);if(x===126)return p>
vendor: 5,255 bytes, line 5616
56161?c(x):(o.consume(x),p++,f);if(p<2&&!r)return c(x);const y=o.exit("strikethroughSequenceTemporary"),b=Pu(x);return y._open=!b||b===2&&!!g,y._close=!g||g===2&&!!b,l(x)}}}class lK{constructor(){this.map=[]}add(t,r,n){cK(this,t,r,n)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let s=n.pop();for(;s;){for(const i of s)t.push(i);s=n.pop()}this.map.length=0}}function cK(e,t,r,n){let s=0;if(!(r===0&&n.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=r,e.map[s][2].push(...n);return}s+=1}e.map.push([t,r,n])}}function uK(e,t){let r=!1;const n=[];for(;t<e.length;){const s=e[t];if(r){if(s[0]==="enter")s[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=n.length-1;n[i]=n[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function dK(){return{flow:{null:{name:"table",tokenize:pK,resolveAll:hK}}}}function pK(e,t,r){const n=this;let s=0,i=0,o;return l;function l(A){let P=n.events.length-1;for(;P>-1;){const I=n.events[P][1].type;if(I==="lineEnding"||I==="linePrefix")P--;else break}const E=P>-1?n.events[P][1].type:null,_=E==="tableHead"||E==="tableRow"?w:c;return _===w&&n.parser.lazy[n.now().line]?r(A):_(A)}function c(A){return e.enter("tableHead"),e.enter("tableRow"),u(A)}function u(A){return A===124||(o=!0,i+=1),d(A)}function d(A){return A===null?r(A):Lt(A)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),f):r(A):_n(A)?zn(e,d,"whitespace")(A):(i+=1,o&&(o=!1,s+=1),A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),o=!0,d):(e.enter("data"),p(A)))}function p(A){return A===null||A===124||br(A)?(e.exit("data"),d(A)):(e.consume(A),A===92?h:p)}function h(A){return A===92||A===124?(e.consume(A),p):p(A)}function f(A){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(A):(e.enter("tableDelimiterRow"),o=!1,_n(A)?zn(e,x,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):x(A))}function x(A){return A===45||A===58?y(A):A===124?(o=!0,e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),g):j(A)}function g(A){return _n(A)?zn(e,y,"whitespace")(A):y(A)}function y(A){return A===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),b):A===45?(i+=1,b(A)):A===null||Lt(A)?N(A):j(A)}function b(A){return A===45?(e.enter("tableDelimiterFiller"),v(A)):j(A)}function v(A){return A===45?(e.consume(A),v):A===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),k):(e.exit("tableDelimiterFiller"),k(A))}function k(A){return _n(A)?zn(e,N,"whitespace")(A):N(A)}function N(A){return A===124?x(A):A===null||Lt(A)?!o||s!==i?j(A):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(A)):j(A)}function j(A){return r(A)}function w(A){return e.enter("tableRow"),S(A)}function S(A){return A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),S):A===null||Lt(A)?(e.exit("tableRow"),t(A)):_n(A)?zn(e,S,"whitespace")(A):(e.enter("data"),T(A))}function T(A){return A===null||A===124||br(A)?(e.exit("data"),S(A)):(e.consume(A),A===92?C:T)}function C(A){return A===92||A===124?(e.consume(A),T):T(A)}}function hK(e,t){let r=-1,n=!0,s=0,i=[0,0,0,0],o=[0,0,0,0],l=!1,c=0,u,d,p;const h=new lK;for(;++r<e.length;){const f=e[r],x=f[1];f[0]==="enter"?x.type==="tableHead"?(l=!1,c!==0&&(i2(h,t,c,u,d),d=void 0,c=0),u={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},h.add(r,0,[["enter",u,t]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(n=!0,p=void 0,i=[0,0,0,0],o=[0,r+1,0,0],l&&(l=!1,d={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)},h.add(r,0,[["enter",d,t]])),s=x.type==="tableDelimiterRow"?2:d?3:1):s&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(n=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],p=wf(h,t,i,s,void 0,p),i=[0,0,0,0]),o[2]=r)):x.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(o[0]=o[1],p=wf(h,t,i,s,void 0,p)),i=o,o=[i[1],r,0,0])):x.type==="tableHead"?(l=!0,c=r):x.type==="tableRow"||x.type==="tableDelimiterRow"?(c=r,i[1]!==0?(o[0]=o[1],p=wf(h,t,i,s,r,p)):o[1]!==0&&(p=wf(h,t,o,s,r,p)),s=0):s&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(o[3]=r)}for(c!==0&&i2(h,t,c,u,d),h.consume(t.events),r=-1;++r<t.events.length;){const f=t.events[r];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=uK(t.events,r))}return e}function wf(e,t,r,n,s,i){const o=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",l="tableContent";r[0]!==0&&(i.end=Object.assign({},eu(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const c=eu(t.events,r[1]);if(i={type:o,start:Object.assign({},c),end:Object.assign({},c)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const u=eu(t.events,r[2]),d=eu(t.events,r[3]),p={type:l,start:Object.assign({},u),end:Object.assign({},d)};
5616if(e.add(r[2],0,[["enter",p,t]]),n!==2){const h=t.events[r[2]],f=t.events[r[3]];if(h[1].end=Object.assign({},f[1].end),h[1].type="chunkText",h[1].contentType="text",r[3]>r[2]+1){const x=r[2]+1,g=r[3]-r[2]-1;e.add(x,g,[])}}e.add(r[3]+1,0,[["exit",p,t]])}return s!==void 0&&(i.end=Object.assign({},eu(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function i2(e,t,r,n,s){const i=[],o=eu(t.events,r);s&&(s.end=Object.assign({},o),i.push(["exit",s,t])),n.end=Object.assign({},o),i.push(["exit",n,t]),e.add(r+1,0,i)}function eu(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const fK={name:"tasklistCheck",tokenize:gK};function mK(){return{text:{91:fK}}}function gK(e,t,r){const n=this;return s;function s(c){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),i)}function i(c){return br(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),o):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),o):r(c)}function o(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),l):r(c)}function l(c){return Lt(c)?t(c):_n(c)?e.check({tokenize:xK},t,r)(c):r(c)}}function xK(e,t,r){return zn(e,n,"whitespace");function n(s){return s===null?r(s):t(s)}}function yK(e){return N3([qG(),QG(),oK(e),dK(),mK()])}const bK={};function vK(e){const t=this,r=e||bK,n=t.data(),s=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),o=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);s.push(yK(r)),i.push(FG()),o.push(BG(r))}function tp(e){var s,i;const t=[];let r=0;for(const o of e){const l=o.content,c=o.filename,u=/(?:app|router|server)\.(get|post|put|delete|patch)\s*\(\s*['"`]([^'"`]+)['"`]/gi;let d;for(;(d=u.exec(l))!==null;)t.push({id:`api-${r++}`,method:d[1].toUpperCase(),path:d[2],description:Hc(d[2],d[1].toUpperCase()),filename:c,params:Vy(d[2])});const p=/export\s+(?:async\s+)?function\s+(GET|POST|PUT|DELETE|PATCH)\s*\(/gi;for(;(d=p.exec(l))!==null;){const g=wK(c);t.push({id:`api-${r++}`,method:d[1].toUpperCase(),path:g,description:Hc(g,d[1].toUpperCase()),filename:c})}const h=/fetch\s*\(\s*['"`]([^'"`]+)['"`](?:\s*,\s*\{[^}]*method\s*:\s*['"`](GET|POST|PUT|DELETE|PATCH)['"`])?/gi;for(;(d=h.exec(l))!==null;){const g=d[1];g.startsWith("http")&&!g.includes("/api/")||t.push({id:`api-${r++}`,method:((s=d[2])==null?void 0:s.toUpperCase())||"GET",path:g,description:Hc(g,((i=d[2])==null?void 0:i.toUpperCase())||"GET"),filename:c,params:Vy(g)})}if(/serve\s*\(\s*async\s*\(\s*req\s*\)/gi.test(l)){const g=/req\.method\s*===?\s*['"`](GET|POST|PUT|DELETE|PATCH)['"`]/gi,y=[];for(;(d=g.exec(l))!==null;)y.push(d[1].toUpperCase());const b=`/functions/v1/${c.split("/").filter(v=>v!=="index.ts"&&v!=="index.js").pop()||c}`;if(y.length>0)for(const v of y)t.push({id:`api-${r++}`,method:v,path:b,description:Hc(b,v),filename:c});else t.push({id:`api-${r++}`,method:"POST",path:b,description:Hc(b,"POST"),filename:c})}const x=/\/\/\s*(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)/gi;for(;(d=x.exec(l))!==null;)t.find(y=>y.method===d[1].toUpperCase()&&y.path===d[2])||t.push({id:`api-${r++}`,method:d[1].toUpperCase(),path:d[2],description:Hc(d[2],d[1].toUpperCase()),filename:c,params:Vy(d[2])})}const n=new Set;return t.filter(o=>{const l=`${o.method}:${o.path}`;return n.has(l)?!1:(n.add(l),!0)})}function Vy(e){const t=[],r=/:(\w+)|\[(\w+)\]|\{(\w+)\}/g;let n;for(;(n=r.exec(e))!==null;)t.push(n[1]||n[2]||n[3]);return t.length>0?t:void 0}function wK(e){const t=e.match(/api\/(.+?)(?:\/route|\/index)?\.\w+$/);return t?`/api/${t[1]}`:`/${e.replace(/\.\w+$/,"").split("/").pop()||e}`}function Hc(e,t){const n=(e.split("/").filter(i=>i&&!i.startsWith(":")&&!i.startsWith("[")&&i!=="api"&&i!=="v1"&&i!=="functions").pop()||"resource").replace(/[-_]/g," ");return{GET:`Retrieve ${n}`,POST:`Create ${n}`,PUT:`Update ${n}`,DELETE:`Delete ${n}`,PATCH:`Partially update ${n}`}[t]||`${t} ${n}`}function np(e){var c;const t=[],r=[];let n=0,s=0;const i=e.filter(u=>u.language==="sql"||u.content.match(/CREATE\s+TABLE/i));for(const u of i){const d=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?["']?(\w+)["']?\s*\(([\s\S]*?)\)\s*;/gi;let p;for(;(p=d.exec(u.content))!==null;){const h=p[1],f=p[2],x=[],g=f.match(/PRIMARY\s+KEY\s*\(\s*([^)]+)\)/i),y=g?g[1].split(",").map(v=>v.trim().replace(/["']/g,"")):[],b=f.split(",").map(v=>v.trim()).filter(v=>v.length>0);for(const v of b){if(/^\s*(PRIMARY\s+KEY|UNIQUE|CHECK|CONSTRAINT|FOREIGN\s+KEY)/i.test(v)){const _=v.match(/FOREIGN\s+KEY\s*\(\s*["']?(\w+)["']?\s*\)\s*REFERENCES\s+(?:public\.)?["']?(\w+)["']?\s*\(\s*["']?(\w+)["']?\s*\)/i);if(_){const I=x.find(D=>D.name===_[1]);I&&(I.isForeignKey=!0,I.referencesTable=_[2],I.referencesColumn=_[3]),r.push({id:`rel-${s++}`,fromTable:h,fromColumn:_[1],toTable:_[2],toColumn:_[3],type:"many-to-one"})}continue}const k=v.match(/^\s*["']?(\w+)["']?\s+([A-Z][A-Z0-9_ ()]+?)(?:\s+(.*?))?$/i);if(!k)continue;const N=k[1];let j=k[2].trim();const w=k[3]||"";j=j.replace(/\s+(NOT|NULL|DEFAULT|PRIMARY|UNIQUE|REFERENCES|CHECK|CONSTRAINT).*/i,"").trim();const S=/PRIMARY\s+KEY/i.test(w)||y.includes(N),T=!/NOT\s+NULL/i.test(w)&&!S,C=/REFERENCES/i.test(w);let A,P;if(C){const _=w.match(/REFERENCES\s+(?:public\.)?["']?(\w+)["']?\s*\(\s*["']?(\w+)["']?\s*\)/i);_&&(A=_[1],P=_[2],r.push({id:`rel-${s++}`,fromTable:h,fromColumn:N,toTable:_[1],toColumn:_[2],type:"many-to-one"}))}const E=w.match(/DEFAULT\s+(.+?)(?:\s+(?:NOT|NULL|PRIMARY|UNIQUE|REFERENCES|CHECK|CONSTRAINT)|$)/i);x.push({name:N,type:j.toUpperCase(),isPrimaryKey:S,isForeignKey:C,isNullable:T,defaultValue:(c=E==null?void 0:E[1])==null?void 0:c.trim(),referencesTable:A,referencesColumn:P})}x.length>0&&t.push({id:`table-${n++}`,name:h,columns:x,filename:u.filename})}}const o=new Set;return{tables:t.filter(u=>o.has(u.name)?!1:(o.add(u.name),!0)),relationships:r}}const vp="__custom__";function o2(e){return String(e).toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,60)||"opt"}function jK(e,t){if(typeof e=="string"){const r=e.trim();return r?{value:o2(r)||`opt_${t}`,label:r}:null}if(e&&typeof e=="object"){const r=e,n=typeof r.label=="string"?r.label:typeof r.value=="string"?r.value:"";if(!n)return null;const i={value:typeof r.value=="string"&&r.value?r.value:o2(n)||`opt_${t}`,label:n};
5616return typeof r.icon=="string"&&(i.icon=r.icon),typeof r.description=="string"&&(i.description=r.description),i}return null}function NK(e,t){if(!e||typeof e!="object")return null;const r=e,n=typeof r.id=="string"&&r.id?r.id:`q${t+1}`,s=typeof r.label=="string"&&r.label?r.label:"",i=typeof r.question=="string"&&r.question?r.question:s;if(!i)return null;const l=(typeof r.type=="string"?r.type.toLowerCase():"choice")==="text"||r.freeText===!0,c=n==="next_phase"||/next\s*phase/i.test(s||i),u=r.multiSelect===!0||r.type==="multi"||c,d=r.allowCustom===!0||c;let p=[];return Array.isArray(r.options)&&(p=r.options.map((h,f)=>jK(h,f)).filter(h=>h!==null)),{id:n,label:s||i,question:i,options:p,multiSelect:u,freeText:l,allowCustom:d}}function kK(e){const r=/```questions\s*\n([\s\S]*?)```/.exec(e);if(!r)return null;const n=i=>{try{const o=JSON.parse(i);if(!o||typeof o!="object")return null;const l=Array.isArray(o.questions)?o.questions:[],c=typeof o.intro=="string"?o.intro:"",u=l.map((d,p)=>NK(d,p)).filter(d=>d!==null);return u.length===0?null:{intro:c,questions:u}}catch{return null}},s=r[1].trim();return n(s)??n(s.replace(/,\s*}/g,"}").replace(/,\s*]/g,"]"))}function SK(e){return e.replace(/```questions\s*\n[\s\S]*?```/g,"").trim()}function CK(e,t,r={}){const n=[];for(const s of e){if(s.freeText){const u=(r[s.id]||"").trim();if(!u)continue;n.push(`**${s.label}:** ${u}`);continue}const i=t[s.id]||[],o=(r[s.id]||"").trim(),l=[];for(const u of i){if(u===vp)continue;const d=s.options.find(p=>p.value===u);l.push((d==null?void 0:d.label)??u)}if(o&&l.push(o),l.length===0)continue;const c=s.multiSelect&&l.length>1?`${s.label} (selected ${l.length})`:s.label;n.push(`**${c}:** ${l.join(", ")}`)}return n.join(`
5617`)}const PK={sparkles:Dn,palette:Ai,briefcase:$$,moon:a6,zap:hr,sun:k6,circle:U_,leaf:fu,layout:no,globe:Br,shield:os,rocket:Es,heart:Q$,star:jT,code:hp,database:Hn,image:ad,mail:nT,phone:p6,map:n6};function l2({option:e,isSelected:t,onToggle:r,index:n}){const s=e.icon?PK[e.icon]:null;return a.jsxs("button",{onClick:r,className:L("group w-full flex items-start gap-2.5 px-3 py-2 rounded-lg border text-left transition-all",t?"bg-primary/[0.06] border-primary/40 ring-1 ring-primary/20":"bg-card border-border/70 hover:border-primary/30 hover:bg-secondary/40"),children:[a.jsx("span",{className:L("shrink-0 mt-px w-5 h-5 rounded-md flex items-center justify-center text-[10px] font-mono font-semibold transition-all",t?"bg-primary text-primary-foreground":"bg-muted/70 text-muted-foreground group-hover:bg-muted"),children:t?a.jsx(Wn,{className:"w-3 h-3"}):n+1}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&a.jsx(s,{className:L("w-3.5 h-3.5 shrink-0",t?"text-primary":"text-muted-foreground")}),a.jsx("span",{className:L("text-[13px] font-medium leading-snug",t?"text-primary":"text-foreground"),children:e.label})]}),e.description&&a.jsx("p",{className:"text-[11px] text-muted-foreground/90 mt-0.5 leading-snug",children:e.description})]})]})}function AK({question:e,selections:t,customText:r,onSelect:n,onCustomTextChange:s}){if(e.freeText)return a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-primary font-semibold",children:e.label}),a.jsx("p",{className:"text-sm font-medium text-foreground mt-0.5",children:e.question})]}),a.jsx("textarea",{value:r,onChange:l=>s(l.target.value),placeholder:"Type your answer...",rows:2,className:"w-full text-sm rounded-xl border border-border bg-card px-3 py-2 text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:border-primary/40 focus:ring-1 focus:ring-primary/20 resize-y min-h-[40px]"})]});const i=t.includes(vp),o=e.allowCustom||e.id==="next_phase";return a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-primary font-semibold",children:e.label}),a.jsx("p",{className:"text-sm font-medium text-foreground mt-0.5",children:e.question})]}),a.jsxs("div",{className:"space-y-1",children:[e.options.map((l,c)=>
5617a.jsx(l2,{option:l,index:c,isSelected:t.includes(l.value),onToggle:()=>n(l.value)},l.value)),o&&a.jsx(l2,{option:{value:vp,label:"Other (write your own)",icon:void 0},index:e.options.length,isSelected:i,onToggle:()=>n(vp)})]}),i&&a.jsxs("div",{className:"flex items-start gap-2 pl-1",children:[a.jsx(uc,{className:"w-3.5 h-3.5 text-muted-foreground mt-2 shrink-0"}),a.jsx("textarea",{value:r,onChange:l=>s(l.target.value),placeholder:"Type your custom answer...",rows:2,className:"flex-1 text-sm rounded-xl border border-border bg-card px-3 py-2 text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:border-primary/40 focus:ring-1 focus:ring-primary/20 resize-y min-h-[40px]",autoFocus:!0})]}),e.multiSelect&&a.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"Select one or more"})]})}function _K({data:e,onSubmit:t,isSubmitted:r}){const[n,s]=m.useState({}),[i,o]=m.useState({}),l=(p,h,f)=>{s(x=>{const g=x[p]||[];return f?{...x,[p]:g.includes(h)?g.filter(y=>y!==h):[...g,h]}:{...x,[p]:g.includes(h)?[]:[h]}})},c=(p,h)=>{o(f=>({...f,[p]:h}))},u=e.questions.some(p=>{if(p.freeText)return(i[p.id]||"").trim().length>0;const h=n[p.id]||[];return h.includes(vp)?(i[p.id]||"").trim().length>0||h.length>1:h.length>0}),d=()=>{const p=CK(e.questions,n,i);t(p)};return a.jsxs("div",{className:L("space-y-4",r&&"opacity-60 pointer-events-none"),children:[e.intro&&a.jsx("p",{className:"text-sm text-foreground leading-relaxed",children:e.intro}),e.questions.map(p=>a.jsx(AK,{question:p,selections:n[p.id]||[],customText:i[p.id]||"",onSelect:h=>l(p.id,h,p.multiSelect),onCustomTextChange:h=>c(p.id,h)},p.id)),!r&&a.jsxs(Q,{onClick:d,disabled:!u,size:"sm",className:"w-full gap-2 rounded-xl",children:[a.jsx(Li,{className:"w-3.5 h-3.5"}),e.questions.some(p=>p.multiSelect)?"Submit Selected":"Submit Preferences"]})]})}function TK(e){const t=e.filter(n=>n.language==="sql"),r=[];for(const n of t){const s=n.content.split(/;\s*\n/).map(i=>i.trim()).filter(i=>i.length>0).map(i=>i.endsWith(";")?i:i+";");for(const i of s)/^\s*(CREATE|ALTER|DROP|INSERT|UPDATE|DELETE|TRUNCATE)\s/i.test(i)&&r.push(i)}return r}function EK(e){const t=[],r=[];for(const n of e)/^\s*(CREATE|ALTER|DROP)\s/i.test(n)?t.push(n):r.push(n);return{ddl:t,dml:r}}function IK(e){const t=[/```(?:json)\s+workflow\.json\s*\n([\s\S]*?)```/i,/```workflow\s*\n([\s\S]*?)```/i,/```json\s*\n(\{[\s\S]*?"steps"[\s\S]*?\})\s*```/i];for(const r of t){const n=e.match(r);if(n)try{const s=JSON.parse(n[1]);if(s.steps&&Array.isArray(s.steps))return{name:s.name||"Untitled Workflow",description:s.description||"",steps:s.steps.map((i,o)=>({id:i.id||`step-${o}`,type:i.type||"action",name:i.name||`Step ${o+1}`,description:i.description||"",config:i.config||{},next:i.next,condition:i.condition}))}}catch{}}return null}function OK(e){return e.replace(/[_\-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase()).trim()}function RK(e){const t=e.match(/```autodb[^\n]*\n/i);if(!t||t.index===void 0)return null;const r=t.index+t[0].length,n=e.slice(r),s=n.search(/\n```[^\n]*/),i=s===-1?n:n.slice(0,s),o=i.indexOf("{"),l=i.lastIndexOf("}");return o===-1||l===-1||l<=o?null:i.slice(o,l+1).trim()}function DK(e){const t=RK(e);if(!t)return null;try{const r=JSON.parse(t),n=Array.isArray(r.tables)?r.tables:[];if(n.length===0)return null;const s=n.map(o=>{const l=String(o.tableName||o.name||"").trim(),u=(Array.isArray(o.columns)?o.columns:[]).map(d=>({name:String(d.name||"").trim(),type:String(d.type||"").trim(),nullable:typeof d.nullable=="boolean"?d.nullable:void 0,default_value:typeof d.default_value=="string"?d.default_value:void 0,is_primary:typeof d.is_primary=="boolean"?d.is_primary:void 0,description:typeof d.description=="string"?d.description:void 0})).filter(d=>d.name&&d.type);return!l||u.length===0?null:{tableName:l,displayName:String(o.displayName||o.display_name||OK(l)).trim(),description:typeof o.description=="string"?o.description:void 0,columns:u}}).filter(o=>o!==null);if(s.length===0)return null;const i=r.seedData&&typeof r.seedData=="object"?r.seedData:void 0;return{intro:typeof r.intro=="string"?r.intro:void 0,tables:s,seedData:i}}catch{return null}}function MK(e){return e.replace(/```autodb[\s\S]*?(?=\n```|$)/gi,"").replace(/^```\s*$/gm,"").trim()}function LK(e){const t=["✅ Approved schema creation:"];for(const r of e.tables)t.push(`  • **${r.displayName}** (${r.tableName}): ${r.columns.length} columns`);return t.join(`
5618`)}function $K(e){const t=e.match(/```secret_request\s*\n([\s\S]*?)\n```/);if(!t)return null;try{const r=JSON.parse(t[1]);if(r&&Array.isArray(r.secrets)&&r.secrets.length>0)return r}catch{}return null}function FK(e){return e.replace(/```secret_request\s*\n[\s\S]*?\n```/g,"").trim()}const fI=/```checkpoint\s*\n([\s\S]*?)\n```/i;function BK(e){const t=e.match(fI);if(!t)return null;const r=t[1].trim();try{const n=JSON.parse(r);return{completed:Array.isArray(n.completed)?n.completed.map(String):[],remaining:Array.isArray(n.remaining)?n.remaining.map(String):[],next:String(n.next||""),message:String(n.message||"Want me to continue building the rest?"),raw:r}}catch{return null}}function UK(e){return e.replace(fI,"").replace(/\n{3,}/g,`
5619
5620`).trim()}function zK(e){const t=e.completed.length?e.completed.map(n=>`- ${n}`).join(`
5621`):"(already built — see previous messages)",r=e.remaining.length?e.remaining.map(n=>`- ${n}`).join(`
5622`):"(the remaining parts of the app)";return`Continue the build. Here is where we stopped:
5623
5624ALREADY BUILT (do NOT regenerate these):
5625${t}
5626
5627STILL REMAINING (build these now):
5628${r}
5629
5630Focus next on: ${e.next||"the next logical chunk"}.
5631
5632Rules:
5633- Preserve all already-built files — do NOT re-emit them.
5634- Generate the remaining pages/features with the SAME design system, color scheme, and structure as before.
5635- If the remaining work is STILL too large to fit in one response, emit another \`\`\`checkpoint block and stop — I will click Continue again.
5636- Otherwise finish everything and emit a final "✅ Build Complete" summary.`}class ta{constructor(t,r,n){this.line=void 0,this.column=void 0,n!==void 0&&(this.index=void 0),this.line=t,this.column=r,n!==void 0&&(this.index=n)}}class Dm{constructor(t,r){Qe(this,"start");Qe(this,"end");Qe(this,"filename");Qe(this,"identifierName");this.start=t,this.end=r}}function Oa(e,t){const{line:r,column:n,index:s}=e;return new ta(r,n+t,s+t)}const c2="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",qK={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:c2},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:c2}},u2={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"cat
5636ch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},am=e=>e.type==="UpdateExpression"?u2.UpdateExpression[`${e.prefix}`]:u2[e.type],HK={AccessorIsGenerator:({kind:e})=>`A ${e}ter cannot be a generator.`,ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:({kind:e})=>`Missing initializer in ${e} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:({exportName:e})=>`\`${e}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName:e,exportName:t})=>`A string literal cannot be used as an exported binding without \`from\`.
5637- Did you mean \`export { '${e}' as '${t}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:e})=>`'${e==="ForInStatement"?"for-in":"for-of"}' loop variable declaration may not have an initializer.`,ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:({type:e})=>`Unsyntactic ${e==="BreakStatement"?"break":"continue"}.`,IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportBindingIsString:({importName:e})=>`A string literal cannot be used as an imported binding.
5638- Did you mean \`import { "${e}" as foo }\`?`,ImportCallArity:({phase:e})=>`\`import${e?`.${e}`:""}
5638()\` requires exactly one or two arguments.`,ImportCallNotNewExpression:({phase:e})=>`Cannot use new with import${e?`.${e}`:""}().`,ImportCallSpreadArgument:({phase:e})=>`\`...\` is not allowed in \`import${e?`.${e}`:""}()\`.`,IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDigit:({radix:e})=>`Expected number in radix ${e}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:e})=>`Escape sequence in keyword ${e}.`,InvalidIdentifier:({identifierName:e})=>`Invalid identifier ${e}.`,InvalidLhs:({ancestor:e})=>`Invalid left-hand side in ${am(e)}.`,InvalidLhsBinding:({ancestor:e})=>`Binding invalid left-hand side in ${am(e)}.`,InvalidLhsOptionalChaining:({ancestor:e})=>`Invalid optional chaining in the left-hand side of ${am(e)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:e})=>`Unexpected character '${e}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:e})=>`Private name #${e} is not defined.`,InvalidPropertyBindingPattern:"Binding member expression.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:({labelName:e})=>`Label '${e}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:({missingPlugin:e})=>`This experimental syntax requires enabling the parser plugin: ${e.map(t=>JSON.stringify(t)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:e})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${e.map(t=>JSON.stringify(t)).join(", ")}.`,MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:({key:e})=>`Duplicate key "${e}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:e})=>`An export name cannot include a lone surrogate, found '\\u${e.toString(16)}'.`,ModuleExportUndefined:({localName:e})=>`Export '${e}' is not defined.`,MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:({identifierName:e})=>`Private names are only allowed in property accesses (\`obj.#${e}\`) or in \`in\` expressions (\`#${e} in obj\`).`,PrivateNameRedeclaration:({identifierName:e})=>`Duplicate private name #${e}.`,RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode co
5638de, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperCallNotNewExpression:"Cannot use new with super(...).",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:({keyword:e})=>`Unexpected keyword '${e}'.`,UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:({reservedWord:e})=>`Unexpected reserved word '${e}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:e,unexpected:t})=>`Unexpected token${t?` '${t}'.`:""}${e?`, expected "${e}"`:""}`,UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:({target:e,onlyValidPropertyName:t})=>`The only valid meta property for ${e} is ${e}.${t}.`,UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:e})=>`Identifier '${e}' has already been declared.`,VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},WK={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:e})=>`Assigning to '${e}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:e})=>`Binding '${e}' in strict mode.`,StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block.",StrictNumericEscape:"The only valid numeric escape in strict mode is '\\0'.",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode.",StrictWith:"'with' in strict mode."},VK={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:e})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(e)}\`.`},GK=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),KK={PipeTopicRequiresHackPipes:'Topic references are only supported when using the `"proposal": "hack"` version of the pipeline proposal.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:({token:e})=>`Invalid topic token ${e}. In order to use ${e} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${e}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:e})=>`Hack-style pipe body cannot be an unparenthesized ${am({type:e})}; please wrap it in parentheses.`,PipelineUnparenthesized:"Cannot mix binary operator with solo-await F#-style pipeline. Please wrap the pipeline in parentheses."},YK={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."};
5638function d2(e,t,r){Object.defineProperty(e,t,{enumerable:!1,configurable:!0,value:r})}function JK({toMessage:e,code:t,reasonCode:r,syntaxPlugin:n}){const s=r==="MissingPlugin"||r==="MissingOneOfPlugins";return function i(o,l,c){const u=new SyntaxError;return u.code=t,u.reasonCode=r,u.loc=o,u.pos=l,u.syntaxPlugin=n,s&&(u.missingPlugin=c.missingPlugin),d2(u,"clone",function(p={}){const{line:h,column:f,index:x=l}=p.loc??o;return i(new ta(h,f),x,{...c,...p.details})}),d2(u,"details",c),Object.defineProperty(u,"message",{configurable:!0,get(){const d=`${e(c)} (${o.line}:${o.column})`;return this.message=d,d},set(d){Object.defineProperty(this,"message",{value:d,writable:!0})}}),u}}function Za(e,t){if(Array.isArray(e))return n=>Za(n,e[0]);const r={};for(const n of Object.keys(e)){const s=e[n],{message:i,...o}=typeof s=="string"?{message:()=>s}:typeof s=="function"?{message:s}:s,l=typeof i=="string"?()=>i:i;r[n]=JK({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:n,toMessage:l,...t?{syntaxPlugin:t}:{},...o})}return r}const J={...Za(qK),...Za(HK),...Za(WK),...Za(VK),...Za`pipelineOperator`(KK),...Za`functionBind`(YK)};function XK(){return{sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:void 0,ranges:!1,locations:!0,tokens:!1,createImportExpressions:!0,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0}}function ZK(e){const t=XK();if(e==null)return t;if(e.annexB!=null&&e.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(const r of Object.keys(t))e[r]!=null&&(t[r]=e[r]);if(t.startLine===1)e.startIndex==null&&t.startColumn>0?t.startIndex=t.startColumn:e.startColumn==null&&t.startIndex>0&&(t.startColumn=t.startIndex);else if(e.startColumn==null||e.startIndex==null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(t.sourceType==="commonjs"){if(e.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(e.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(e.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return t}function Wc(e){const{start:t,end:r}=e.loc;return e.loc.start=new ta(t.line,t.column),e.loc.end=new ta(r.line,r.column),e}const QK=e=>class extends e{createPosition(r){return new ta(r.line,r.column)}parse(){const r=super.parse();return this.optionFlags&512&&(r.tokens=r.tokens.map(Wc)),Wc(r)}parseRegExpLiteral({pattern:r,flags:n}){let s=null;try{s=new RegExp(r,n)}catch{}const i=this.estreeParseLiteral(s);return i.regex={pattern:r,flags:n},i}parseBigIntLiteral(r){let n;try{n=BigInt(r)}catch{n=null}const s=this.estreeParseLiteral(n);return s.bigint=String(s.value||r),s}estreeParseLiteral(r){return this.parseLiteral(r,"Literal")}parseStringLiteral(r){return this.estreeParseLiteral(r)}parseNumericLiteral(r){return this.estreeParseLiteral(r)}parseNullLiteral(){return this.estreeParseLiteral(null)}parseBooleanLiteral(r){return this.estreeParseLiteral(r)}estreeParseChainExpression(r,n){const s=this.startNodeAtNode(r);return s.expression=r,this.finishNodeAtNode(s,"ChainExpression",n)}directiveToStmt(r){const n=r.value;delete r.value,this.castNodeTo(n,"Literal"),n.raw=n.extra.raw,n.value=n.extra.expressionValue;const s=this.castNodeTo(r,"ExpressionStatement");return s.expression=n,s.directive=n.extra.rawValue,delete n.extra,s}fillOptionalPropertiesForTSESLint(r){}cloneEstreeStringLiteral(r){const{start:n,end:s,loc:i,range:o,raw:l,value:c}=r,u=Object.create(r.constructor.prototype);return u.type="Literal",u.start=n,u.end=s,u.loc=i,u.range=o,u.raw=l,u.value=c,u}
5638initFunction(r,n){super.initFunction(r,n),r.expression=!1}checkDeclaration(r){r!=null&&this.isObjectProperty(r)?this.checkDeclaration(r.value):super.checkDeclaration(r)}getObjectOrClassMethodParams(r){return r.value.params}isValidDirective(r){var n;return r.type==="ExpressionStatement"&&r.expression.type==="Literal"&&typeof r.expression.value=="string"&&!((n=r.expression.extra)!=null&&n.parenthesized)}parseBlockBody(r,n,s,i,o){super.parseBlockBody(r,n,s,i,o);const l=r.directives.map(c=>this.directiveToStmt(c));r.body=l.concat(r.body),delete r.directives}parsePrivateName(){const r=super.parsePrivateName();return this.convertPrivateNameToPrivateIdentifier(r)}convertPrivateNameToPrivateIdentifier(r){const n=super.getPrivateNameSV(r);return delete r.id,r.name=n,this.castNodeTo(r,"PrivateIdentifier")}isPrivateName(r){return r.type==="PrivateIdentifier"}getPrivateNameSV(r){return r.name}parseLiteral(r,n){const s=super.parseLiteral(r,n);return s.raw=s.extra.raw,delete s.extra,s}parseFunctionBody(r,n,s=!1){super.parseFunctionBody(r,n,s),r.expression=r.body.type!=="BlockStatement"}parseMethod(r,n,s,i,o,l,c=!1){let u=this.startNode();u.kind=r.kind,u=super.parseMethod(u,n,s,i,o,l,c),delete u.kind;const{typeParameters:d}=r;d&&(delete r.typeParameters,u.typeParameters=d,this.resetStartLocationFromNode(u,d));const p=this.castNodeTo(u,this.hasPlugin("typescript")&&!u.body?"TSEmptyBodyFunctionExpression":"FunctionExpression");return r.value=p,l==="ClassPrivateMethod"&&(r.computed=!1),this.hasPlugin("typescript")&&r.abstract?(delete r.abstract,this.finishNode(r,"TSAbstractMethodDefinition")):l==="ObjectMethod"?(r.kind==="method"&&(r.kind="init"),r.shorthand=!1,this.finishNode(r,"Property")):this.finishNode(r,"MethodDefinition")}nameIsConstructor(r){return r.type==="Literal"?r.value==="constructor":super.nameIsConstructor(r)}parseClassProperty(...r){const n=super.parseClassProperty(...r);return n.abstract&&this.hasPlugin("typescript")?(delete n.abstract,this.castNodeTo(n,"TSAbstractPropertyDefinition")):this.castNodeTo(n,"PropertyDefinition"),n}parseClassPrivateProperty(...r){const n=super.parseClassPrivateProperty(...r);return n.abstract&&this.hasPlugin("typescript")?this.castNodeTo(n,"TSAbstractPropertyDefinition"):this.castNodeTo(n,"PropertyDefinition"),n.computed=!1,n}parseClassAccessorProperty(r){const n=super.parseClassAccessorProperty(r);return n.abstract&&this.hasPlugin("typescript")?(delete n.abstract,this.castNodeTo(n,"TSAbstractAccessorProperty")):this.castNodeTo(n,"AccessorProperty"),n}parseObjectProperty(r,n,s,i){const o=super.parseObjectProperty(r,n,s,i);return o&&(o.kind="init",this.castNodeTo(o,"Property")),o}finishObjectProperty(r){return r.kind="init",this.finishNode(r,"Property")}isValidLVal(r,n,s,i){return r==="Property"?"value":super.isValidLVal(r,n,s,i)}isAssignable(r,n){return r!=null&&this.isObjectProperty(r)?this.isAssignable(r.value,n):super.isAssignable(r,n)}toAssignable(r,n=!1){if(r!=null&&this.isObjectProperty(r)){const{key:s,value:i}=r;this.isPrivateName(s)&&this.classScope.usePrivateName(this.getPrivateNameSV(s),s.start),this.toAssignable(i,n)}else super.toAssignable(r,n)}toAssignableObjectExpressionProp(r,n,s){r.type==="Property"&&(r.kind==="get"||r.kind==="set")?this.raise(J.PatternHasAccessor,r.key):r.type==="Property"&&r.method?this.raise(J.PatternHasMethod,r.key):super.toAssignableObjectExpressionProp(r,n,s)}finishCallExpression(r,n){const s=super.finishCallExpression(r,n);return s.callee.type==="Import"?(this.castNodeTo(s,"ImportExpression"),s.source=s.arguments[0],s.options=s.arguments[1]??null,delete s.arguments,delete s.callee):s.type==="OptionalCallExpression"?this.castNodeTo(s,"CallExpression"):s.optional=!1,s}parseExport(r,n){var o;const s=this.state.lastTokStartLoc,i=super.parseExport(r,n);switch(i.type){case"ExportAllDeclaration":i.exported=null;break;case"ExportNamedDeclaration":i.specifiers.length===1&&i.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(i,"ExportAllDeclaration"),i.exported=i.specifiers[0].exported,delete i.specifiers);case"ExportDefaultDeclaration":{const{declaration:l}=i;(l==null?void 0:l.type)==="ClassDeclaration"&&((o=l.decorators)==null?void 0:o.length)>0&&l.start===i.start&&this.resetStartLocation(i,s)}break}return i}stopParseSubscript(r,n){const s=super.stopParseSubscript(r,n);return n.optionalChainMember?this.estreeParseChainExpression(s,r):s}parseMember(r,n,s,i,o){const l=super.parseMember(r,n,s,i,o);
5638return l.type==="OptionalMemberExpression"?this.castNodeTo(l,"MemberExpression"):l.optional=!1,l}isOptionalMemberExpression(r){return r.type==="ChainExpression"?r.expression.type==="MemberExpression":super.isOptionalMemberExpression(r)}hasPropertyAsPrivateName(r){return r.type==="ChainExpression"&&(r=r.expression),super.hasPropertyAsPrivateName(r)}isObjectProperty(r){return r.type==="Property"&&r.kind==="init"&&!r.method}isObjectMethod(r){return r.type==="Property"&&(r.method||r.kind==="get"||r.kind==="set")}castNodeTo(r,n){const s=super.castNodeTo(r,n);return this.fillOptionalPropertiesForTSESLint(s),s}cloneIdentifier(r){const n=super.cloneIdentifier(r);return this.fillOptionalPropertiesForTSESLint(n),n}cloneStringLiteral(r){return r.type==="Literal"?this.cloneEstreeStringLiteral(r):super.cloneStringLiteral(r)}finishNodeAt(r,n,s){return Wc(super.finishNodeAt(r,n,s))}finishNodeAtNode(r,n,s){return Wc(super.finishNodeAtNode(r,n,s))}finishNode(r,n){const s=super.finishNode(r,n);return this.fillOptionalPropertiesForTSESLint(s),s}resetStartLocation(r,n){super.resetStartLocation(r,n),Wc(r)}resetEndLocation(r,n=this.state.lastTokEndLoc){super.resetEndLocation(r,n),Wc(r)}},An=!0,nt=!0,Gy=!0,$d=!0,Io=!0,eY=!0;class mI{constructor(t,r={}){Qe(this,"label");Qe(this,"keyword");Qe(this,"beforeExpr");Qe(this,"startsExpr");Qe(this,"rightAssociative");Qe(this,"isLoop");Qe(this,"isAssign");Qe(this,"prefix");Qe(this,"postfix");Qe(this,"binop");this.label=t,this.keyword=r.keyword,this.beforeExpr=!!r.beforeExpr,this.startsExpr=!!r.startsExpr,this.rightAssociative=!!r.rightAssociative,this.isLoop=!!r.isLoop,this.isAssign=!!r.isAssign,this.prefix=!!r.prefix,this.postfix=!!r.postfix,this.binop=r.binop!=null?r.binop:null}}const C1=new Map;function Ln(e,t={}){t.keyword=e;const r=Ot(e,t);return C1.set(e,r),r}function Ks(e,t){return Ot(e,{beforeExpr:An,binop:t})}let wp=-1;const P1=[],A1=[],_1=[],T1=[],E1=[],I1=[];function Ot(e,t={}){return++wp,A1.push(e),_1.push(t.binop??-1),T1.push(t.beforeExpr??!1),E1.push(t.startsExpr??!1),I1.push(t.prefix??!1),P1.push(new mI(e,t)),wp}function Nn(e,t={}){return++wp,C1.set(e,wp),A1.push(e),_1.push(t.binop??-1),T1.push(t.beforeExpr??!1),E1.push(t.startsExpr??!1),I1.push(t.prefix??!1),P1.push(new mI("name",t)),wp}const tY={bracketL:Ot("[",{beforeExpr:An,startsExpr:nt}),bracketR:Ot("]"),braceL:Ot("{",{beforeExpr:An,startsExpr:nt}),braceBarL:Ot("{|",{beforeExpr:An,startsExpr:nt}),braceR:Ot("}"),braceBarR:Ot("|}"),parenL:Ot("(",{beforeExpr:An,startsExpr:nt}),parenR:Ot(")"),comma:Ot(",",{beforeExpr:An}),semi:Ot(";",{beforeExpr:An}),colon:Ot(":",{beforeExpr:An}),doubleColon:Ot("::",{beforeExpr:An}),dot:Ot("."),question:Ot("?",{beforeExpr:An}),questionDot:Ot("?."),arrow:Ot("=>",{beforeExpr:An}),template:Ot("template"),ellipsis:Ot("...",{beforeExpr:An}),backQuote:Ot("`",{startsExpr:nt}),dollarBraceL:Ot("${",{beforeExpr:An,startsExpr:nt}),templateTail:Ot("...`",{startsExpr:nt}),templateNonTail:Ot("...${",{beforeExpr:An,startsExpr:nt}),at:Ot("@"),hash:Ot("#",{startsExpr:nt}),interpreterDirective:Ot("#!..."),eq:Ot("=",{beforeExpr:An,isAssign:$d}),assign:Ot("_=",{beforeExpr:An,isAssign:$d}),slashAssign:Ot("_=",{beforeExpr:An,isAssign:$d}),xorAssign:Ot("_=",{beforeExpr:An,isAssign:$d}),moduloAssign:Ot("_=",{beforeExpr:An,isAssign:$d}),incDec:Ot("++/--",{prefix:Io,postfix:eY,startsExpr:nt}),bang:Ot("!",{beforeExpr:An,prefix:Io,startsExpr:nt}),tilde:Ot("~",{beforeExpr:An,prefix:Io,startsExpr:nt}),doubleCaret:Ot("^^",{startsExpr:nt}),doubleAt:Ot("@@",{startsExpr:nt}),pipeline:Ks("|>",0),nullishCoalescing:Ks("??",1),logicalOR:Ks("||",1),logicalAND:Ks("&&",2),bitwiseOR:Ks("|",3),bitwiseXOR:Ks("^",4),bitwiseAND:Ks("&",5),equality:Ks("==/!=/===/!==",6),lt:Ks("</>/<=/>=",7),gt:Ks("</>/<=/>=",7),relational:Ks("</>/<=/>=",7),bitShift:Ks("<</>>/>>>",8),bitShiftL:Ks("<</>>/>>>",8),bitShiftR:Ks("<</>>/>>>",8),plusMin:Ot("+/-",{beforeExpr:An,binop:9,prefix:Io,startsExpr:nt}),modulo:Ot("%",{binop:10,startsExpr:nt}),star:Ot("*",{binop:10}),slash:Ks("/",10),exponent:Ot("**",{beforeExpr:An,binop:11,rightAssociative:!0}),_in:Ln("in",{beforeExpr:An,binop:7}
5638),_instanceof:Ln("instanceof",{beforeExpr:An,binop:7}),_break:Ln("break"),_case:Ln("case",{beforeExpr:An}),_catch:Ln("catch"),_continue:Ln("continue"),_debugger:Ln("debugger"),_default:Ln("default",{beforeExpr:An}),_else:Ln("else",{beforeExpr:An}),_finally:Ln("finally"),_function:Ln("function",{startsExpr:nt}),_if:Ln("if"),_return:Ln("return",{beforeExpr:An}),_switch:Ln("switch"),_throw:Ln("throw",{beforeExpr:An,prefix:Io,startsExpr:nt}),_try:Ln("try"),_var:Ln("var"),_const:Ln("const"),_with:Ln("with"),_new:Ln("new",{beforeExpr:An,startsExpr:nt}),_this:Ln("this",{startsExpr:nt}),_super:Ln("super",{startsExpr:nt}),_class:Ln("class",{startsExpr:nt}),_extends:Ln("extends",{beforeExpr:An}),_export:Ln("export"),_import:Ln("import",{startsExpr:nt}),_null:Ln("null",{startsExpr:nt}),_true:Ln("true",{startsExpr:nt}),_false:Ln("false",{startsExpr:nt}),_typeof:Ln("typeof",{beforeExpr:An,prefix:Io,startsExpr:nt}),_void:Ln("void",{beforeExpr:An,prefix:Io,startsExpr:nt}),_delete:Ln("delete",{beforeExpr:An,prefix:Io,startsExpr:nt}),_do:Ln("do",{isLoop:Gy,beforeExpr:An}),_for:Ln("for",{isLoop:Gy}),_while:Ln("while",{isLoop:Gy}),_as:Nn("as",{startsExpr:nt}),_assert:Nn("assert",{startsExpr:nt}),_async:Nn("async",{startsExpr:nt}),_await:Nn("await",{startsExpr:nt}),_defer:Nn("defer",{startsExpr:nt}),_from:Nn("from",{startsExpr:nt}),_get:Nn("get",{startsExpr:nt}),_let:Nn("let",{startsExpr:nt}),_meta:Nn("meta",{startsExpr:nt}),_of:Nn("of",{startsExpr:nt}),_sent:Nn("sent",{startsExpr:nt}),_set:Nn("set",{startsExpr:nt}),_source:Nn("source",{startsExpr:nt}),_static:Nn("static",{startsExpr:nt}),_using:Nn("using",{startsExpr:nt}),_yield:Nn("yield",{startsExpr:nt}),_asserts:Nn("asserts",{startsExpr:nt}),_checks:Nn("checks",{startsExpr:nt}),_exports:Nn("exports",{startsExpr:nt}),_global:Nn("global",{startsExpr:nt}),_implements:Nn("implements",{startsExpr:nt}),_intrinsic:Nn("intrinsic",{startsExpr:nt}),_infer:Nn("infer",{startsExpr:nt}),_is:Nn("is",{startsExpr:nt}),_mixins:Nn("mixins",{startsExpr:nt}),_proto:Nn("proto",{startsExpr:nt}),_require:Nn("require",{startsExpr:nt}),_satisfies:Nn("satisfies",{startsExpr:nt}),_keyof:Nn("keyof",{startsExpr:nt}),_readonly:Nn("readonly",{startsExpr:nt}),_unique:Nn("unique",{startsExpr:nt}),_abstract:Nn("abstract",{startsExpr:nt}),_declare:Nn("declare",{startsExpr:nt}),_enum:Nn("enum",{startsExpr:nt}),_module:Nn("module",{startsExpr:nt}),_namespace:Nn("namespace",{startsExpr:nt}),_interface:Nn("interface",{startsExpr:nt}),_type:Nn("type",{startsExpr:nt}),_opaque:Nn("opaque",{startsExpr:nt}),name:Ot("name",{startsExpr:nt}),placeholder:Ot("%%",{startsExpr:nt}),string:Ot("string",{startsExpr:nt}),num:Ot("num",{startsExpr:nt}),bigint:Ot("bigint",{startsExpr:nt}),regexp:Ot("regexp",{startsExpr:nt}),privateName:Ot("#name",{startsExpr:nt}),eof:Ot("eof"),jsxName:Ot("jsxName"),jsxText:Ot("jsxText",{beforeExpr:An}),jsxTagStart:Ot("jsxTagStart",{startsExpr:nt}),jsxTagEnd:Ot("jsxTagEnd")};function or(e){return e>=89&&e<=129}function nY(e){return e<=88}function ti(e){return e>=54&&e<=129}function gI(e){return e>=54&&e<=132}function rY(e){return T1[e]}function rp(e){return E1[e]}function sY(e){return e>=25&&e<=29}function p2(e){return e>=125&&e<=127}function aY(e){return e>=86&&e<=88}function O1(e){return e>=54&&e<=88}function h2(e){return e>=35&&e<=55}function iY(e){return e===30}function oY(e){return I1[e]}function lY(e){return e>=117&&e<=119}function cY(e){return e>=120&&e<=126}function Jo(e){return A1[e]}function im(e){return _1[e]}function uY(e){return e===53}function j0(e){return e>=20&&e<=21}function xI(e){return P1[e]}class jf{constructor(t,r){Qe(this,"token");Qe(this,"preserveSpace");this.token=t,this.preserveSpace=!!r}}const Nr={brace:new jf("{"),j_oTag:new jf("<tag"),j_cTag:new jf("</tag"),j_expr:new jf("<tag>...</tag>",!0)},yI="\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u
563807fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088f\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c5c\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdc-\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u
563812b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c8a\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7dc\\ua7f1-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e
56380-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc",dY="\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0897-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1add\\u1ae0-\\u1aeb\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65",bI=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],pY=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],hY=new RegExp("["+yI+"]"),fY=new RegExp("["+yI+dY+"]");function N0(e,t){let r=65536;for(let n=0,s=t.length;n<s;n+=2){if(r+=t[n],r>e)return!1;if(r+=t[n+1],r>=e)return!0}return!1}function Si(e){return e<65?e===36:e<=90?!0:e<97?e===95:e<=122?!0:e<=65535?e>=170&&hY.test(String.fromCharCode(e)):N0(e,bI)}function ec(e){return e<48?e===36:e<58?!0:e<65?!1:e<=90?!0:e<97?e===95:e<=122?!0:e<=65535?e>=170&&fY.test(String.fromCharCode(e)):N0(e,bI)||N0(e,pY)}const R1={keyword:["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"],strict:["implements","interface","let","package","private","protected","public","static","yield"],strictBind:["eval","arguments"]},mY=new Set(R1.keyword),gY=new Set(R1.strict),xY=new Set(R1.strictBind);function vI(e,t){return t&&e==="await"||e==="enum"}function wI(e,t){return vI(e,t)||gY.has(e)}function jI(e){return xY.has(e)}function NI(e,t){return wI(e,t)||jI(e)}function yY(e){return mY.has(e)}function bY(e,t,r){return e===64&&t===64&&Si(r)}
5638const vY=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);function wY(e){return vY.has(e)}class D1{constructor(t){Qe(this,"flags",0);Qe(this,"names",new Map);Qe(this,"firstLexicalName","");this.flags=t}}class M1{constructor(t,r){Qe(this,"parser");Qe(this,"scopeStack",[]);Qe(this,"inModule");Qe(this,"undefinedExports",new Map);this.parser=t,this.inModule=r}get inTopLevel(){return(this.currentScope().flags&1)>0}get inFunction(){return(this.currentVarScopeFlags()&2)>0}get allowSuper(){return(this.currentThisScopeFlags()&16)>0}get allowDirectSuper(){return(this.currentThisScopeFlags()&32)>0}get allowNewTarget(){return(this.currentThisScopeFlags()&512)>0}get inClass(){return(this.currentThisScopeFlags()&64)>0}get inClassAndNotInNonArrowFunction(){const t=this.currentThisScopeFlags();return(t&64)>0&&(t&2)===0}get inStaticBlock(){for(let t=this.scopeStack.length-1;;t--){const{flags:r}=this.scopeStack[t];if(r&128)return!0;if(r&3779)return!1}}get inNonArrowFunction(){return(this.currentThisScopeFlags()&2)>0}get inBareCaseStatement(){return(this.currentScope().flags&256)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(t){return new D1(t)}enter(t){this.scopeStack.push(this.createScope(t))}exit(){return this.scopeStack.pop().flags}treatFunctionsAsVarInScope(t){return!!(t.flags&130||!this.parser.inModule&&t.flags&1)}declareName(t,r,n){let s=this.currentScope();if(r&8||r&16){this.checkRedeclarationInScope(s,t,r,n);let i=s.names.get(t)||0;r&16?i=i|4:(s.firstLexicalName||(s.firstLexicalName=t),i=i|2),s.names.set(t,i),r&8&&this.maybeExportDefined(s,t)}else if(r&4)for(let i=this.scopeStack.length-1;i>=0&&(s=this.scopeStack[i],this.checkRedeclarationInScope(s,t,r,n),s.names.set(t,(s.names.get(t)||0)|1),this.maybeExportDefined(s,t),!(s.flags&3715));--i);this.parser.inModule&&s.flags&1&&this.undefinedExports.delete(t)}maybeExportDefined(t,r){this.parser.inModule&&t.flags&1&&this.undefinedExports.delete(r)}checkRedeclarationInScope(t,r,n,s){this.isRedeclaredInScope(t,r,n)&&this.parser.raise(J.VarRedeclaration,s,{identifierName:r})}isRedeclaredInScope(t,r,n){if(!(n&1))return!1;if(n&8)return t.names.has(r);const s=t.names.get(r)||0;return n&16?(s&2)>0||!this.treatFunctionsAsVarInScope(t)&&(s&1)>0:(s&2)>0&&!(t.flags&8&&t.firstLexicalName===r)||!this.treatFunctionsAsVarInScope(t)&&(s&4)>0}checkLocalExport(t){const{name:r}=t;this.scopeStack[0].names.has(r)||this.undefinedExports.set(r,t.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let t=this.scopeStack.length-1;;t--){const{flags:r}=this.scopeStack[t];if(r&3715)return r}}currentThisScopeFlags(){for(let t=this.scopeStack.length-1;;t--){const{flags:r}=this.scopeStack[t];if(r&3779&&!(r&4))return r}}}class jY extends D1{constructor(){super(...arguments);Qe(this,"declareFunctions",new Set)}}class NY extends M1{createScope(t){return new jY(t)}declareName(t,r,n){const s=this.currentScope();if(r&2048){this.checkRedeclarationInScope(s,t,r,n),this.maybeExportDefined(s,t),s.declareFunctions.add(t);return}super.declareName(t,r,n)}isRedeclaredInScope(t,r,n){if(super.isRedeclaredInScope(t,r,n))return!0;if(n&2048&&!t.declareFunctions.has(r)){const s=t.names.get(r);return(s&4)>0||(s&2)>0}return!1}checkLocalExport(t){this.scopeStack[0].declareFunctions.has(t.name)||super.checkLocalExport(t)}}const kY=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),SY={AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType:e})=>
5638`Cannot overwrite reserved type ${e}.`,DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:({memberName:e,enumName:t})=>`Boolean enum members need to be initialized. Use either \`${e} = true,\` or \`${e} = false,\` in enum \`${t}\`.`,EnumDuplicateMemberName:({memberName:e,enumName:t})=>`Enum member names need to be unique, but the name \`${e}\` has already been used before in enum \`${t}\`.`,EnumInconsistentMemberValues:({enumName:e})=>`Enum \`${e}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:e,enumName:t})=>`Enum type \`${e}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:e})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${e}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:e,memberName:t,explicitType:r})=>`Enum \`${e}\` has type \`${r}\`, so the initializer of \`${t}\` needs to be a ${r} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:e,memberName:t})=>`Symbol enum members cannot be initialized. Use \`${t},\` in enum \`${e}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:e,memberName:t})=>`The enum member initializer for \`${t}\` needs to be a literal (either a boolean, number, or string) in enum \`${e}\`.`,EnumInvalidMemberName:({enumName:e,memberName:t,suggestion:r})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${t}\`, consider using \`${r}\`, in enum \`${e}\`.`,EnumNumberMemberNotInitialized:({enumName:e,memberName:t})=>`Number enum members need to be initialized, e.g. \`${t} = 1\` in enum \`${e}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:e})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${e}\`.`,GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:{message:"A binding pattern parameter cannot be optional in an implementation signature."},SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:({reservedType:e})=>`Unexpected reserved type ${e}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:e,suggestion:t})=>`\`declare export ${e}\` is not supported. Use \`${t}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."},It=Za`flow`(SY);function CY(e){return e.type==="DeclareExportAllDeclaration"||e.type==="DeclareExportDeclaration"&&(!e.declaration||e.declaration.type!=="TypeAlias"&&e.declaration.type!=="InterfaceDeclaration")}function f2(e){return e.importKind==="type"||e.importKind==="typeof"}const PY={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function AY(e,t){const r=[],n=[];for(let s=0;s<e.length;s++)(t(e[s],s,e)?r:n).push(e[s]);return[r,n]}const _Y=/\*?\s*@((?:no)?flow)\b/,TY=e=>class extends e{constructor(){super(...arguments);Qe(this,"flowPragma")}getScopeHandler(){return NY}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(n,s){n!==130&&n!==9&&n!==24&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(n,s)}addComment(n){if(this.flowPragma===void 0){const s=_Y.exec(n.value);if(s)if(s[1]==="flow")this.flowPragma="flow";else if(s[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(n)}flowParseTypeInitialiser(n){const s=this.state.inType;this.state.inType=!0,this.expect(n||10);const i=this.flowParseType();return this.state.inType=s,i}flowParsePredicate(){const n=this.startNode(),s=this.state.startLoc;return this.next(),this.expectContextual(106),this.state.lastTokStartLoc.index>s.index+1&&this.raise(It.UnexpectedSpaceBetweenModuloChecks,s),this.eat(6)?(n.value=super.parseExpression(),this.expect(7),this.finishNode(n,"DeclaredPredicate")):this.finishNode(n,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(n){const s=this.state.inType;this.state.inType=!0,this.expect(10);let i=null,o=null;return n&&this.match(50)?(this.state.inType=s,o=this.flowParsePredicate()):(i=this.flowParseType(),this.state.inType=s,this.match(50)&&(o=this.flowParsePredicate())),[i,o]}flowParseDeclareClass(n){return this.next(),this.flowParseInterfaceish(n,!0),this.finishNode(n,"DeclareClass")}flowParseDeclareFunction(n){this.next();const s=n.id=this.parseIdentifier(),i=this.startNode(),o=this.startNode();this.match(43)?i.typeParameters=this.flowParseTypeParameterDeclaration():i.typeParameters=null,this.expect(6);const l=this.flowParseFunctionTypeParams();return i.params=l.params,i.rest=l.rest,i.this=l._this,this.expect(7),[i.returnType,n.predicate]=this.flowParseTypeAndPredicateInitialiser(!1),o.typeAnnotation=this.finishNode(i,"FunctionTypeAnnotation"),s.typeAnnotation=this.finishNode(o,"TypeAnnotation"),this.resetEndLocation(s),this.semicolon(),this.scope.declareName(n.id.name,2048,n.id.start),this.finishNode(n,"DeclareFunction")}
5638flowParseDeclare(n,s){if(this.match(76))return this.flowParseDeclareClass(n);if(this.match(64))return this.flowParseDeclareFunction(n);if(this.match(70))return this.flowParseDeclareVariable(n);if(this.eatContextual(123))return this.match(12)?this.flowParseDeclareModuleExports(n):(s&&this.raise(It.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(n));if(this.isContextual(126))return this.flowParseDeclareTypeAlias(n);if(this.isContextual(127))return this.flowParseDeclareOpaqueType(n);if(this.isContextual(125))return this.flowParseDeclareInterface(n);if(this.match(78))return this.flowParseDeclareExportDeclaration(n,s);throw this.unexpected()}flowParseDeclareVariable(n){return this.next(),n.id=this.flowParseTypeAnnotatableIdentifier(),this.scope.declareName(n.id.name,5,n.id.start),this.semicolon(),this.finishNode(n,"DeclareVariable")}flowParseDeclareModule(n){this.scope.enter(0),this.match(130)?n.id=super.parseExprAtom():n.id=this.parseIdentifier();const s=this.startNode(),i=s.body=[];for(this.expect(2);!this.match(4);){const c=this.startNode();this.match(79)?(this.next(),!this.isContextual(126)&&!this.match(83)&&this.raise(It.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),i.push(super.parseImport(c))):(this.expectContextual(121,It.UnsupportedStatementInDeclareModule),i.push(this.flowParseDeclare(c,!0)))}this.scope.exit(),this.expect(4),n.body=this.finishNode(s,"BlockStatement");let o=null,l=!1;return i.forEach(c=>{CY(c)?(o==="CommonJS"&&this.raise(It.AmbiguousDeclareModuleKind,c),o="ES"):c.type==="DeclareModuleExports"&&(l&&this.raise(It.DuplicateDeclareModuleExports,c),o==="ES"&&this.raise(It.AmbiguousDeclareModuleKind,c),o="CommonJS",l=!0)}),n.kind=o||"CommonJS",this.finishNode(n,"DeclareModule")}flowParseDeclareExportDeclaration(n,s){if(this.expect(78),this.eat(61))return this.match(64)||this.match(76)?n.declaration=this.flowParseDeclare(this.startNode()):(n.declaration=this.flowParseType(),this.semicolon()),n.default=!0,this.finishNode(n,"DeclareExportDeclaration");if(this.match(71)||this.isLet()||(this.isContextual(126)||this.isContextual(125))&&!s){const i=this.state.value;throw this.raise(It.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:i,suggestion:PY[i]})}if(this.match(70)||this.match(64)||this.match(76)||this.isContextual(127))return n.declaration=this.flowParseDeclare(this.startNode()),n.default=!1,this.finishNode(n,"DeclareExportDeclaration");if(this.match(51)||this.match(2)||this.isContextual(125)||this.isContextual(126)||this.isContextual(127)){const i=this.parseExport(n,null);return i.type==="ExportNamedDeclaration"?(i.default=!1,delete i.export
5638Kind,this.castNodeTo(i,"DeclareExportDeclaration")):this.castNodeTo(i,"DeclareExportAllDeclaration")}throw this.unexpected()}flowParseDeclareModuleExports(n){return this.next(),this.expectContextual(107),n.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(n,"DeclareModuleExports")}flowParseDeclareTypeAlias(n){this.next();const s=this.flowParseTypeAlias(n);return this.castNodeTo(s,"DeclareTypeAlias"),s}flowParseDeclareOpaqueType(n){return this.next(),this.flowParseOpaqueType(n,!0)}flowParseDeclareInterface(n){return this.next(),this.flowParseInterfaceish(n,!1),this.finishNode(n,"DeclareInterface")}flowParseInterfaceish(n,s){if(n.id=this.flowParseRestrictedIdentifier(!s,!0),this.scope.declareName(n.id.name,s?17:8201,n.id.start),this.match(43)?n.typeParameters=this.flowParseTypeParameterDeclaration():n.typeParameters=null,n.extends=[],this.eat(77))do n.extends.push(this.flowParseInterfaceExtends());while(!s&&this.eat(8));if(s){const i=[],o=[];if(this.eatContextual(113))do o.push(this.flowParseInterfaceExtends());while(this.eat(8));if(this.eatContextual(109))do i.push(this.flowParseClassImplements());while(this.eat(8));n.implements=i,n.mixins=o}n.body=this.flowParseObjectType({allowStatic:s,allowExact:!1,allowSpread:!1,allowProto:s,allowInexact:!1})}flowParseInterfaceExtends(){const n=this.startNode();return n.id=this.flowParseQualifiedTypeIdentifier(),this.match(43)?n.typeParameters=this.flowParseTypeParameterInstantiation():n.typeParameters=null,this.finishNode(n,"InterfaceExtends")}flowParseInterface(n){return this.flowParseInterfaceish(n,!1),this.finishNode(n,"InterfaceDeclaration")}checkNotUnderscore(n){n==="_"&&this.raise(It.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(n,s,i){kY.has(n)&&this.raise(i?It.AssignReservedType:It.UnexpectedReservedType,s,{reservedType:n})}flowParseRestrictedIdentifierName(n,s){return this.checkReservedType(this.state.value,this.state.startLoc,s),this.parseIdentifierName(n)}flowParseRestrictedIdentifier(n,s){const i=this.startNode(),o=this.flowParseRestrictedIdentifierName(n,s);return this.createIdentifier(i,o)}flowParseTypeAlias(n){return n.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(n.id.name,8201,n.id.start),this.match(43)?n.typeParameters=this.flowParseTypeParameterDeclaration():n.typeParameters=null,n.right=this.flowParseTypeInitialiser(25),this.semicolon(),this.finishNode(n,"TypeAlias")}flowParseOpaqueType(n,s){return this.expectContextual(126),n.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(n.id.name,8201,n.id.start),this.match(43)?n.typeParameters=this.flowParseTypeParameterDeclaration():n.typeParameters=null,n.supertype=null,this.match(10)&&(n.supertype=this.flowParseTypeInitialiser(10)),n.impltype=null,s||(n.impltype=this.flowParseTypeInitialiser(25)),this.semicolon(),this.finishNode(n,s?"DeclareOpaqueType":"OpaqueType")}flowParseTypeParameterBound(){if(this.match(10)||this.isContextual(77)){const n=this.startNode();return this.next(),n.typeAnnotation=this.flowParseType(),this.finishNode(n,"TypeAnnotation")}}flowParseTypeParameter(n=!1){const s=this.state.startLoc,i=this.startNode(),o=this.flowParseVariance();return i.name=this.flowParseRestrictedIdentifierName(),i.variance=o,i.bound=this.flowParseTypeParameterBound(),this.match(25)?(this.eat(25),i.default=this.flowParseType()):n&&this.raise(It.MissingTypeParamDefault,s),this.finishNode(i,"TypeParameter")}flowParseTypeParameterDeclaration(){const n=this.state.inType,s=this.startNode();s.params=[],this.state.inType=!0,this.match(43)||this.match(138)?this.next():this.unexpected();let i=!1;do{const o=this.flowParseTypeParameter(i);s.params.push(o),o.default&&(i=!0),this.match(44)||this.expect(8)}while(!this.match(44));return this.expect(44),this.state.inType=n,this.finishNode(s,"TypeParameterDeclaration")}flowInTopLevelContext(n){if(this.curContext()!==Nr.brace){const s=this.state.context;this.state.context=[s[0]];try{return n()}finally{this.state.context=s}}else return n()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===43)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){const n=this.startNode(),s=this.state.inType;return this.state.inType=!0,n.params=[],this.flowInTopLevelContext(()=>{this.expect(43);const i=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.match(44);)n.params.push(this.flowParseType()),this.match(44)||this.expect(8);this.state.noAnonFunctionType=i}),this.state.inType=s,!this.state.inType&&this.curContext()===Nr.brace&&this.reScan_lt_gt(),this.expect(44),this.finishNode(n,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==43)return null;const n=this.startNode(),s=this.state.inType;for(n.params=[],this.state.inType=!0,this.expect(43);!this.match(44);)n.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(44)||this.expect(8);return this.expect(44),this.state.inType=s,this.finishNode(n,"TypeParameterInstantiation")}flowParseInterfaceType(){const n=this.startNode();if(this.expectContextual(125),n.extends=[],this.eat(77))do n.extends.push(this.flowParseInterfaceExtends());while(this.eat(8));return n.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(n,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(131)||this.match(130)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(n,s,i){return n.static=s,this.lookahead().type===10?(n.id=this.parseIdentifier(!0),n.key=this.flowParseTypeInitialiser()):(n.id=null,n.key=this.flowParseType()),this.expect(1),n.value=this.flowParseTypeInitialiser(),n.variance=i,this.finishNode(n,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(n,s){return n.static=s,n.id=this.parseIdentifier(!0),this.expect(1),this.expect(1),this.match(43)||this.match(6)?(n.method=!0,n.optional=!1,n.value=this.flowParseObjectTypeMethodish(this.startNodeAtNode(n))):(n.method=!1,this.eat(13)&&(n.optional=!0),n.value=this.flowParseTypeInitialiser()),this.finishNode(n,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(n){for(n.params=[],n.rest=null,n.typeParameters=null,n.this=null,this.match(43)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(6),this.match(74)&&(n.this=this.flowParseFunctionTypeParam(!0),n.this.name=null,this.match(7)||this.expect(8));!this.match(7)&&!this.match(17);)n.params.push(this.flowParseFunctionTypeParam(!1)),this.match(7)||this.expect(8);
5638return this.eat(17)&&(n.rest=this.flowParseFunctionTypeParam(!1)),this.expect(7),n.returnType=this.flowParseTypeInitialiser(),this.finishNode(n,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(n,s){const i=this.startNode();return n.static=s,n.value=this.flowParseObjectTypeMethodish(i),this.finishNode(n,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:n,allowExact:s,allowSpread:i,allowProto:o,allowInexact:l}){const c=this.state.inType;this.state.inType=!0;const u=this.startNode();u.callProperties=[],u.properties=[],u.indexers=[],u.internalSlots=[];let d,p,h=!1;for(s&&this.match(3)?(this.expect(3),d=5,p=!0):(this.expect(2),d=4,p=!1),u.exact=p;!this.match(d);){let x=!1,g=null,y=null;const b=this.startNode();if(o&&this.isContextual(114)){const k=this.lookahead();k.type!==10&&k.type!==13&&(this.next(),g=this.state.startLoc,n=!1)}if(n&&this.isContextual(102)){const k=this.lookahead();k.type!==10&&k.type!==13&&(this.next(),x=!0)}const v=this.flowParseVariance();if(this.eat(0))g!=null&&this.unexpected(g),this.eat(0)?(v&&this.unexpected(v.start),u.internalSlots.push(this.flowParseObjectTypeInternalSlot(b,x))):u.indexers.push(this.flowParseObjectTypeIndexer(b,x,v));else if(this.match(6)||this.match(43))g!=null&&this.unexpected(g),v&&this.unexpected(v.start),u.callProperties.push(this.flowParseObjectTypeCallProperty(b,x));else{let k="init";if(this.isContextual(95)||this.isContextual(100)){const j=this.lookahead();gI(j.type)&&(k=this.state.value,this.next())}const N=this.flowParseObjectTypeProperty(b,x,g,v,k,i,l??!p);N===null?(h=!0,y=this.state.lastTokStartLoc):u.properties.push(N)}this.flowObjectTypeSemicolon(),y&&!this.match(4)&&!this.match(5)&&this.raise(It.UnexpectedExplicitInexactInObject,y)}this.expect(d),i&&(u.inexact=h);const f=this.finishNode(u,"ObjectTypeAnnotation");return this.state.inType=c,f}flowParseObjectTypeProperty(n,s,i,o,l,c,u){if(this.eat(17))return this.match(8)||this.match(9)||this.match(4)||this.match(5)?(c?u||this.raise(It.InexactInsideExact,this.state.lastTokStartLoc):this.raise(It.InexactInsideNonObject,this.state.lastTokStartLoc),o&&this.raise(It.InexactVariance,o),null):(c||this.raise(It.UnexpectedSpreadType,this.state.lastTokStartLoc),i!=null&&this.unexpected(i),o&&this.raise(It.SpreadVariance,o),n.argument=this.flowParseType(),this.finishNode(n,"ObjectTypeSpreadProperty"));{n.key=this.flowParseObjectPropertyKey(),n.static=s,n.proto=i!=null,n.kind=l;let d=!1;return this.match(43)||this.match(6)?(n.method=!0,i!=null&&this.unexpected(i),o&&this.unexpected(o.start),n.value=this.flowParseObjectTypeMethodish(this.startNodeAtNode(n)),l==="get"||l==="set"?this.flowCheckGetterSetterParams(n):!s&&!c&&n.key.name==="constructor"&&n.value.this&&this.raise(It.ThisParamBannedInConstructor,n.value.this)):(l!=="init"&&this.unexpected(),n.method=!1,this.eat(13)&&(d=!0),n.value=this.flowParseTypeInitialiser(),n.variance=o),n.optional=d,this.finishNode(n,"ObjectTypeProperty")}}flowCheckGetterSetterParams(n){const s=n.kind==="get"?0:1,i=n.value,o=i.params.length+(i.rest?1:0);i.this&&this.raise(n.kind==="get"?It.GetterMayNotHaveThisParam:It.SetterMayNotHaveThisParam,i.this),o!==s&&this.raise(n.kind==="get"?J.BadGetterArity:J.BadSetterArity,n),n.kind==="set"&&i.rest&&this.raise(J.BadSetterRestParameter,n)}flowObjectTypeSemicolon(){!this.eat(9)&&!this.eat(8)&&!this.match(4)&&!this.match(5)&&this.unexpected()}flowParseQualifiedTypeIdentifier(n,s){n??(n=this.state.startLoc);let i=s||this.flowParseRestrictedIdentifier(!0);for(;this.eat(12);){const o=this.startNodeAt(n);o.qualification=i,o.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(o,"QualifiedTypeIdentifier")}return i}flowParseGenericType(n,s){const i=this.startNodeAt(n);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(n,s),this.match(43)&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")}flowParseTypeofType(){const n=this.startNode();return this.expect(83),n.argument=this.flowParsePrimaryType(),this.finishNode(n,"TypeofTypeAnnotation")}flowParseTupleType(){const n=this.startNode();for(n.types=[],this.expect(0);this.state.pos<this.length&&!this.match(1)&&(n.types.push(this.flowParseType()),!this.match(1));)this.expect(8);return this.expect(1),this.finishNode(n,"TupleTypeAnnotation")}flowParseFunctionTypeParam(n){let s=null,i=!1,o;const l=this.startNode(),c=this.lookahead(),u=this.state.type===74;return c.type===10||c.type===13?(u&&!n&&this.raise(It.ThisParamMustBeFirst,l),s=this.parseIdentifier(u),this.eat(13)&&(i=!0,u&&this.raise(It.ThisParamMayNotBeOptional,l)),o=this.flowParseTypeInitialiser()):o=this.flowParseType(),l.name=s,l.optional=i,l.typeAnnotation=o,this.finishNode(l,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(n){const s=this.startNodeAtNode(n);return s.name=null,s.optional=!1,s.typeAnnotation=n,this.finishNode(s,"FunctionTypeParam")}flowParseFunctionTypeParams(n=[]){let s=null,i=null;for(this.match(74)&&(i=this.flowParseFunctionTypeParam(!0),i.name=null,this.match(7)||this.expect(8));!this.match(7)&&!this.match(17);)n.push(this.flowParseFunctionTypeParam(!1)),this.match(7)||this.expect(8);
5638return this.eat(17)&&(s=this.flowParseFunctionTypeParam(!1)),{params:n,rest:s,_this:i}}flowIdentToTypeAnnotation(n,s,i){switch(i.name){case"any":return this.finishNode(s,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(s,"BooleanTypeAnnotation");case"mixed":return this.finishNode(s,"MixedTypeAnnotation");case"empty":return this.finishNode(s,"EmptyTypeAnnotation");case"number":return this.finishNode(s,"NumberTypeAnnotation");case"string":return this.finishNode(s,"StringTypeAnnotation");case"symbol":return this.finishNode(s,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(i.name),this.flowParseGenericType(n,i)}}flowParsePrimaryType(){const n=this.state.startLoc,s=this.startNode();let i,o,l=!1;const c=this.state.noAnonFunctionType;switch(this.state.type){case 2:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case 3:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case 0:return this.state.noAnonFunctionType=!1,o=this.flowParseTupleType(),this.state.noAnonFunctionType=c,o;case 43:{const u=this.startNode();return u.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(6),i=this.flowParseFunctionTypeParams(),u.params=i.params,u.rest=i.rest,u.this=i._this,this.expect(7),this.expect(15),u.returnType=this.flowParseType(),this.finishNode(u,"FunctionTypeAnnotation")}case 6:{const u=this.startNode();if(this.next(),!this.match(7)&&!this.match(17))if(or(this.state.type)||this.match(74)){const d=this.lookahead().type;l=d!==13&&d!==10}else l=!0;if(l){if(this.state.noAnonFunctionType=!1,o=this.flowParseType(),this.state.noAnonFunctionType=c,this.state.noAnonFunctionType||!(this.match(8)||this.match(7)&&this.lookahead().type===15))return this.expect(7),o;this.eat(8)}return o?i=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(o)]):i=this.flowParseFunctionTypeParams(),u.params=i.params,u.rest=i.rest,u.this=i._this,this.expect(7),this.expect(15),u.returnType=this.flowParseType(),u.typeParameters=null,this.finishNode(u,"FunctionTypeAnnotation")}case 130:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 81:case 82:return s.value=this.match(81),this.next(),this.finishNode(s,"BooleanLiteralTypeAnnotation");case 49:if(this.state.value==="-"){if(this.next(),this.match(131))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",s);if(this.match(132))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",s);throw this.raise(It.UnexpectedSubtractionOperand,this.state.startLoc)}throw this.unexpected();case 131:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 132:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 84:return this.next(),this.finishNode(s,"VoidTypeAnnotation");
5638case 80:return this.next(),this.finishNode(s,"NullLiteralTypeAnnotation");case 74:return this.next(),this.finishNode(s,"ThisTypeAnnotation");case 51:return this.next(),this.finishNode(s,"ExistsTypeAnnotation");case 83:return this.flowParseTypeofType();default:if(O1(this.state.type)){const u=Jo(this.state.type);return this.next(),super.createIdentifier(s,u)}else if(or(this.state.type))return this.isContextual(125)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(n,s,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){const n=this.state.startLoc;let s=this.flowParsePrimaryType(),i=!1;for(;(this.match(0)||this.match(14))&&!this.canInsertSemicolon();){const o=this.startNodeAt(n),l=this.eat(14);i=i||l,this.expect(0),!l&&this.match(1)?(o.elementType=s,this.next(),s=this.finishNode(o,"ArrayTypeAnnotation")):(o.objectType=s,o.indexType=this.flowParseType(),this.expect(1),i?(o.optional=l,s=this.finishNode(o,"OptionalIndexedAccessType")):s=this.finishNode(o,"IndexedAccessType"))}return s}flowParsePrefixType(){const n=this.startNode();return this.eat(13)?(n.typeAnnotation=this.flowParsePrefixType(),this.finishNode(n,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){const n=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(15)){const s=this.startNodeAtNode(n);return s.params=[this.reinterpretTypeAsFunctionTypeParam(n)],s.rest=null,s.this=null,s.returnType=this.flowParseType(),s.typeParameters=null,this.finishNode(s,"FunctionTypeAnnotation")}return n}flowParseIntersectionType(){const n=this.startNode();this.eat(41);const s=this.flowParseAnonFunctionWithoutParens();for(n.types=[s];this.eat(41);)n.types.push(this.flowParseAnonFunctionWithoutParens());return n.types.length===1?s:this.finishNode(n,"IntersectionTypeAnnotation")}flowParseUnionType(){const n=this.startNode();this.eat(39);const s=this.flowParseIntersectionType();for(n.types=[s];this.eat(39);)n.types.push(this.flowParseIntersectionType());return n.types.length===1?s:this.finishNode(n,"UnionTypeAnnotation")}flowParseType(){const n=this.state.inType;this.state.inType=!0;const s=this.flowParseUnionType();return this.state.inType=n,s}flowParseTypeOrImplicitInstantiation(){if(this.state.type===128&&this.state.value==="_"){const n=this.state.startLoc,s=this.parseIdentifier();return this.flowParseGenericType(n,s)}else return this.flowParseType()}flowParseTypeAnnotation(){const n=this.startNode();return n.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(n,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){const n=this.startNode(),s=this.parseIdentifierName();return this.match(10)&&(n.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(n,s)}typeCastToParameter(n){return n.expression.typeAnnotation=n.typeAnnotation,this.resetEndLocationFromNode(n.expression,n.typeAnnotation),n.expression}flowParseVariance(){let n=null;return this.match(49)?(n=this.startNode(),this.state.value==="+"?n.kind="plus":n.kind="minus",this.next(),this.finishNode(n,"Variance")):n}parseFunctionBody(n,s,i=!1){if(s){this.forwardNoArrowParamsConversionAt(n,()=>super.parseFunctionBody(n,!0,i));return}super.parseFunctionBody(n,!1,i)}parseFunctionBodyAndFinish(n,s,i=!1){if(this.match(10)){const o=this.startNode();s==="FunctionDeclaration"||s==="FunctionExpression"||s==="ArrowFunctionExpression"?[o.typeAnnotation,n.predicate]=this.flowParseTypeAndPredicateInitialiser(!0):o.typeAnnotation=this.flowParseTypeInitialiser(),n.returnType=o.typeAnnotation?this.finishNode(o,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(n,s,i)}parseStatementLike(n){if(this.state.strict&&this.isContextual(125)){const i=this.lookahead();if(ti(i.type)){const o=this.startNode();return this.next(),this.flowParseInterface(o)}}else if(this.isContextual(122)){const i=this.startNode();return this.next(),this.flowParseEnumDeclaration(i)}const s=super.parseStatementLike(n);return this.flowPragma===void 0&&!this.isValidDirective(s)&&(this.flowPragma=null),s}parseExpressionStatement(n,s,i){if(s.type==="Identifier"){if(s.name==="declare"){if(this.match(76)||or(this.state.type)||this.match(64)||this.match(70)||this.match(78))return this.flowParseDeclare(n)}else if(or(this.state.type)){if(s.name==="interface")return this.flowParseInterface(n);if(s.name==="type")return this.flowParseTypeAlias(n);if(s.name==="opaque")return this.flowParseOpaqueType(n,!1)}}
5638return super.parseExpressionStatement(n,s,i)}shouldParseExportDeclaration(){const{type:n}=this.state;return n===122||p2(n)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){const{type:n}=this.state;return n===122||p2(n)?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(122)){const n=this.startNode();return this.next(),this.flowParseEnumDeclaration(n)}return super.parseExportDefaultExpression()}parseConditional(n,s,i){if(!this.match(13))return n;if(i!=null){const x=this.lookaheadCharCode();if(x===44||x===61||x===58||x===41)return this.setOptionalParametersError(i),n}this.expect(13);const o=this.state.clone(),l=this.state.noArrowAt,c=this.startNodeAt(s);let{consequent:u,failed:d}=this.tryParseConditionalConsequent();const p=this.getArrowLikeExpressions(u);let h=p[0];const f=p[1];if(d||f.length>0){const x=[...l];if(f.length>0){this.state=o,this.state.noArrowAt=x;for(let g=0;g<f.length;g++)x.push(f[g].start);({consequent:u,failed:d}=this.tryParseConditionalConsequent()),[h]=this.getArrowLikeExpressions(u)}d&&h.length>1&&this.raise(It.AmbiguousConditionalArrow,o.startLoc),d&&h.length===1&&(this.state=o,x.push(h[0].start),this.state.noArrowAt=x,{consequent:u}=this.tryParseConditionalConsequent())}return this.getArrowLikeExpressions(u,!0),this.state.noArrowAt=l,this.expect(10),c.test=n,c.consequent=u,c.alternate=this.forwardNoArrowParamsConversionAt(c,()=>this.parseMaybeAssign(void 0,void 0)),this.finishNode(c,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);const n=this.parseMaybeAssignAllowIn(),s=!this.match(10);return this.state.noArrowParamsConversionAt.pop(),{consequent:n,failed:s}}getArrowLikeExpressions(n,s){const i=[n],o=[];for(;i.length!==0;){const l=i.pop();l.type==="ArrowFunctionExpression"&&l.body.type!=="BlockStatement"?(l.typeParameters||!l.returnType?this.finishArrowValidation(l):o.push(l),i.push(l.body)):l.type==="ConditionalExpression"&&(i.push(l.consequent),i.push(l.alternate))}return s?(o.forEach(l=>this.finishArrowValidation(l)),[o,[]]):AY(o,l=>l.params.every(c=>this.isAssignable(c,!0)))}finishArrowValidation(n){var s;this.toAssignableList(n.params,(s=n.extra)==null?void 0:s.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(n,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(n,s){let i;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(n.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),i=s(),this.state.noArrowParamsConversionAt.pop()):i=s(),i}parseParenItem(n,s){const i=super.parseParenItem(n,s);if(this.eat(13)&&(i.optional=!0,this.resetEndLocation(n)),this.match(10)){const o=this.startNodeAt(s);return o.expression=i,o.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(o,"TypeCastExpression")}return i}assertModuleNodeAllowed(n){n.type==="ImportDeclaration"&&(n.importKind==="type"||n.importKind==="typeof")||n.type==="ExportNamedDeclaration"&&n.exportKind==="type"||n.type==="ExportAllDeclaration"&&n.exportKind==="type"||super.assertModuleNodeAllowed(n)}parseExportDeclaration(n){if(this.isContextual(126)){n.exportKind="type";const s=this.startNode();return this.next(),this.match(2)?(n.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(n),null):this.flowParseTypeAlias(s)}else if(this.isContextual(127)){n.exportKind="type";const s=this.startNode();return this.next(),this.flowParseOpaqueType(s,!1)}else if(this.isContextual(125)){n.exportKind="type";const s=this.startNode();return this.next(),this.flowParseInterface(s)}else if(this.isContextual(122)){n.exportKind="value";const s=this.startNode();return this.next(),this.flowParseEnumDeclaration(s)}else return super.parseExportDeclaration(n)}eatExportStar(n){return super.eatExportStar(n)?!0:this.isContextual(126)&&this.lookahead().type===51?(n.exportKind="type",this.next(),this.next(),!0):!1}maybeParseExportNamespaceSpecifier(n){const{startLoc:s}=this.state,i=super.maybeParseExportNamespaceSpecifier(n);
5638return i&&n.exportKind==="type"&&this.unexpected(s),i}parseClassId(n,s,i){if((!s||i)&&this.isContextual(109)){n.id=null;return}super.parseClassId(n,s,i),this.match(43)&&(n.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(n,s,i){const{startLoc:o}=this.state;if(this.isContextual(121)){if(super.parseClassMemberFromModifier(n,s))return;s.declare=!0}super.parseClassMember(n,s,i),s.declare&&(s.type!=="ClassProperty"&&s.type!=="ClassPrivateProperty"&&s.type!=="PropertyDefinition"?this.raise(It.DeclareClassElement,o):s.value&&this.raise(It.DeclareClassFieldInitializer,s.value))}isIterator(n){return n==="iterator"||n==="asyncIterator"}readIterator(){const n=super.readWord1(),s="@@"+n;(!this.isIterator(n)||!this.state.inType)&&this.raise(J.InvalidIdentifier,this.state.curPosition(),{identifierName:s}),this.finishToken(128,s)}getTokenFromCode(n){const s=this.input.charCodeAt(this.state.pos+1);n===123&&s===124?this.finishOp(3,2):this.state.inType&&(n===62||n===60)?this.finishOp(n===62?44:43,1):this.state.inType&&n===63?s===46?this.finishOp(14,2):this.finishOp(13,1):bY(n,s,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(n)}isAssignable(n,s){return n.type==="TypeCastExpression"?this.isAssignable(n.expression,s):super.isAssignable(n,s)}toAssignable(n,s=!1){!s&&n.type==="AssignmentExpression"&&n.left.type==="TypeCastExpression"&&(n.left=this.typeCastToParameter(n.left)),super.toAssignable(n,s)}toAssignableListItem(n,s,i){const o=n[s];o.type==="TypeCastExpression"&&(n[s]=this.typeCastToParameter(o)),super.toAssignableListItem(n,s,i)}toReferencedList(n,s){var i;for(let o=0;o<n.length;o++){const l=n[o];(l==null?void 0:l.type)==="TypeCastExpression"&&!((i=l.extra)!=null&&i.parenthesized)&&(n.length>1||!s)&&this.raise(It.TypeCastInPattern,l.typeAnnotation)}return n}parseArrayLike(n,s){const i=super.parseArrayLike(n,s);return i.type==="ArrayExpression"&&this.toReferencedList(i.elements),i}isValidLVal(n,s,i,o){return n==="TypeCastExpression"||super.isValidLVal(n,s,i,o)}parseClassProperty(n){return this.match(10)&&(n.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(n)}parseClassPrivateProperty(n){return this.match(10)&&(n.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(n)}isClassMethod(){return this.match(43)||super.isClassMethod()}isClassProperty(){return this.match(10)||super.isClassProperty()}isNonstaticConstructor(n){return!this.match(10)&&super.isNonstaticConstructor(n)}pushClassMethod(n,s,i,o,l,c){if(s.variance&&this.unexpected(s.variance.start),delete s.variance,this.match(43)&&(s.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(n,s,i,o,l,c),s.params&&l){const u=s.params;u.length>0&&this.isThisParam(u[0])&&this.raise(It.ThisParamBannedInConstructor,s)}else if(s.type==="MethodDefinition"&&l&&s.value.params){const u=s.value.params;u.length>0&&this.isThisParam(u[0])&&this.raise(It.ThisParamBannedInConstructor,s)}}pushClassPrivateMethod(n,s,i,o){s.variance&&this.unexpected(s.variance.start),delete s.variance,this.match(43)&&(s.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(n,s,i,o)}flowParseClassImplements(){const n=this.startNode();return n.id=this.flowParseRestrictedIdentifier(!0),this.match(43)?n.typeParameters=this.flowParseTypeParameterInstantiation():n.typeParameters=null,this.finishNode(n,"ClassImplements")}parseClassSuper(n){if(super.parseClassSuper(n),n.superClass&&(this.match(43)||this.match(47))&&(n.superTypeArguments=this.flowParseTypeParameterInstantiationInExpression()),this.eatContextual(109)){const s=n.implements=[];do s.push(this.flowParseClassImplements());while(this.eat(8))}}checkGetterSetterParams(n){super.checkGetterSetterParams(n);const s=this.getObjectOrClassMethodParams(n);if(s.length>0){const i=s[0];this.isThisParam(i)&&n.kind==="get"?this.raise(It.GetterMayNotHaveThisParam,i):this.isThisParam(i)&&this.raise(It.SetterMayNotHaveThisParam,i)}}parsePropertyNamePrefixOperator(n){n.variance=this.flowParseVariance()}parseObjPropValue(n,s,i,o,l,c,u){n.variance&&this.unexpected(n.variance.start),delete n.variance;let d;this.match(43)&&!c&&(d=this.flowParseTypeParameterDeclaration(),this.match(6)||this.unexpected());const p=super.parseObjPropValue(n,s,i,o,l,c,u);return d&&((p.value||p).typeParameters=d),p}parseFunctionParamType(n){return this.eat(13)&&(n.type!=="Identifier"&&this.raise(It.PatternIsOptional,n),this.isThisParam(n)&&this.raise(It.ThisParamMayNotBeOptional,n),n.optional=!0),this.match(10)?n.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(n)&&this.raise(It.ThisParamAnnotationRequired,n),this.match(25)&&this.isThisParam(n)&&this.raise(It.ThisParamNoDefault,n),this.resetEndLocation(n),n}parseMaybeDefault(n,s){const i=super.parseMaybeDefault(n,s);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(It.TypeBeforeInitializer,i.typeAnnotation),i}parseImportSpecifierLocal(n,s,i){s.local=f2(n)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),n.specifiers.push(this.finishImportSpecifier(s,i))}isPotentialImportPhase(n){if(super.isPotentialImportPhase(n))return!0;
5638if(this.isContextual(126)){if(!n)return!0;const s=this.lookaheadCharCode();return s===123||s===42}return!n&&this.isContextual(83)}applyImportPhase(n,s,i,o){if(super.applyImportPhase(n,s,i,o),s){if(!i&&this.match(61))return;n.exportKind=i==="type"?i:"value"}else i==="type"&&this.match(51)&&this.unexpected(),n.importKind=i==="type"||i==="typeof"?i:"value"}parseImportSpecifier(n,s,i,o,l){const c=n.imported;let u=null;c.type==="Identifier"&&(c.name==="type"?u="type":c.name==="typeof"&&(u="typeof"));let d=!1;if(this.isContextual(89)&&!this.isLookaheadContextual("as")){const h=this.parseIdentifier(!0);u!==null&&!ti(this.state.type)?(n.imported=h,n.importKind=u,n.local=this.cloneIdentifier(h)):(n.imported=c,n.importKind=null,n.local=this.parseIdentifier())}else{if(u!==null&&ti(this.state.type))n.imported=this.parseIdentifier(!0),n.importKind=u;else{if(s)throw this.raise(J.ImportBindingIsString,n,{importName:c.value});n.imported=c,n.importKind=null}this.eatContextual(89)?n.local=this.parseIdentifier():(d=!0,n.local=this.cloneIdentifier(n.imported))}const p=f2(n);return i&&p&&this.raise(It.ImportTypeShorthandOnlyInPureImport,n),(i||p)&&this.checkReservedType(n.local.name,n.local.start,!0),d&&!i&&!p&&this.checkReservedWord(n.local.name,n.start,!0,!0),this.finishImportSpecifier(n,"ImportSpecifier")}parseBindingAtom(){switch(this.state.type){case 74:return this.parseIdentifier(!0);default:return super.parseBindingAtom()}}parseFunctionParams(n,s){const i=n.kind;i!=="get"&&i!=="set"&&this.match(43)&&(n.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(n,s)}parseVarId(n,s){super.parseVarId(n,s),this.match(10)&&(n.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(n.id))}parseAsyncArrowFromCallExpression(n,s){if(this.match(10)){const i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,n.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=i}return super.parseAsyncArrowFromCallExpression(n,s)}shouldParseAsyncArrow(){return this.match(10)||super.shouldParseAsyncArrow()}parseMaybeAssign(n,s){let i=null,o;if(this.hasPlugin("jsx")&&(this.match(138)||this.match(43))){if(i=this.state.clone(),o=this.tryParse(()=>super.parseMaybeAssign(n,s),i),!o.error)return o.node;const{context:l}=this.state,c=l[l.length-1];(c===Nr.j_oTag||c===Nr.j_expr)&&l.pop()}if(o!=null&&o.error||this.match(43)){i=i||this.state.clone();let l;const c=this.tryParse(d=>{var f;l=this.flowParseTypeParameterDeclaration();const p=this.forwardNoArrowParamsConversionAt(l,()=>{const x=super.parseMaybeAssign(n,s);return this.resetStartLocationFromNode(x,l),x});(f=p.extra)!=null&&f.parenthesized&&d();const h=this.maybeUnwrapTypeCastExpression(p);return h.type!=="ArrowFunctionExpression"&&d(),h.typeParameters=l,this.resetStartLocationFromNode(h,l),p},i);let u=null;if(c.node&&this.maybeUnwrapTypeCastExpression(c.node).type==="ArrowFunctionExpression"){if(!c.error&&!c.aborted)return c.node.async&&this.raise(It.UnexpectedTypeParameterBeforeAsyncArrowFunction,l),c.node;u=c.node}if(o!=null&&o.node)return this.state=o.failState,o.node;if(u)return this.state=c.failState,u;throw o!=null&&o.thrown?o.error:c.thrown?c.error:this.raise(It.UnexpectedTokenAfterTypeParameter,l)}return super.parseMaybeAssign(n,s)}parseArrow(n){if(this.match(10)){const s=this.tryParse(()=>{const i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;const o=this.startNode();return[o.typeAnnotation,n.predicate]=this.flowParseTypeAndPredicateInitialiser(!0),this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(15)||this.unexpected(),o});if(s.thrown)return null;s.error&&(this.state=s.failState),n.returnType=s.node.typeAnnotation?this.finishNode(s.node,"TypeAnnotation"):null}return super.parseArrow(n)}shouldParseArrow(n){return this.match(10)||super.shouldParseArrow(n)}setArrowFunctionParameters(n,s){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(n.start))?n.params=s:super.setArrowFunctionParameters(n,s)}checkParams(n,s,i,o=!0){if(!(i&&this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(n.start)))){for(let l=0;l<n.params.length;l++)this.isThisParam(n.params[l])&&l>0&&this.raise(It.ThisParamMustBeFirst,n.params[l]);super.checkParams(n,s,i,o)}}parseParenAndDistinguishExpression(n){return super.parseParenAndDistinguishExpression(n&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(n,s,i){if(n.type==="Identifier"&&n.name==="async"&&this.state.noArrowAt.includes(s.index)){this.next();const o=this.startNodeAt(s);o.callee=n,o.arguments=super.parseCallExpressionArguments(),n=this.finishNode(o,"CallExpression")}else if(n.type==="Identifier"&&n.name==="async"&&this.match(43)){const o=this.state.clone(),l=this.tryParse(u=>this.parseAsyncArrowWithTypeParameters(s)||u(),o);if(!l.error&&!l.aborted)return l.node;const c=this.tryParse(()=>super.parseSubscripts(n,s,i),o);if(c.node&&!c.error)return c.node;if(l.node)return this.state=l.failState,l.node;if(c.node)return this.state=c.failState,c.node;throw l.error||c.error}return super.parseSubscripts(n,s,i)}parseSubscript(n,s,i,o){if(this.match(14)&&this.isLookaheadToken_lt()){if(o.optionalChainMember=!0,i)return o.stop=!0,n;this.next();const l=this.startNodeAt(s);return l.callee=n,l.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(6),l.arguments=this.parseCallExpressionArguments(),l.o
5638ptional=!0,this.finishCallExpression(l,!0)}else if(!i&&this.shouldParseTypes()&&(this.match(43)||this.match(47))){const l=this.startNodeAt(s);l.callee=n;const c=this.tryParse(()=>(l.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(6),l.arguments=super.parseCallExpressionArguments(),o.optionalChainMember&&(l.optional=!1),this.finishCallExpression(l,o.optionalChainMember)));if(c.node)return c.error&&(this.state=c.failState),c.node}return super.parseSubscript(n,s,i,o)}parseNewCallee(n){super.parseNewCallee(n);let s=null;this.shouldParseTypes()&&this.match(43)&&(s=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),n.typeArguments=s}parseAsyncArrowWithTypeParameters(n){const s=this.startNodeAt(n);if(this.parseFunctionParams(s,!1),!!this.parseArrow(s))return super.parseArrowExpression(s,void 0,!0)}readToken_mult_modulo(n){const s=this.input.charCodeAt(this.state.pos+1);if(n===42&&s===47&&this.state.hasFlowComment){this.state.hasFlowComment=!1,this.state.pos+=2,this.nextToken();return}super.readToken_mult_modulo(n)}readToken_pipe_amp(n){const s=this.input.charCodeAt(this.state.pos+1);if(n===124&&s===125){this.finishOp(5,2);return}super.readToken_pipe_amp(n)}parseTopLevel(n,s){const i=super.parseTopLevel(n,s);return this.state.hasFlowComment&&this.raise(It.UnterminatedFlowComment,this.state.curPosition()),i}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(It.NestedFlowComment,this.state.startLoc);this.hasFlowCommentCompletion();const n=this.skipFlowComment();n&&(this.state.pos+=n,this.state.hasFlowComment=!0);return}return super.skipBlockComment(this.state.hasFlowComment?"*-/":"*/")}skipFlowComment(){const{pos:n}=this.state;let s=2;for(;[32,9].includes(this.input.charCodeAt(n+s));)s++;const i=this.input.charCodeAt(s+n),o=this.input.charCodeAt(s+n+1);return i===58&&o===58?s+2:this.input.slice(s+n,s+n+12)==="flow-include"?s+12:i===58&&o!==58?s:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(J.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(n,s){this.raise(It.EnumBooleanMemberNotInitialized,n,s)}flowEnumErrorInvalidMemberInitializer(n,s){return this.raise(s.explicitType?s.explicitType==="symbol"?It.EnumInvalidMemberInitializerSymbolType:It.EnumInvalidMemberInitializerPrimaryType:It.EnumInvalidMemberInitializerUnknownType,n,s)}flowEnumErrorNumberMemberNotInitialized(n,s){this.raise(It.EnumNumberMemberNotInitialized,n,s)}flowEnumErrorStringMemberInconsistentlyInitialized(n,s){this.raise(It.EnumStringMemberInconsistentlyInitialized,n,s)}flowEnumMemberInit(){const n=this.state.startLoc,s=()=>this.match(8)||this.match(4);switch(this.state.type){case 131:{const i=this.parseNumericLiteral(this.state.value);if(s())return{type:"number",loc:i.start,value:i};break}case 130:{const i=this.parseStringLiteral(this.state.value);if(s())return{type:"string",loc:i.start,value:i};break}case 81:case 82:{const i=this.parseBooleanLiteral(this.match(81));if(s())return{type:"boolean",loc:i.start,value:i}}}return{type:"invalid",loc:n}}flowEnumMemberRaw(){const n=this.state.startLoc,s=this.parseIdentifier(!0),i=this.eat(25)?this.flowEnumMemberInit():{type:"none",loc:n};return{id:s,init:i}}flowEnumCheckExplicitTypeMismatch(n,s,i){const{explicitType:o}=s;o!==null&&o!==i&&this.flowEnumErrorInvalidMemberInitializer(n,s)}flowEnumMembers({enumName:n,explicitType:s}){const i=new Set,o={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]};let l=!1;for(;!this.match(4);){if(this.eat(17)){l=!0;break}const c=this.startNode(),{id:u,init:d}=this.flowEnumMemberRaw(),p=u.name;if(p==="")continue;/^[a-z]/.test(p)&&this.raise(It.EnumInvalidMemberName,u,{memberName:p,suggestion:p[0].toUpperCase()+p.slice(1),enumName:n}),i.has(p)&&this.raise(It.EnumDuplicateMemberName,u,{memberName:p,enumName:n}),i.add(p);const h={enumName:n,explicitType:s,memberName:p};switch(c.id=u,d.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(d.loc,h,"boolean"),c.init=d.value,o.booleanMembers.push(this.finishNode(c,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(d.loc,h,"number"),c.init=d.value,o.numberMembers.push(this.finishNode(c,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(d.loc,h,"string"),c.init=d.value,o.stringMembers.push(this.finishNode(c,"EnumStr
5638ingMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(d.loc,h);case"none":switch(s){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(d.loc,h);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(d.loc,h);break;default:o.defaultedMembers.push(this.finishNode(c,"EnumDefaultedMember"))}}this.match(4)||this.expect(8)}return{members:o,hasUnknownMembers:l}}flowEnumStringMembers(n,s,{enumName:i}){if(n.length===0)return s;if(s.length===0)return n;if(s.length>n.length){for(const o of n)this.flowEnumErrorStringMemberInconsistentlyInitialized(o,{enumName:i});return s}else{for(const o of s)this.flowEnumErrorStringMemberInconsistentlyInitialized(o,{enumName:i});return n}}flowEnumParseExplicitType({enumName:n}){if(!this.eatContextual(98))return null;if(!or(this.state.type))throw this.raise(It.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:n});const{value:s}=this.state;return this.next(),s!=="boolean"&&s!=="number"&&s!=="string"&&s!=="symbol"&&this.raise(It.EnumInvalidExplicitType,this.state.startLoc,{enumName:n,invalidEnumType:s}),s}flowEnumBody(n,s){const i=s.name,o=s.start,l=this.flowEnumParseExplicitType({enumName:i});this.expect(2);const{members:c,hasUnknownMembers:u}=this.flowEnumMembers({enumName:i,explicitType:l});switch(n.hasUnknownMembers=u,l){case"boolean":return n.explicitType=!0,n.members=c.booleanMembers,this.expect(4),this.finishNode(n,"EnumBooleanBody");case"number":return n.explicitType=!0,n.members=c.numberMembers,this.expect(4),this.finishNode(n,"EnumNumberBody");case"string":return n.explicitType=!0,n.members=this.flowEnumStringMembers(c.stringMembers,c.defaultedMembers,{enumName:i}),this.expect(4),this.finishNode(n,"EnumStringBody");case"symbol":return n.members=c.defaultedMembers,this.expect(4),this.finishNode(n,"EnumSymbolBody");default:{const d=()=>(n.members=[],this.expect(4),this.finishNode(n,"EnumStringBody"));n.explicitType=!1;const p=c.booleanMembers.length,h=c.numberMembers.length,f=c.stringMembers.length,x=c.defaultedMembers.length;if(!p&&!h&&!f&&!x)return d();if(!p&&!h)return n.members=this.flowEnumStringMembers(c.stringMembers,c.defaultedMembers,{enumName:i}),this.expect(4),this.finishNode(n,"EnumStringBody");if(!h&&!f&&p>=x){for(const g of c.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(g.start,{enumName:i,memberName:g.id.name});return n.members=c.booleanMembers,this.expect(4),this.finishNode(n,"EnumBooleanBody")}else if(!p&&!f&&h>=x){for(const g of c.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(g.start,{enumName:i,memberName:g.id.name});return n.members=c.numberMembers,this.expect(4),this.finishNode(n,"EnumNumberBody")}else return this.raise(It.EnumInconsistentMemberValues,o,{enumName:i}),d()}}}flowParseEnumDeclaration(n){const s=this.parseIdentifier();return n.id=s,n.body=this.flowEnumBody(this.startNode(),s),this.finishNode(n,"EnumDeclaration")}jsxParseOpeningElementAfterName(n){return this.shouldParseTypes()&&(this.match(43)||this.match(47))&&(n.typeArguments=this.flowParseTypeParameterInstantiationInExpression()),super.jsxParseOpeningElementAfterName(n)}isLookaheadToken_lt(){const n=this.nextTokenStart();if(this.input.charCodeAt(n)===60){const s=this.input.charCodeAt(n+1);return s!==60&&s!==61}return!1}reScan_lt_gt(){const{type:n}=this.state;n===43?(this.state.pos-=1,this.readToken_lt()):n===44&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){const{type:n}=this.state;return n===47?(this.state.pos-=2,this.finishOp(43,1),43):n}maybeUnwrapTypeCastExpression(n){return n.type==="TypeCastExpression"?n.expression:n}},EY={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",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
5638:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",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:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",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
5638:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},IY=/\r\n|[\r\n\u2028\u2029]/,Nf=new RegExp(IY.source,"g");function gu(e){switch(e){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function m2(e,t,r){for(let n=t;n<r;n++)if(gu(e.charCodeAt(n)))return!0;return!1}const Ky=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,Yy=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function OY(e){switch(e){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}const RY={AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:e})=>`Expected corresponding JSX closing tag for <${e}>.`,MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:({unexpected:e,HTMLEntity:t})=>`Unexpected token \`${e}\`. Did you mean \`${t}\` or \`{'${e}'}\`?`,UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"},Ji=Za`jsx`(RY);function Oo(e){return e?e.type==="JSXOpeningFragment"||e.type==="JSXClosingFragment":!1}function au(e){if(e.type==="JSXIdentifier")return e.name;if(e.type==="JSXNamespacedName")return e.namespace.name+":"+e.name.name;if(e.type==="JSXMemberExpression")return au(e.object)+"."+au(e.property);throw new Error("Node had unexpected type: "+e.type)}const DY=e=>class extends e{jsxReadToken(){let r="",n=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(Ji.UnterminatedJsxContent,this.state.startLoc);const s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:if(this.state.pos===this.state.start){s===60&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(138)):super.getTokenFromCode(s);return}r+=this.input.slice(n,this.state.pos),this.finishToken(137,r);return;case 38:r+=this.input.slice(n,this.state.pos),r+=this.jsxReadEntity(),n=this.state.pos;break;case 62:case 125:this.raise(Ji.UnexpectedToken,this.state.curPosition(),{unexpected:this.input[this.state.pos],HTMLEntity:s===125?"&rbrace;":"&gt;"});default:gu(s)?(r+=this.input.slice(n,this.state.pos),r+=this.jsxReadNewLine(!0),n=this.state.pos):++this.state.pos}}}jsxReadNewLine(r){const n=this.input.charCodeAt(this.state.pos);let s;return++this.state.pos,n===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,s=r?`
5639`:`\r
5640`):s=String.fromCharCode(n),++this.state.curLine,this.state.lineStart=this.state.pos,s}jsxReadString(r){let n="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(J.UnterminatedString,this.state.startLoc);const i=this.input.charCodeAt(this.state.pos);if(i===r)break;i===38?(n+=this.input.slice(s,this.state.pos),n+=this.jsxReadEntity(),s=this.state.pos):gu(i)?(n+=this.input.slice(s,this.state.pos),n+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}n+=this.input.slice(s,this.state.pos++),this.finishToken(130,n)}jsxReadEntity(){const r=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let n=10;this.codePointAtPos(this.state.pos)===120&&(n=16,++this.state.pos);const s=this.readInt(n,void 0,!1,"bail");if(s!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(s)}else{let n=0,s=!1;for(;n++<10&&this.state.pos<this.length&&!(s=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(s){const i=this.input.slice(r,this.state.pos),o=EY[i];if(++this.state.pos,o)return o}}return this.state.pos=r,"&"}jsxReadWord(){let r;const n=this.state.pos;do r=this.input.charCodeAt(++this.state.pos);while(ec(r)||r===45);this.finishToken(136,this.input.slice(n,this.state.pos))}jsxParseIdentifier(){const r=this.startNode();return this.match(136)?r.name=this.state.value:O1(this.state.type)?r.name=Jo(this.state.type):this.unexpected(),this.next(),this.finishNode(r,"JSXIdentifier")}jsxParseNamespacedName(){const r=this.state.startLoc,n=this.jsxParseIdentifier();if(!this.eat(10))return n;const s=this.startNodeAt(r);return s.namespace=n,s.name=this.jsxParseIdentifier(),this.finishNode(s,"JSXNamespacedName")}jsxParseElementName(){const r=this.state.startLoc;let n=this.jsxParseNamespacedName();if(n.type==="JSXNamespacedName")return n;for(;this.eat(12);){const s=this.startNodeAt(r);s.object=n,s.property=this.jsxParseIdentifier(),n=this.finishNode(s,"JSXMemberExpression")}return n}jsxParseAttributeValue(){let r;switch(this.state.type){case 2:return r=this.startNode(),this.setContext(Nr.brace),this.next(),r=this.jsxParseExpressionContainer(r,Nr.j_oTag),r.expression.type==="JSXEmptyExpression"&&this.raise(Ji.AttributeIsEmpty,r),r;case 138:case 130:return this.parseExprAtom();default:throw this.raise(Ji.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){const r=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(r,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(r){return this.next(),r.expression=this.parseExpression(),this.setContext(Nr.j_expr),this.state.canStartJSXElement=!0,this.expect(4),this.finishNode(r,"JSXSpreadChild")}jsxParseExpressionContainer(r,n){var s;if(this.match(4))r.expression=this.jsxParseEmptyExpression();else{const i=this.parseExpression();i.type==="SequenceExpression"&&!((s=i.extra)!=null&&s.parenthesized)&&this.raise(Ji.UnexpectedSequenceExpression,i.expressions[1]),r.expression=i}return this.setContext(n),this.state.canStartJSXElement=!0,this.expect(4),this.finishNode(r,"JSXExpressionContainer")}jsxParseAttribute(){if(this.match(2)){const n=this.startNode();return this.setContext(Nr.brace),this.next(),this.expect(17),n.argument=this.parseMaybeAssignAllowIn(),this.setContext(Nr.j_oTag),this.state.canStartJSXElement=!0,this.expect(4),this.finishNode(n,"JSXSpreadAttribute")}const r=this.startNode();return r.name=this.jsxParseNamespacedName(),r.value=this.eat(25)?this.jsxParseAttributeValue():null,this.finishNode(r,"JSXAttribute")}jsxParseOpeningElementAt(r){if(this.eat(139)){const s=this.startNodeAt(r);return this.finishNode(s,"JSXOpeningFragment")}const n=this.startNodeAt(r);return n.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(n)}jsxParseOpeningElementAfterName(r){const n=[];for(;!this.match(52)&&!this.match(139);)n.push(this.jsxParseAttribute());return r.attributes=n,r.selfClosing=this.eat(52),this.expect(139),this.finishNode(r,"JSXOpeningElement")}jsxParseClosingElementAt(r){if(this.eat(139)){const s=this.startNodeAt(r);return this.finishNode(s,"JSXClosingFragment")}const n=this.startNodeAt(r);return n.name=this.jsxParseElementName(),this.expect(139),this.finishNode(n,"JSXClosingElement")}jsxParseElementAt(r){const n=this.startNodeAt(r),s=[],i=this.jsxParseOpeningElementAt(r);let o=null;if(!i.selfClosing){e:for(;;)switch(this.state.type){case 138:if(r=this.state.startLoc,this.next(),this.eat(52)){this.setLoc(r),o=this.jsxParseClosingElementAt(r);break e}s.push(this.jsxParseElementAt(r));break;case 137:s.push(this.parseLiteral(this.state.value,"JSXText"));break;case 2:{const l=this.startNode();this.setContext(Nr.brace),this.next(),this.match(17)?s.push(this.jsxParseSpreadChild(l)):s.push(this.jsxParseExpressionContainer(l,Nr.j_expr));break}default:this.unexpected()}Oo(i)&&!Oo(o)&&o!==null?this.raise(Ji.MissingClosingTagFragment,o):!Oo(i)&&Oo(o)?this.raise(Ji.MissingClosingTagElement,o,{openingTagName:au(i.name)}):!Oo(i)&&!Oo(o)&&au(o.name)!==au(i.name)&&this.raise(Ji.MissingClosingTagElement,o,{openingTagName:au(i.name)})}if(Oo(i)?(n.openingFragment=i,n.closingFragment=o):(n.openingElement=i,n.closingElement=o),n.children=s,this.match(43))throw this.raise(Ji.UnwrappedAdjacentJSXElements,this.state.startLoc);return Oo(i)?this.finishNode(n,"JSXFragment"):this.finishNode(n,"JSXElement")}jsxParseElement(){const r=this.state.startLoc;return this.next(),this.jsxParseElementAt(r)}setContext(r){const{context:n}=this.state;n[n.length-1]=r}parseExprAtom(r){return this.match(138)?this.jsxParseElement():this.match(43)&&this.input.charCodeAt(this.state.pos)!==33?(this.replaceToken(138),this.jsxParseElement()):super.parseExprAtom(r)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(r){const n=this.curContext();if(n===Nr.j_expr){this.jsxReadToken();return}
5640if(n===Nr.j_oTag||n===Nr.j_cTag){if(Si(r)){this.jsxReadWord();return}if(r===62){++this.state.pos,this.finishToken(139);return}if((r===34||r===39)&&n===Nr.j_oTag){this.jsxReadString(r);return}}if(r===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos,this.finishToken(138);return}super.getTokenFromCode(r)}updateContext(r){const{context:n,type:s}=this.state;if(s===52&&r===138)n.splice(-2,2,Nr.j_cTag),this.state.canStartJSXElement=!1;else if(s===138)n.push(Nr.j_oTag);else if(s===139){const i=n[n.length-1];i===Nr.j_oTag&&r===52||i===Nr.j_cTag?(n.pop(),this.state.canStartJSXElement=n[n.length-1]===Nr.j_expr):(this.setContext(Nr.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=rY(s)}};class MY extends D1{constructor(){super(...arguments);Qe(this,"tsNames",new Map)}}class LY extends M1{constructor(){super(...arguments);Qe(this,"importsStack",[])}get inTSNamespace(){const r=this.scopeStack;return r.length>=2&&r[r.length-1].flags===0&&(r[r.length-2].flags&2048)>0}createScope(r){return this.importsStack.push(new Set),new MY(r)}enter(r){r&3072&&this.importsStack.push(new Set),super.enter(r)}exit(){const r=super.exit();return r&3072&&this.importsStack.pop(),r}hasImport(r,n){const s=this.importsStack.length;if(this.importsStack[s-1].has(r))return!0;if(!n&&s>1){for(let i=0;i<s-1;i++)if(this.importsStack[i].has(r))return!0}return!1}declareName(r,n,s){if(n&4096){this.hasImport(r,!0)&&this.parser.raise(J.VarRedeclaration,s,{identifierName:r}),this.importsStack[this.importsStack.length-1].add(r);return}const i=this.currentScope();let o=i.tsNames.get(r)||0;if(n&1024){this.maybeExportDefined(i,r),i.tsNames.set(r,o|16);return}super.declareName(r,n,s),n&2&&(n&1||(this.checkRedeclarationInScope(i,r,n,s),this.maybeExportDefined(i,r)),o=o|1),n&256&&(o=o|2),n&512&&(o=o|4),n&128&&(o=o|8),o&&i.tsNames.set(r,o)}isRedeclaredInScope(r,n,s){const i=r.tsNames.get(n);if((i&2)>0){if(s&256){const o=(s&512)>0,l=(i&4)>0;return o!==l}return!0}return s&128&&(i&8)>0?r.names.get(n)&2?!!(s&1):!1:s&2&&(i&1)>0?!0:super.isRedeclaredInScope(r,n,s)}checkLocalExport(r){const{name:n}=r;if(this.hasImport(n))return;const s=this.scopeStack.length;for(let i=s-1;i>=0;i--){const l=this.scopeStack[i].tsNames.get(n);if((l&1)>0||(l&16)>0)return}super.checkLocalExport(r)}}class $Y{constructor(){Qe(this,"sawUnambiguousESM",!1);Qe(this,"ambiguousScriptDifferentAst",!1)}sourceToOffsetPos(t){return t+this.startIndex}offsetToSourcePos(t){return t-this.startIndex}hasPlugin(t){if(typeof t=="string")return this.plugins.has(t);{const[r,n]=t;if(!this.hasPlugin(r))return!1;const s=this.plugins.get(r);for(const i of Object.keys(n))if((s==null?void 0:s[i])!==n[i])return!1;return!0}}getPluginOption(t,r){var n;return(n=this.plugins.get(t))==null?void 0:n[r]}}function kI(e,t){e.trailingComments===void 0?e.trailingComments=t:e.trailingComments.unshift(...t)}function FY(e,t){e.leadingComments===void 0?e.leadingComments=t:e.leadingComments.unshift(...t)}function Fp(e,t){e.innerComments===void 0?e.innerComments=t:e.innerComments.unshift(...t)}function Ro(e,t,r){let n=null,s=t.length;for(;n===null&&s>0;)n=t[--s];n===null||n.start>r.start?Fp(e,r.comments):kI(n,r.comments)}class BY extends $Y{addComment(t){this.filename&&(t.loc.filename=this.filename);const{commentsLen:r}=this.state;this.comments.length!==r&&(this.comments.length=r),this.comments.push(t),this.state.commentsLen++}processComment(t){const{commentStack:r}=this.state,n=r.length;if(n===0)return;let s=n-1;const i=r[s];i.start===t.end&&(i.leadingNode=t,s--);const o=t.start;for(;s>=0;s--){const l=r[s],c=l.end;if(c>o)l.containingNode=t,this.finalizeComment(l),r.splice(s,1);else{c===o&&(l.trailingNode=t);break}}}finalizeComment(t){const{comments:r}=t;if(t.leadingNode!==null||t.trailingNode!==null)t.leadingNode!==null&&kI(t.leadingNode,r),t.trailingNode!==null&&FY(t.trailingNode,r);else{const n=t.containingNode,s=t.start;if(this.input.charCodeAt(this.offsetToSourcePos(s)-1)===44)switch(n.type){case"ObjectExpression":case"ObjectPattern":Ro(n,n.properties,t);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":Ro(n,n.arguments,t);break;case"ImportExpression":Ro(n,[n.source,n.options??null],t);break;
5640case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":Ro(n,n.params,t);break;case"ArrayExpression":case"ArrayPattern":Ro(n,n.elements,t);break;case"ExportNamedDeclaration":case"ImportDeclaration":Ro(n,n.specifiers,t);break;case"TSEnumBody":Ro(n,n.members,t);break;case"TSInterfaceBody":Ro(n,n.body,t);break;default:Fp(n,r)}else Fp(n,r)}}finalizeRemainingComments(){const{commentStack:t}=this.state;for(let r=t.length-1;r>=0;r--)this.finalizeComment(t[r]);this.state.commentStack=[]}resetPreviousNodeTrailingComments(t){const{commentStack:r}=this.state,{length:n}=r;if(n===0)return;const s=r[n-1];s.leadingNode===t&&(s.leadingNode=null)}takeSurroundingComments(t,r,n){const{commentStack:s}=this.state,i=s.length;if(i===0)return;let o=i-1;for(;o>=0;o--){const l=s[o],c=l.end;if(l.start===n)l.leadingNode=t;else if(c===r)l.trailingNode=t;else if(c<r)break}}}class L1{constructor(){Qe(this,"flags",2048);Qe(this,"startIndex");Qe(this,"curLine");Qe(this,"lineStart");Qe(this,"startLoc");Qe(this,"endLoc");Qe(this,"errors",[]);Qe(this,"noArrowAt",[]);Qe(this,"noArrowParamsConversionAt",[]);Qe(this,"labels",[]);Qe(this,"commentsLen",0);Qe(this,"commentStack",[]);Qe(this,"pos",0);Qe(this,"type",135);Qe(this,"value",null);Qe(this,"start",0);Qe(this,"end",0);Qe(this,"lastTokEndLoc",null);Qe(this,"lastTokStartLoc",null);Qe(this,"context",[Nr.brace]);Qe(this,"firstInvalidTemplateEscapePos",null);Qe(this,"strictErrors",new Map);Qe(this,"tokensLength",0)}get strict(){return(this.flags&1)>0}set strict(t){t?this.flags|=1:this.flags&=-2}init({strictMode:t,sourceType:r,startIndex:n,startLine:s,startColumn:i}){this.strict=t===!1?!1:t===!0?!0:r==="module",this.startIndex=n,this.curLine=s,this.lineStart=-i,this.startLoc=this.endLoc=new ta(s,i,n)}get canStartArrow(){return(this.flags&2)>0}set canStartArrow(t){t?this.flags|=2:this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(t){t?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(t){t?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(t){t?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(t){t?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(t){t?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(t){t?this.flags|=128:this.flags&=-129}get inConditionalConsequent(){return(this.flags&256)>0}set inConditionalConsequent(t){t?this.flags|=256:this.flags&=-257}get inHackPipelineBody(){return(this.flags&512)>0}set inHackPipelineBody(t){t?this.flags|=512:this.flags&=-513}get seenTopicReference(){return(this.flags&1024)>0}set seenTopicReference(t){t?this.flags|=1024:this.flags&=-1025}get canStartJSXElement(){return(this.flags&2048)>0}set canStartJSXElement(t){t?this.flags|=2048:this.flags&=-2049}get containsEsc(){return(this.flags&4096)>0}set containsEsc(t){t?this.flags|=4096:this.flags&=-4097}get hasTopLevelAwait(){return(this.flags&8192)>0}set hasTopLevelAwait(t){t?this.flags|=8192:this.flags&=-8193}curPosition(){return new ta(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){const t=new L1;return t.flags=this.flags,t.startIndex=this.startIndex,t.curLine=this.curLine,t.lineStart=this.lineStart,t.startLoc=this.startLoc,t.endLoc=this.endLoc,t.errors=this.errors.slice(),t.noArrowAt=this.noArrowAt.slice(),t.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),t.labels=this.labels.slice(),t.commentsLen=this.commentsLen,t.commentStack=this.commentStack.slice(),t.pos=this.pos,t.type=this.type,t.value=this.value,t.start=this.start,t.end=this.end,t.lastTokEndLoc=this.lastTokEndLoc,t.lastTokStartLoc=this.lastTokStartLoc,t.context=this.context.slice(),t.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,t.strictErrors=this.strictErrors,t.tokensLength=this.tokensLength,t}}var UY=function(t){return t>=48&&t<=57};const g2={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},kf={bin:e=>e===48||e===49,oct:e=>e>=48&&e<=55,dec:e=>e>=48&&e<=57,hex:e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102};function x2(e,t,r,n,s,i){const o=r,l=n,c=s;let u="",d=null,p=r;const{length:h}=t;for(;;){if(r>=h){i.unterminated(o,l,c),u+=t.slice(p,r);break}const f=t.charCodeAt(r);if(zY(e,f,t,r)){u+=t.slice(p,r);break}if(f===92){u+=t.slice(p,r);
5640const x=qY(t,r,n,s,e==="template",i);x.ch===null&&!d?d={pos:r,lineStart:n,curLine:s}:u+=x.ch,{pos:r,lineStart:n,curLine:s}=x,p=r}else f===8232||f===8233?(++r,++s,n=r):f===10||f===13?e==="template"?(u+=t.slice(p,r)+`
5641`,++r,f===13&&t.charCodeAt(r)===10&&++r,++s,p=n=r):i.unterminated(o,l,c):++r}return{pos:r,str:u,firstInvalidLoc:d,lineStart:n,curLine:s}}function zY(e,t,r,n){return e==="template"?t===96||t===36&&r.charCodeAt(n+1)===123:t===(e==="double"?34:39)}function qY(e,t,r,n,s,i){const o=!s;t++;const l=u=>({pos:t,ch:u,lineStart:r,curLine:n}),c=e.charCodeAt(t++);switch(c){case 110:return l(`
5642`);case 114:return l("\r");case 120:{let u;return{code:u,pos:t}=k0(e,t,r,n,2,!1,o,i),l(u===null?null:String.fromCharCode(u))}case 117:{let u;return{code:u,pos:t}=CI(e,t,r,n,o,i),l(u===null?null:String.fromCodePoint(u))}case 116:return l("	");case 98:return l("\b");case 118:return l("\v");case 102:return l("\f");case 13:e.charCodeAt(t)===10&&++t;case 10:r=t,++n;case 8232:case 8233:return l("");case 56:case 57:if(s)return l(null);i.strictNumericEscape(t-1,r,n);default:if(c>=48&&c<=55){const u=t-1;let p=/^[0-7]+/.exec(e.slice(u,t+2))[0],h=parseInt(p,8);h>255&&(p=p.slice(0,-1),h=parseInt(p,8)),t+=p.length-1;const f=e.charCodeAt(t);if(p!=="0"||f===56||f===57){if(s)return l(null);i.strictNumericEscape(u,r,n)}return l(String.fromCharCode(h))}return l(String.fromCharCode(c))}}function k0(e,t,r,n,s,i,o,l){const c=t;let u;return{n:u,pos:t}=SI(e,t,r,n,16,s,i,!1,l,!o),u===null&&(o?l.invalidEscapeSequence(c,r,n):t=c-1),{code:u,pos:t}}function SI(e,t,r,n,s,i,o,l,c,u){const d=t,p=s===16?g2.hex:g2.decBinOct,h=s===16?kf.hex:s===10?kf.dec:s===8?kf.oct:kf.bin;let f=!1,x=0;for(let g=0,y=i??1/0;g<y;++g){const b=e.charCodeAt(t);let v;if(b===95&&l!=="bail"){const k=e.charCodeAt(t-1),N=e.charCodeAt(t+1);if(l){if(Number.isNaN(N)||!h(N)||p.has(k)||p.has(N)){if(u)return{n:null,pos:t};c.unexpectedNumericSeparator(t,r,n)}}else{if(u)return{n:null,pos:t};c.numericSeparatorInEscapeSequence(t,r,n)}++t;continue}if(b>=97?v=b-97+10:b>=65?v=b-65+10:UY(b)?v=b-48:v=1/0,v>=s){if(v<=9&&u)return{n:null,pos:t};if(v<=9&&c.invalidDigit(t,r,n,s))v=0;else if(o)v=0,f=!0;else break}++t,x=x*s+v}return t===d||i!=null&&t-d!==i||f?{n:null,pos:t}:{n:x,pos:t}}function CI(e,t,r,n,s,i){const o=e.charCodeAt(t);let l;if(o===123){if(++t,{code:l,pos:t}=k0(e,t,r,n,e.indexOf("}",t)-t,!0,s,i),++t,l!==null&&l>1114111)if(s)i.invalidCodePoint(t,r,n);else return{code:null,pos:t}}else({code:l,pos:t}=k0(e,t,r,n,4,!1,s,i));return{code:l,pos:t}}function Fd(e,t,r){return new ta(r,e-t,e)}const HY=new Set([103,109,115,105,121,117,100,118]);
5642class WY{constructor(t){const r=t.startIndex||0;this.type=t.type,this.value=t.value,this.start=r+t.start,this.end=r+t.end,this.loc=new Dm(t.startLoc,t.endLoc)}}let Sf;class VY extends BY{constructor(r,n){super();Qe(this,"isLookahead");Qe(this,"tokens",[]);Qe(this,"errorHandlers_readInt",{invalidDigit:(r,n,s,i)=>this.optionFlags&4096?(this.raise(J.InvalidDigit,Fd(r,n,s),{radix:i}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(J.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(J.UnexpectedNumericSeparator)});Qe(this,"errorHandlers_readCodePoint",{...this.errorHandlers_readInt,invalidEscapeSequence:this.errorBuilder(J.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(J.InvalidCodePoint)});Qe(this,"errorHandlers_readStringContents_string",{...this.errorHandlers_readCodePoint,strictNumericEscape:(r,n,s)=>{this.recordStrictModeErrors(J.StrictNumericEscape,Fd(r,n,s))},unterminated:(r,n,s)=>{throw this.raise(J.UnterminatedString,Fd(r-1,n,s))}});Qe(this,"errorHandlers_readStringContents_template",{...this.errorHandlers_readCodePoint,strictNumericEscape:this.errorBuilder(J.StrictNumericEscape),unterminated:(r,n,s)=>{throw this.raise(J.UnterminatedTemplate,Fd(r,n,s))}});this.state=new L1,this.state.init(r),this.input=n,this.length=n.length,this.comments=[],this.isLookahead=!1,(!Sf||Sf.length<(this.length+1)*2)&&(Sf=new Uint32Array((this.length+1)*2)),this.locData=Sf}setLoc(r){const n=this.offsetToSourcePos(r.index);this.locData[n*2]=r.line,this.locData[n*2+1]=r.column}getLoc(r){const n=this.offsetToSourcePos(r);return new ta(this.locData[n*2],this.locData[n*2+1],r)}pushToken(r){this.tokens.length=this.state.tokensLength,this.tokens.push(r),++this.state.tokensLength}next(){this.checkKeywordEscapes(),this.optionFlags&512&&this.pushToken(new WY(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(r){return this.match(r)?(this.next(),!0):!1}match(r){return this.state.type===r}createLookaheadState(r){return{pos:r.pos,value:null,type:r.type,start:r.start,end:r.end,context:[this.curContext()],inType:r.inType,startLoc:r.startLoc,lastTokEndLoc:r.lastTokEndLoc,curLine:r.curLine,lineStart:r.lineStart,curPosition:r.curPosition}}lookahead(){const r=this.state;this.state=this.createLookaheadState(r),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;const n=this.state;return this.state=r,n}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(r){return Ky.lastIndex=r,Ky.test(this.input)?Ky.lastIndex:r}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(r){return this.input.charCodeAt(this.nextTokenStartSince(r))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(r){return Yy.lastIndex=r,Yy.test(this.input)?Yy.lastIndex:r}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(r){let n=this.input.charCodeAt(r);if((n&64512)===55296&&++r<this.input.length){const s=this.input.charCodeAt(r);(s&64512)===56320&&(n=65536+((n&1023)<<10)+(s&1023))}return n}setStrict(r){this.state.strict=r,r&&(this.state.strictErrors.forEach(([n,s])=>this.raise(n,s)),this.state.strictErrors.clear())}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){if(this.skipSpace(),this.state.start=this.state.pos,this.isLookahead||(this.state.startLoc=this.state.curPosition()),this.state.pos>=this.length){this.finishToken(135);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(r){let n;this.isLookahead||(n=this.state.curPosition());const s=this.state.pos,i=this.input.indexOf(r,s+2);if(i===-1)throw this.raise(J.UnterminatedComment,this.state.curPosition());for(this.state.pos=i+r.length,Nf.lastIndex=s+2;Nf.test(this.input)&&Nf.lastIndex<=i;)++this.state.curLine,this.state.lineStart=Nf.lastIndex;if(this.isLookahead)return;const o={type:"CommentBlock",value:this.input.slice(s+2,i),start:this.sourceToOffsetPos(s),end:this.sourceToOffsetPos(i+r.length),loc:new Dm(n,this.state.curPosition())};return this.optionFlags&512&&this.pushToken(o),o}skipLineComment(r){const n=this.state.pos;let s;this.isLookahead||(s=this.state.curPosition());let i=this.input.charCodeAt(this.state.pos+=r);if(this.state.pos<this.length)for(;!gu(i)&&++this.state.pos<this.length;)i=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;const o=this.state.pos,c={type:"CommentLine",value:this.input.slice(n+r,o),start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(o),loc:new Dm(s,this.state.curPosition())};return this.optionFlags&512&&this.pushToken(c),c}skipSpace(){const r=this.state.pos,n=this.optionFlags&8192?[]:null;e:for(;this.state.pos<this.length;){const s=this.input.charCodeAt(this.state.pos);switch(s){case 32:case 160:case 9:++this.state.pos;break;case 13:this.input.charCodeAt(this.state.pos+1)===10&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{const i=this.skipBlockComment("*/");i!==void 0&&(this.addComment(i),n==null||n.push(i));break}case 47:{const i=this.skipLineComment(2);i!==void 0&&(this.addComment(i),n==null||n.push(i));break}default:break e}break;default:if(OY(s))++this.state.pos;else if(s===45&&!this.inModule&&this.optionFlags&16384){const i=this.state.pos;if(this.input.charCodeAt(i+1)===45&&this.input.charCodeAt(i+2)===62&&(r===0||this.state.lineStart>r)){const o=this.skipLineComment(3);o!==void 0&&(this.addComment(o),n==null||n.push(o))}else break e}else if(s===60&&!this.inModule&&this.optionFlags&16384){const i=this.state.pos;if(this.input.charCodeAt(i+1)===33&&this.input.charCodeAt(i+2)===45&&this.input.charCodeAt(i+3)===45){const o=this.skipLineComment(4);o!==void 0&&(this.addComment(o),n==null||n.push(o))}else break e}else break e}}if((n==null?void 0:n.length)>0){const s=this.state.pos,i={start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(s),comments:n,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(i)}}finishToken(r,n){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();const s=this.state.type;this.state.type=r,this.state.value=n,this.isLookahead||this.updateContext(s)}replaceToken(r){this.state.type=r,this.updateContext()}readToken_numberSign(){if(this.state.pos===0&&this.readToken_interpreter())return;const r=this.state.pos+1,n=this.codePointAtPos(r);if(n>=48&&n<=57)throw this.raise(J.UnexpectedDigitAfterHash,this.state.curPosition());Si(n)?(++this.state.pos,this.finishToken(134,this.readWord1(n))):n===92?(++this.state.pos,this.finishToken(134,this.readWord1())):this.finishOp(23,1)}readToken_dot(){const r=this.input.charCodeAt(this.state.pos+1);if(r>=48&&r<=57){this.readNumber(!0);return}r===46&&this.input.charCodeAt(this.state.pos+2)===46?(this.state.pos+=3,this.finishToken(17)):(++this.state.pos,this.finishToken(12))}readToken_slash(){this.input.charCodeAt(this.state.pos+1)===61?this.finishOp(27,2):this.finishOp(52,1)}readToken_interpreter(){if(this.state.pos!==0||this.length<2)return!1;let r=this.input.charCodeAt(this.state.pos+1);if(r!==33)return!1;const n=this.state.pos;for(this.state.pos+=1;!gu(r)&&++this.state.pos<this.length;)r=this.input.charCodeAt(this.state.pos);const s=this.input.slice(n+2,this.state.pos);return this.finishToken(24,s),!0}readToken_mult_modulo(r){let n=r===42?51:50,s=1,i=this.input.charCodeAt(this.state.pos+1);r===42&&i===42&&(s++,i=this.input.charCodeAt(this.state.pos+2),n=53),i===61&&!this.state.inType&&(s++,n=r===37?29:26),this.finishOp(n,s)}readToken_pipe_amp(r){const n=this.input.charCodeAt(this.state.pos+1);if(n===r){this.input.charCodeAt(this.state.pos+2)===61?this.finishOp(26,3):this.finishOp(r===124?37:38,2);return}if(r===124&&n===62){this.finishOp(35,2);return}if(n===61){this.finishOp(26,2);return}this.finishOp(r===124?39:41,1)}readToken_caret(){const r=this.input.charCodeAt(this.state.pos+1);r===61&&!this.state.inType?this.finishOp(28,2):r===94&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])?(this.finishOp(33,2),this.input.codePointAt(this.state.pos)===94&&this.unexpected()):this.finishOp(40,1)}readToken_atSign(){this.input.charCodeAt(this.state.pos+1)===64&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])?this.finishOp(34,2):this.finishOp(22,1)}readToken_plus_min(r){const n=this.input.charCodeAt(this.state.pos+1);if(n===r){this.finishOp(30,2);return}n===61?this.finishOp(26,2):this.finishOp(49,1)}readToken_lt(){const{pos:r}=this.state,n=this.input.charCodeAt(r+1);if(n===60){if(this.input.charCodeAt(r+2)===61){this.finishOp(26,3);return}this.finishOp(47,2);return}if(n===61){this.finishOp(45,2);return}this.finishOp(43,1)}readToken_gt(){const{pos:r}=this.state,n=this.input.charCodeAt(r+1);if(n===62){const s=this.input.charCodeAt(r+2)===62?3:2;if(this.input.charCodeAt(r+s)===61){this.finishOp(26,s+1);return}this.finishOp(48,s);return}if(n===61){this.finishOp(45,2);return}this.finishOp(44,1)}readToken_eq_excl(r){const n=this.input.charCodeAt(this.state.pos+1);if(n===61){this.finishOp(42,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(r===61&&n===62){this.state.pos+=2,this.finishToken(15);return}this.finishOp(r===61?25:31,1)}readToken_question(){const r=this.input.charCodeAt(this.state.pos+1),n=this.input.charCodeAt(this.state.pos+2);r===63?n===61?this.finishOp(26,3):this.finishOp(36,2):r===46&&!(n>=48&&n<=57)?(this.state.pos+=2,this.finishToken(14)):(++this.state.pos,this.finishToken(13))}getTokenFromCode(r){switch(r){case 46:this.readToken_dot();return;case 40:++this.state.pos,this.finishToken(6);return;case 41:++this.state.pos,this.finishToken(7);return;case 59:++this.state.pos,this.finishToken(9);return;case 44:++this.state.pos,this.finishToken(8);return;case 91:++this.state.pos,this.finishToken(0);return;case 93:++this.state.pos,this.finishToken(1);return;case 123:++this.state.pos,this.finishToken(2);return;case 125:++this.state.pos,this.finishToken(4);return;case 58:this.hasPlugin("functionBind")&&this.input.charCodeAt(this.state.pos+1)===58?this.finishOp(11,2):(++this.state.pos,this.finishToken(10));return;case 63:this.readToken_question();return;case 96:this.readTemplateToken();return;case 48:{const n=this.input.charCodeAt(this.state.pos+1);if(n===120||n===88){this.readRadixNumber(16);return}if(n===111||n===79){this.readRadixNumber(8);return}if(n===98||n===66){this.readRadixNumber(2);return}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:this.readNumber(!1);return;case 34:case 39:this.readString(r);return;case 47:this.readToken_slash();return;case 37:case 42:this.readToken_mult_modulo(r);return;case 124:case 38:this.readToken_pipe_amp(r);return;case 94:this.readToken_caret();return;case 43:case 45:this.readToken_plus_min(r);return;case 60:this.readToken_lt();return;case 62:this.readToken_gt();return;case 61:case 33:this.readToken_eq_excl(r);return;case 126:this.finishOp(32,1);return;case 64:this.readToken_atSign();return;case 35:this.readToken_numberSign();return;case 92:this.readWord();return;default:if(Si(r)){this.readWord(r);return}}throw this.raise(J.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(r)})}finishOp(r,n){const s=this.input.slice(this.state.pos,this.state.pos+n);this.state.pos+=n,this.finishToken(r,s)}readRegexp(){const r=this.state.startLoc,n=this.state.start+1;let s,i,{pos:o}=this.state;for(;;++o){if(o>=this.length)throw this.raise(J.UnterminatedRegExp,Oa(r,1));const d=this.input.charCodeAt(o);if(gu(d))throw this.raise(J.UnterminatedRegExp,Oa(r,1));if(s)s=!1;else{if(d===91)i=!0;else if(d===93&&i)i=!1;else if(d===47&&!i)break;s=d===92}}const l=this.input.slice(n,o);++o;let c="";const u=()=>Oa(r,o+2-n);for(;o<this.length;){const d=this.codePointAtPos(o),p=String.fromCharCode(d);if(HY.has(d))d===118?c.includes("u")&&this.raise(J.IncompatibleRegExpUVFlags,u()):d===117&&c.includes("v")&&this.raise(J.IncompatibleRegExpUVFlags,u()),c.includes(p)&&this.raise(J.DuplicateRegExpFlags,u());else if(ec(d)||d===92)this.raise(J.MalformedRegExpFlags,u());else break;++o,c+=p}this.state.pos=o,this.finishToken(133,{pattern:l,flags:c})}readInt(r,n,s=!1,i=!0){const{n:o,pos:l}=SI(this.input,this.state.pos,this.state.lineStart,this.state.curLine,r,n,s,i,this.errorHandlers_readInt,!1);return this.state.pos=l,o}readRadixNumber(r){const n=this.state.pos,s=this.state.curPosition();let i=!1;this.state.pos+=2;const o=this.readInt(r);if(o==null&&this.raise(J.InvalidDigit,Oa(s,2),{radix:r}),this.input.charCodeAt(this.state.pos)===110&&(++this.state.pos,i=!0),Si(this.codePointAtPos(this.state.pos)))throw this.raise(J.NumberIdentifier,this.state.curPosition());if(i){const c=this.input.slice(n,this.state.pos).replace(/[_n]/g,"");this.finishToken(132,c);return}this.finishToken(131,o)}readNumber(r){const n=this.state.pos,s=this.state.curPosition();let i=!1,o=!1,l=!1;!r&&this.readInt(10)===null&&this.raise(J.InvalidNumber,this.state.curPosition());const c=this.state.pos-n>=2&&this.input.charCodeAt(n)===48;if(c){const h=this.input.slice(n,this.state.pos);
5642if(this.recordStrictModeErrors(J.StrictOctalLiteral,s),!this.state.strict){const f=h.indexOf("_");f>0&&this.raise(J.ZeroDigitNumericSeparator,Oa(s,f))}l=c&&!/[89]/.test(h)}let u=this.input.charCodeAt(this.state.pos);u===46&&!l&&(++this.state.pos,this.readInt(10),i=!0,u=this.input.charCodeAt(this.state.pos)),(u===69||u===101)&&!l&&(u=this.input.charCodeAt(++this.state.pos),(u===43||u===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(J.InvalidOrMissingExponent,s),i=!0,u=this.input.charCodeAt(this.state.pos));const d=this.input.slice(n,this.state.pos).replaceAll("_","");if(u===110&&((i||c)&&this.raise(J.InvalidBigIntLiteral,s),++this.state.pos,o=!0),Si(this.codePointAtPos(this.state.pos)))throw this.raise(J.NumberIdentifier,this.state.curPosition());if(o){this.finishToken(132,d);return}const p=l?parseInt(d,8):parseFloat(d);this.finishToken(131,p)}readCodePoint(r){const{code:n,pos:s}=CI(this.input,this.state.pos,this.state.lineStart,this.state.curLine,r,this.errorHandlers_readCodePoint);return this.state.pos=s,n}readString(r){const{str:n,pos:s,curLine:i,lineStart:o}=x2(r===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=s+1,this.state.lineStart=o,this.state.curLine=i,this.finishToken(130,n)}readTemplateContinuation(){this.match(4)||this.unexpected(null,4),this.state.pos--,this.readTemplateToken()}readTemplateToken(){const r=this.input[this.state.pos],{str:n,firstInvalidLoc:s,pos:i,curLine:o,lineStart:l}=x2("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=i+1,this.state.lineStart=l,this.state.curLine=o,s&&(this.state.firstInvalidTemplateEscapePos=new ta(s.curLine,s.pos-s.lineStart,this.sourceToOffsetPos(s.pos))),this.input.codePointAt(i)===96?this.finishToken(20,s?null:r+n+"`"):(this.state.pos++,this.finishToken(21,s?null:r+n+"${"))}recordStrictModeErrors(r,n){const s=n.index;this.state.strict&&!this.state.strictErrors.has(s)?this.raise(r,n):this.state.strictErrors.set(s,[r,n])}readWord1(r){this.state.containsEsc=!1;let n="";const s=this.state.pos;let i=this.state.pos;for(r!==void 0&&(this.state.pos+=r<=65535?1:2);this.state.pos<this.length;){const o=this.codePointAtPos(this.state.pos);if(ec(o))this.state.pos+=o<=65535?1:2;else if(o===92){this.state.containsEsc=!0,n+=this.input.slice(i,this.state.pos);const l=this.state.curPosition(),c=this.state.pos===s?Si:ec;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(J.MissingUnicodeEscape,this.state.curPosition()),i=this.state.pos-1;continue}++this.state.pos;const u=this.readCodePoint(!0);u!==null&&(c(u)||this.raise(J.EscapedCharNotAnIdentifier,l),n+=String.fromCodePoint(u)),i=this.state.pos}else break}return n+this.input.slice(i,this.state.pos)}readWord(r){const n=this.readWord1(r),s=C1.get(n);s!==void 0?this.finishToken(s,Jo(s)):this.finishToken(128,n)}checkKeywordEscapes(){const{type:r}=this.state;O1(r)&&this.state.containsEsc&&this.raise(J.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Jo(r)})}raise(r,n,s={}){const i=n instanceof ta?n:typeof n=="number"?this.getLoc(n):this.optionFlags&256?n.loc.start:this.getLoc(n.start),o=n instanceof ta?i.index:typeof n=="number"?n:n.start,l=r(i,o,s);if(!(this.optionFlags&4096))throw l;return this.isLookahead||this.state.errors.push(l),l}raiseOverwrite(r,n,s={}){const i=n instanceof ta?n:this.optionFlags&256?n.loc.start:this.getLoc(n.start),o=n instanceof ta?i.index:n.start,l=this.state.errors;for(let c=l.length-1;c>=0;c--){const u=l[c];if(u.pos===o)return l[c]=r(i,o,s);if(u.pos<o)break}return this.raise(r,i,s)}updateContext(r){}unexpected(r,n){throw this.raise(J.UnexpectedToken,r??this.state.startLoc,{expected:n?Jo(n):null})}expectPlugin(r,n){if(this.hasPlugin(r))return!0;throw this.raise(J.MissingPlugin,n??this.state.startLoc,{missingPlugin:[r]})}expectOnePlugin(r){if(!r.some(n=>this.hasPlugin(n)))throw this.raise(J.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:r})}errorBuilder(r){return(n,s,i)=>{this.raise(r,Fd(n,s,i))}}}class GY{constructor(){Qe(this,"privateNames",new Set);Qe(this,"loneAccessors",new Map);Qe(this,"undefinedPrivateNames",new Map)}}class KY{constructor(t){Qe(this,"parser");Qe(this,"stack",[]);this.parser=t}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new GY)}exit(){const t=this.stack.pop(),r=this.current();for(const[n,s]of Array.from(t.undefinedPrivateNames))r?r.undefinedPrivateNames.has(n)||r.undefinedPrivateNames.set(n,s):this.parser.raise(J.InvalidPrivateFieldResolution,s,{identifierName:n})}declarePrivateName(t,r,n){const{privateNames:s,loneAccessors:i,undefinedPrivateNames:o}=this.current();let l=s.has(t);if(r&3){const c=l&&i.get(t);if(c){const u=c&4,d=r&4,p=c&3,h=r&3;l=p===h||u!==d,l||i.delete(t)}else l||i.set(t,r)}l&&this.parser.raise(J.PrivateNameRedeclaration,n,{identifierName:t}),s.add(t),o.delete(t)}usePrivateName(t,r){let n;for(n of this.stack)if(n.privateNames.has(t))return;n?n.undefinedPrivateNames.set(t,r):this.parser.raise(J.InvalidPrivateFieldResolution,r,{identifierName:t})}}class px{constructor(t=0){this.type=t}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}}class PI extends px{constructor(r){super(r);Qe(this,"declarationErrors",new Map)}recordDeclarationError(r,n){this.declarationErrors.set(n,r)}clearDeclarationError(r){this.declarationErrors.delete(r)}
5642iterateErrors(r){this.declarationErrors.forEach(r)}}class YY{constructor(t){Qe(this,"parser");Qe(this,"stack",[new px]);this.parser=t}enter(t){this.stack.push(t)}exit(){this.stack.pop()}recordParameterInitializerError(t,r){const{stack:n}=this;let s=n.length-1,i=n[s];for(;!i.isCertainlyParameterDeclaration();){if(i.canBeArrowParameterDeclaration())i.recordDeclarationError(t,r);else return;i=n[--s]}this.parser.raise(t,r)}recordArrowParameterBindingError(t,r){const{stack:n}=this,s=n[n.length-1],i=r.start;if(s.isCertainlyParameterDeclaration())this.parser.raise(t,i);else if(s.canBeArrowParameterDeclaration())s.recordDeclarationError(t,i);else return}recordAsyncArrowParametersError(t){const{stack:r}=this;let n=r.length-1,s=r[n];for(;s.canBeArrowParameterDeclaration();)s.type===2&&s.recordDeclarationError(J.AwaitBindingIdentifier,t),s=r[--n]}validateAsPattern(){const{stack:t}=this,r=t[t.length-1];r.canBeArrowParameterDeclaration()&&r.iterateErrors((n,s)=>{this.parser.raise(n,s);let i=t.length-2,o=t[i];for(;o.canBeArrowParameterDeclaration();)o.clearDeclarationError(s),o=t[--i]})}}function JY(){return new px(3)}function XY(){return new PI(1)}function ZY(){return new PI(2)}function AI(){return new px}class QY{constructor(){Qe(this,"stacks",[])}enter(t){this.stacks.push(t)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(this.currentFlags()&2)>0}get hasYield(){return(this.currentFlags()&1)>0}get hasReturn(){return(this.currentFlags()&4)>0}get hasIn(){return(this.currentFlags()&8)>0}get inFSharpPipelineDirectBody(){return(this.currentFlags()&16)===0}}function om(e,t){return(e?2:0)|(t?1:0)}class eJ extends VY{addExtra(t,r,n,s=!0){if(!t)return;let{extra:i}=t;i==null&&(i={},t.extra=i),s?i[r]=n:Object.defineProperty(i,r,{enumerable:s,value:n})}isContextual(t){return this.state.type===t&&!this.state.containsEsc}isUnparsedContextual(t,r){if(this.input.startsWith(r,t)){const n=this.input.charCodeAt(t+r.length);return!(ec(n)||(n&64512)===55296)}return!1}isLookaheadContextual(t){const r=this.nextTokenStart();return this.isUnparsedContextual(r,t)}eatContextual(t){return this.isContextual(t)?(this.next(),!0):!1}expectContextual(t,r){if(!this.eatContextual(t)){if(r!=null)throw this.raise(r,this.state.startLoc);this.unexpected(null,t)}}canInsertSemicolon(){return this.match(135)||this.match(4)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return m2(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return m2(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(9)||this.canInsertSemicolon()}semicolon(t=!0){(t?this.isLineTerminator():this.eat(9))||this.raise(J.MissingSemicolon,this.state.lastTokEndLoc)}expect(t,r){this.eat(t)||this.unexpected(r,t)}tryParse(t,r=this.state.clone()){const n={node:null};try{const s=t((i=null)=>{throw n.node=i,n});if(this.state.errors.length>r.errors.length){const i=this.state;return this.state=r,this.state.tokensLength=i.tokensLength,{node:s,error:i.errors[r.errors.length],thrown:!1,aborted:!1,failState:i}}return{node:s,error:null,thrown:!1,aborted:!1,failState:null}}catch(s){const i=this.state;if(this.state=r,s instanceof SyntaxError)return{node:null,error:s,thrown:!0,aborted:!1,failState:i};if(s===n)return{node:n.node,error:null,thrown:!1,aborted:!0,failState:i};throw s}}checkExpressionErrors(t,r){if(!t)return!1;const{shorthandAssignLoc:n,doubleProtoLoc:s,privateKeyLoc:i,optionalParametersLoc:o,voidPatternLoc:l}=t,c=!!n||!!s||!!o||!!i||!!l;if(!r)return c;n!=null&&this.raise(J.InvalidCoverInitializedName,n),s!=null&&this.raise(J.DuplicateProto,s),i!=null&&this.raise(J.UnexpectedPrivateField,i),o!=null&&this.unexpected(o),l!=null&&this.raise(J.InvalidCoverDiscardElement,l)}isLiteralPropertyName(){return gI(this.state.type)}isPrivateName(t){return t.type==="PrivateName"}getPrivateNameSV(t){return t.id.name}hasPropertyAsPrivateName(t){return(t.type==="MemberExpression"||t.type==="OptionalMemberExpression")&&this.isPrivateName(t.property)}
5642isObjectProperty(t){return t.type==="ObjectProperty"}isObjectMethod(t){return t.type==="ObjectMethod"}initializeScopes(t=this.options.sourceType==="module"){const r=this.state.labels;this.state.labels=[];const n=this.exportedIdentifiers;this.exportedIdentifiers=new Set;const s=this.inModule;this.inModule=t;const i=this.scope,o=this.getScopeHandler();this.scope=new o(this,t);const l=this.prodParam;this.prodParam=new QY;const c=this.classScope;this.classScope=new KY(this);const u=this.expressionScope;return this.expressionScope=new YY(this),()=>{this.state.labels=r,this.exportedIdentifiers=n,this.inModule=s,this.scope=i,this.prodParam=l,this.classScope=c,this.expressionScope=u}}enterInitialScopes(){let t=0;(this.inModule||this.optionFlags&1)&&(t|=2),this.optionFlags&32&&(t|=1);const r=!this.inModule&&this.options.sourceType==="commonjs";(r||this.optionFlags&2)&&(t|=4),this.prodParam.enter(t);let n=r?514:1;this.optionFlags&4&&(n|=512),this.optionFlags&16&&(n|=48),this.scope.enter(n)}checkDestructuringPrivate(t){const{privateKeyLoc:r}=t;r!==null&&this.expectPlugin("destructuringPrivate",r)}}class lm{constructor(){Qe(this,"shorthandAssignLoc",null);Qe(this,"doubleProtoLoc",null);Qe(this,"privateKeyLoc",null);Qe(this,"optionalParametersLoc",null);Qe(this,"voidPatternLoc",null)}}class sp{constructor(t,r,n,s){Qe(this,"type","");this.start=n,this.end=0,s!==void 0&&(this.loc=new Dm(s)),t&128&&(this.range=[n,0]),s!==void 0&&r&&(this.loc.filename=r)}}const y2=sp.prototype;class tJ extends eJ{createPosition(t){return t}startNode(){const{startLoc:t}=this.state;return this.setLoc(t),this.startNodeAt(t)}startNodeAt(t){const{optionFlags:r,filename:n}=this;return r&256?new sp(r,n,t.index,this.createPosition(t)):new sp(r,n,t.index)}startNodeAtNode(t){const{optionFlags:r,filename:n}=this;return r&256?new sp(r,n,t.start,t.loc.start):new sp(r,n,t.start)}finishNode(t,r){return this.finishNodeAt(t,r,this.state.lastTokEndLoc)}finishNodeAt(t,r,n){t.type=r,t.end=n.index;const{optionFlags:s}=this;return s&256&&(t.loc.end=this.createPosition(n)),s&128&&(t.range[1]=n.index),s&8192&&this.processComment(t),t}finishNodeAtNode(t,r,n){t.type=r,t.end=n.end;const{optionFlags:s}=this;return s&256&&(t.loc.end=n.loc.end),s&128&&(t.range[1]=t.end),s&8192&&this.processComment(t),t}resetStartLocation(t,r){t.start=r.index;const{optionFlags:n}=this;n&256&&(t.loc.start=this.createPosition(r)),n&128&&(t.range[0]=r.index)}resetEndLocation(t,r=this.state.lastTokEndLoc){t.end=r.index;const{optionFlags:n}=this;n&256&&(t.loc.end=this.createPosition(r)),n&128&&(t.range[1]=r.index)}resetStartLocationFromNode(t,r){t.start=r.start;const{optionFlags:n}=this;n&256&&(t.loc.start=r.loc.start),n&128&&(t.range[0]=r.start)}resetEndLocationFromNode(t,r){t.end=r.end;const{optionFlags:n}=this;n&256&&(t.loc.end=r.loc.end),n&128&&(t.range[1]=r.end)}castNodeTo(t,r){return t.type=r,t}cloneIdentifier(t){const{type:r,start:n,end:s,loc:i,range:o,name:l}=t,c=Object.create(y2);return c.type=r,c.start=n,c.end=s,c.loc=i,c.range=o,c.name=l,t.extra&&(c.extra=t.extra),c}cloneStringLiteral(t){const{type:r,start:n,end:s,loc:i,range:o,extra:l}=t,c=Object.create(y2);return c.type=r,c.start=n,c.end=s,c.loc=i,c.range=o,c.extra=l,c.value=t.value,c}}const S0=e=>e.type==="ParenthesizedExpression"?S0(e.expression):e;class nJ extends tJ{toAssignable(t,r=!1){var s,i,o;let n;switch((t.type==="ParenthesizedExpression"||(s=t.extra)!=null&&s.parenthesized)&&(n=S0(t),r?n.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(J.InvalidParenthesizedAssignment,t):n.type!=="CallExpression"&&n.type!=="MemberExpression"&&!this.isOptionalMemberExpression(n)&&this.raise(J.InvalidParenthesizedAssignment,t):this.raise(J.InvalidParenthesizedAssignment,t)),t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(t,"ObjectPattern");for(let l=0,c=t.properties.length,u=c-1;l<c;l++){const d=t.properties[l],p=l===u;this.toAssignableObjectExpressionProp(d,p,r),p&&d.type==="RestElement"&&((i=t.extra)!=null&&i.trailingCommaLoc)&&this.raise(J.RestTrailingComma,t.extra.trailingCommaLoc)}break;case"ObjectProperty":{const{key:l,value:c}=t;this.isPrivateName(l)&&this.classScope.usePrivateName(this.getPrivateNameSV(l),l.start),this.toAssignable(c,r);break}case"SpreadElement":throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");case"ArrayExpression":this.castNodeTo(t,"ArrayPattern"),this.toAssignableList(t.elements,(o=t.extra)==null?void 0:o.trailingCommaLoc,r);break;case"AssignmentExpression":t.operator!=="="&&this.raise(J.MissingEqInAssignment,this.optionFlags&256?t.left.loc.end:t.left),this.castNodeTo(t,"AssignmentPattern"),delete t.operator,t.left.type==="VoidPattern"&&this.raise(J.VoidPatternInitializer,t.left),this.toAssignable(t.left,r);break;case"ParenthesizedExpression":this.toAssignable(n,r);break}}
5642toAssignableObjectExpressionProp(t,r,n){if(t.type==="ObjectMethod")this.raise(t.kind==="get"||t.kind==="set"?J.PatternHasAccessor:J.PatternHasMethod,t.key);else if(t.type==="SpreadElement"){this.castNodeTo(t,"RestElement");const s=t.argument;this.checkToRestConversion(s,!1),this.toAssignable(s,n),r||this.raise(J.RestTrailingComma,t)}else this.toAssignable(t,n)}toAssignableList(t,r,n){const s=t.length-1;for(let i=0;i<=s;i++){const o=t[i];o&&(this.toAssignableListItem(t,i,n),o.type==="RestElement"&&(i<s?this.raise(J.RestTrailingComma,o):r&&this.raise(J.RestTrailingComma,r)))}}toAssignableListItem(t,r,n){const s=t[r];if(s.type==="SpreadElement"){this.castNodeTo(s,"RestElement");const i=s.argument;this.checkToRestConversion(i,!0),this.toAssignable(i,n)}else this.toAssignable(s,n)}isAssignable(t,r){switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{const n=t.properties.length-1;return t.properties.every((s,i)=>s.type!=="ObjectMethod"&&(i===n||s.type!=="SpreadElement")&&this.isAssignable(s))}case"ObjectProperty":return this.isAssignable(t.value);case"SpreadElement":return this.isAssignable(t.argument);case"ArrayExpression":return t.elements.every(n=>n===null||this.isAssignable(n));case"AssignmentExpression":return t.operator==="=";case"ParenthesizedExpression":return this.isAssignable(t.expression);case"MemberExpression":case"OptionalMemberExpression":return!r;default:return!1}}toReferencedList(t,r){return t}parseSpread(t){const r=this.startNode();return this.next(),r.argument=this.parseMaybeAssignAllowIn(t,void 0),this.finishNode(r,"SpreadElement")}parseRestBinding(){const t=this.startNode();this.next();const r=this.parseBindingAtom();return r.type==="VoidPattern"&&this.raise(J.UnexpectedVoidPattern,r),t.argument=r,this.finishNode(t,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{const t=this.startNode();return this.next(),t.elements=this.parseBindingList(1,93,1),this.finishNode(t,"ArrayPattern")}case 2:return this.parseObjectLike(4,!0);case 84:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(t,r,n){const s=n&1,i=[];let o=!0;for(;!this.eat(t);)if(o?o=!1:this.expect(8),s&&this.match(8))i.push(null);else{if(this.eat(t))break;if(this.match(17)){let l=this.parseRestBinding();if(n&2&&(l=this.parseFunctionParamType(l)),i.push(l),!this.checkCommaAfterRest(r)){this.expect(t);break}}else{const l=[];if(n&2)for(this.match(22)&&this.hasPlugin("decorators")&&this.raise(J.UnsupportedParameterDecorator,this.state.startLoc);this.match(22);)l.push(this.parseDecorator());i.push(this.parseBindingElement(n,l))}}return i}parseBindingRestProperty(t){return this.next(),this.hasPlugin("discardBinding")&&this.match(84)?(t.argument=this.parseVoidPattern(null),this.raise(J.UnexpectedVoidPattern,t.argument)):t.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(t,"RestElement")}parseBindingProperty(){const{type:t,startLoc:r}=this.state;if(t===17)return this.parseBindingRestProperty(this.startNode());const n=this.startNode();return t===134?(this.expectPlugin("destructuringPrivate",r),this.classScope.usePrivateName(this.state.value,r),n.key=this.parsePrivateName()):this.parsePropertyName(n),n.method=!1,this.parseObjPropValue(n,r,!1,!1,!0,!1)}parseBindingElement(t,r){const{startLoc:n}=this.state,s=this.parseMaybeDefault();return t&2&&this.parseFunctionParamType(s),r.length&&(s.decorators=r,this.resetStartLocationFromNode(s,r[0])),this.parseMaybeDefault(n,s)}parseFunctionParamType(t){return t}parseMaybeDefault(t,r){if(t??(t=this.state.startLoc),r=r??this.parseBindingAtom(),!this.eat(25))return r;const n=this.startNodeAt(t);return r.type==="VoidPattern"&&this.raise(J.VoidPatternInitializer,r),n.left=r,n.right=this.parseMaybeAssignAllowIn(),this.finishNode(n,"AssignmentPattern")}isValidLVal(t,r,n,s){switch(t){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties";case"VoidPattern":return!0;case"CallExpression":if(!r&&!this.state.strict&&this.optionFlags&16384)return!0}return!1}
5642isOptionalMemberExpression(t){return t.type==="OptionalMemberExpression"}checkLVal(t,r,n=64,s=!1,i=!1,o=!1,l=!1){var y;const c=t.type;if(this.isObjectMethod(t))return;const u=this.isOptionalMemberExpression(t);if(u||c==="MemberExpression"){u&&(this.expectPlugin("optionalChainingAssign",t.start),r.type!=="AssignmentExpression"&&this.raise(J.InvalidLhsOptionalChaining,t,{ancestor:r})),n!==64&&this.raise(J.InvalidPropertyBindingPattern,t);return}if(c==="Identifier"){this.checkIdentifier(t,n,i);const{name:b}=t;s&&(s.has(b)?this.raise(J.ParamDupe,t):s.add(b));return}else c==="VoidPattern"&&r.type==="CatchClause"&&this.raise(J.VoidPatternCatchClauseParam,t);const d=S0(t);l||(l=d.type==="CallExpression"&&(d.callee.type==="Import"||d.callee.type==="Super"));const p=this.isValidLVal(c,l,!(o||(y=t.extra)!=null&&y.parenthesized)&&r.type==="AssignmentExpression",n);if(p===!0)return;if(p===!1){const b=n===64?J.InvalidLhs:J.InvalidLhsBinding;this.raise(b,t,{ancestor:r});return}let h,f;typeof p=="string"?(h=p,f=c==="ParenthesizedExpression"):[h,f]=p;const x=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:r,g=t[h];if(Array.isArray(g))for(const b of g)b&&this.checkLVal(b,x,n,s,i,f,!0);else g&&this.checkLVal(g,x,n,s,i,f,l)}checkIdentifier(t,r,n=!1){this.state.strict&&(n?NI(t.name,this.inModule):jI(t.name))&&(r===64?this.raise(J.StrictEvalArguments,t,{referenceName:t.name}):this.raise(J.StrictEvalArgumentsBinding,t,{bindingName:t.name})),r&8192&&t.name==="let"&&this.raise(J.LetInLexicalBinding,t),r&64||this.declareNameFromIdentifier(t,r)}declareNameFromIdentifier(t,r){this.scope.declareName(t.name,r,t.start)}checkToRestConversion(t,r){switch(t.type){case"ParenthesizedExpression":this.checkToRestConversion(t.expression,r);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(r)break;default:this.raise(J.InvalidRestAssignmentPattern,t)}}checkCommaAfterRest(t){return this.match(8)?(this.raise(this.lookaheadCharCode()===t?J.RestTrailingComma:J.ElementAfterRest,this.state.startLoc),!0):!1}}class rJ extends nJ{checkProto(t,r,n){if(t.type==="SpreadElement"||this.isObjectMethod(t)||t.computed||t.shorthand)return r;const s=t.key;return(s.type==="Identifier"?s.name:s.value)==="__proto__"?(r&&(n?n.doubleProtoLoc===null&&(n.doubleProtoLoc=this.getLoc(s.start)):this.raise(J.DuplicateProto,s)),!0):r}shouldExitDescending(t){var r;return t.type==="ArrowFunctionExpression"&&!((r=t.extra)!=null&&r.parenthesized)}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(135))throw this.raise(J.ParseExpressionEmptyInput,this.state.startLoc);const t=this.parseExpression();if(!this.match(135))throw this.raise(J.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),t.comments=this.comments,t.errors=this.state.errors,this.optionFlags&512&&(t.tokens=_I(this.tokens)),t}parseExpression(t,r){return t?this.disallowInAnd(()=>this.parseExpressionBase(r)):this.allowInAnd(()=>this.parseExpressionBase(r))}parseExpressionBase(t){const r=this.state.startLoc,n=this.parseMaybeAssign(t);if(this.match(8)){const s=this.startNodeAt(r);for(s.expressions=[n];this.eat(8);)s.expressions.push(this.parseMaybeAssign(t));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return n}parseMaybeAssignDisallowIn(t,r){return this.disallowInAnd(()=>this.parseMaybeAssign(t,r))}parseMaybeAssignAllowIn(t,r){return this.allowInAnd(()=>this.parseMaybeAssign(t,r))}setOptionalParametersError(t){t.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(t,r){const n=this.state.startLoc,s=this.isContextual(104);if(s&&this.prodParam.hasYield){this.next();let l=this.parseYield(n);return r&&(l=r.call(this,l,n)),l}let i;t?i=!1:(t=new lm,i=!0),this.state.canStartArrow=!0;let o=this.parseMaybeConditional(t);if(r&&(o=r.call(this,o,n)),sY(this.state.type)){const l=this.startNodeAt(n),c=this.state.value;if(l.operator=c,this.match(25)){this.toAssignable(o,!0),l.left=o;const u=n.index;t.doubleProtoLoc!=null&&t.doubleProtoLoc.index>=u&&(t.doubleProtoLoc=null),t.shorthandAssignLoc!=null&&t.shorthandAssignLoc.index>=u&&(t.shorthandAssignLoc=null),t.privateKeyLoc!=null&&t.privateKeyLoc.index>=u&&(this.checkDestructuringPrivate(t),t.privateKeyLoc=null),t.voidPatternLoc!=null&&t.voidPatternLoc.index>=u&&(t.voidPatternLoc=null)}else l.left=o;return this.next(),l.right=this.parseMaybeAssign(),this.checkLVal(o,this.finishNode(l,"AssignmentExpression"),void 0,void 0,void 0,void 0,c==="||="||c==="&&="||c==="??="),l}else i&&this.checkExpressionErrors(t,!0);if(s){const{type:l}=this.state;if((this.hasPlugin("v8intrinsic")?rp(l):rp(l)&&!this.match(50))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(J.YieldNotInGeneratorFunction,n),this.parseYield(n)}return o}parseMaybeConditional(t){const r=this.state.startLoc,n=this.parseExprOps(t);return this.shouldExitDescending(n)?n:this.parseConditional(n,r,t)}parseConditional(t,r,n){if(this.eat(13)){const s=this.startNodeAt(r);return s.test=t,s.consequent=this.parseMaybeAssignAllowIn(),this.expect(10),s.alternate=this.parseMaybeAssign(),this.finishNode(s,"ConditionalExpression")}return t}parseMaybeUnaryOrPrivate(t){return this.match(134)?this.parsePrivateName():this.parseMaybeUnary(t)}parseExprOps(t){const r=this.state.startLoc,n=this.parseMaybeUnaryOrPrivate(t);return this.shouldExitDescending(n)?n:(this.state.canStartArrow=!1,this.parseExprOp(n,r,-1))}parseExprOp(t,r,n){if(this.isPrivateName(t)){const i=this.getPrivateNameSV(t);(n>=im(54)||!this.prodParam.hasIn||!this.match(54))&&this.raise(J.PrivateInExpectedIn,r,{identifierName:i}),this.classScope.usePrivateName(i,r)}const s=this.state.type;if(h2(s)&&(this.prodParam.hasIn||!this.match(54))){let i=im(s);if(i>n){if(s===35&&(this.expectPlugin("pipelineOperator"),this.prodParam.inFSharpPipelineDirectBody))return t;const o=this.startNodeAt(r);o.left=t,o.operator=this.state.value;const l=s===37||s===38,c=s===36;c&&(i=im(38)),this.next(),o.right=this.parseExprOpRightExpr(s,i);const u=this.finishNode(o,l||c?"LogicalExpression":"BinaryExpression"),d=this.state.type;if(c&&(d===37||d===38)||l&&d===36)throw this.raise(J.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(u,r,n)}}return t}parseExprOpRightExpr(t,r){switch(t){case 35:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>this.parseHackPipeBody());case"fsharp":return this.parseFSharpPipelineBody(r)}default:return this.parseExprOpBaseRightExpr(t,r)}}parseExprOpBaseRightExpr(t,r){const n=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),n,uY(t)?r-1:r)}parseHackPipeBody(){var s;const{startLoc:t}=this.state,r=this.parseMaybeAssign();return GK.has(r.type)&&!((s=r.extra)!=null&&s.parenthesized)&&this.raise(J.PipeUnparenthesizedBody,t,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(J.PipeTopicUnused,t),r}checkExponentialAfterUnary(t){this.match(53)&&this.raise(J.UnexpectedTokenUnaryExponentiation,t.argument)}parseMaybeUnary(t,r){const n=this.state.startLoc,s=this.isContextual(92);if(s&&this.recordAwaitIfAllowed()){this.next();const c=this.parseAwait(n);return r||this.checkExponentialAfterUnary(c),c}const i=this.match(30),o=this.startNode();if(oY(this.state.type)){o.operator=this.state.value,o.prefix=!0,this.state.canStartArrow=!1,this.match(68)&&this.expectPlugin("throwExpressions");const c=this.match(85);if(this.next(),o.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),this.state.strict&&c){const u=o.argument;u.type==="Identifier"?this.raise(J.StrictDelete,o):this.hasPropertyAsPrivateName(u)&&this.raise(J.DeletePrivateField,o)}if(!i)return r||this.checkExponentialAfterUnary(o),this.finishNode(o,"UnaryExpression")}
5642const l=this.parseUpdate(o,i,t);if(s){const{type:c}=this.state;if((this.hasPlugin("v8intrinsic")?rp(c):rp(c)&&!this.match(50))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(J.AwaitNotInAsyncContext,n),this.parseAwait(n)}return l}parseUpdate(t,r,n){if(r){const o=this.finishNode(t,"UpdateExpression");return this.checkLVal(o.argument,o),o}const s=this.state.startLoc;let i=this.parseExprSubscripts(n);if(this.checkExpressionErrors(n,!1))return i;for(;iY(this.state.type)&&!this.canInsertSemicolon();){const o=this.startNodeAt(s);o.operator=this.state.value,o.prefix=!1,o.argument=i,this.next(),this.checkLVal(i,i=this.finishNode(o,"UpdateExpression"))}return i}parseExprSubscripts(t){const r=this.state.startLoc;this.setLoc(r);const n=this.parseExprAtom(t);return this.shouldExitDescending(n)?n:this.parseSubscripts(n,r)}parseSubscripts(t,r,n){const s={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do t=this.parseSubscript(t,r,n,s),s.maybeAsyncArrow=!1;while(!s.stop);return t}parseSubscript(t,r,n,s){const{type:i}=this.state;if(!n&&i===11)return this.parseBind(t,r,s);if(j0(i))return this.parseTaggedTemplateExpression(t,r,s);let o=!1;if(i===14){if(n&&(this.raise(J.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(t,s);s.optionalChainMember=o=!0,this.next()}if(!n&&this.match(6))return this.parseCoverCallAndAsyncArrowHead(t,r,s,o);{const l=this.eat(0);return l||o||this.eat(12)?this.parseMember(t,r,s,l,o):this.stopParseSubscript(t,s)}}stopParseSubscript(t,r){return r.stop=!0,t}parseMember(t,r,n,s,i){const o=this.startNodeAt(r);return o.object=t,o.computed=s,s?(o.property=this.parseExpression(),this.expect(1)):this.match(134)?(t.type==="Super"&&this.raise(J.SuperPrivateField,r),this.classScope.usePrivateName(this.state.value,this.state.startLoc),o.property=this.parsePrivateName()):o.property=this.parseIdentifier(!0),n.optionalChainMember?(o.optional=i,this.finishNode(o,"OptionalMemberExpression")):this.finishNode(o,"MemberExpression")}parseBind(t,r,n){const s=this.startNodeAt(r);s.object=t,this.next();const i=this.match(79),o=this.parseNoCallExpr();if(o.type==="Super"||i&&o.type==="ImportExpression"||o.type==="Import")throw this.raise(J.UnsupportedBindRHS,o);return s.callee=o,n.stop=!0,this.parseSubscripts(this.finishNode(s,"BindExpression"),r,!1)}parseCoverCallAndAsyncArrowHead(t,r,n,s){let i=null;this.next();const o=this.startNodeAt(r);o.callee=t;const{maybeAsyncArrow:l,optionalChainMember:c}=n;l&&(this.expressionScope.enter(ZY()),i=new lm),c&&(o.optional=s),s?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(t.type!=="Super",o,i);let u=this.finishCallExpression(o,c);return l&&this.shouldParseAsyncArrow()&&!s?(n.stop=!0,this.checkDestructuringPrivate(i),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),u=this.parseAsyncArrowFromCallExpression(this.startNodeAt(r),u)):(l&&(this.checkExpressionErrors(i,!0),this.expressionScope.exit()),this.toReferencedList(o.arguments)),u}parseTaggedTemplateExpression(t,r,n){const s=this.startNodeAt(r);return s.tag=t,s.quasi=this.parseTemplate(!0),n.optionalChainMember&&this.raise(J.OptionalChainingNoTemplate,r),this.finishNode(s,"TaggedTemplateExpression")}atPossibleAsyncArrow(t){return t.type==="Identifier"&&t.name==="async"&&this.state.lastTokEndLoc.index===t.end&&!this.canInsertSemicolon()&&t.end-t.start===5&&this.state.canStartArrow}finishCallExpression(t,r){if(t.callee.type==="Import")if(t.arguments.length===0||t.arguments.length>2)this.raise(J.ImportCallArity,t);else for(const n of t.arguments)n.type==="SpreadElement"&&this.raise(J.ImportCallSpreadArgument,n);return this.finishNode(t,r?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,r,n){const s=[];let i=!0;for(;!this.eat(7);){if(i)i=!1;else if(this.expect(8),this.match(7)){r&&this.addTrailingCommaExtraToNode(r),this.next();break}s.push(this.parseExprListItem(7,!1,n,t))}return s}shouldParseAsyncArrow(){return this.match(15)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,r){var n;return this.resetPreviousNodeTrailingComments(r),this.expect(15),this.parseArrowExpression(t,r.arguments,!0,(n=r.extra)==null?void 0:n.trailingCommaLoc),r.innerComments&&Fp(t,r.innerComments),r.callee.trailingComments&&Fp(t,r.callee.trailingComments),t}parseNoCallExpr(){const t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,!0)}parseExprAtom(t){let r,n=null;const{type:s}=this.state;switch(s){case 75:return this.parseSuper();case 79:return r=this.startNode(),this.next(),this.match(12)?this.parseImportMetaPropertyOrPhaseCall(r):this.match(6)?this.optionFlags&1024?this.parseImportCall(r):this.finishNode(r,"Import"):(this.raise(J.UnsupportedImport,this.state.lastTokStartLoc),this.finishNode(r,"Import"));case 74:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case 86:return this.parseDo(this.startNode(),!1);case 52:case 27:return this.readRegexp(),this.parseRegExpLiteral(this.state.value);case 131:return this.parseNumericLiteral(this.state.value);case 132:return this.parseBigIntLiteral(this.state.value);case 130:return this.parseStringLiteral(this.state.value);case 80:return this.parseNullLiteral();case 81:return this.parseBooleanLiteral(!0);case 82:return this.parseBooleanLiteral(!1);case 6:return this.parseParenAndDistinguishExpression(this.state.canStartArrow);case 0:return this.parseArrayLike(1,t);case 2:return this.parseObjectLike(4,!1,t);case 64:return this.parseFunctionOrFunctionSent();case 22:n=this.parseDecorators();case 76:return this.parseClass(this.maybeTakeDecorators(n,this.startNode()),!1);case 73:return this.parseNewOrNewTarget();case 21:case 20:return this.parseTemplate(!1);case 11:{r=this.startNode(),this.next(),r.object=null;const i=r.callee=this.parseNoCallExpr();if(i.type==="MemberExpression")return this.finishNode(r,"BindExpression");throw this.raise(J.UnsupportedBind,i)}case 134:return this.raise(J.PrivateInExpectedIn,this.state.startLoc,{identifierName:this.state.value}),this.parsePrivateName();case 29:return this.parseTopicReferenceThenEqualsSign(50,"%");case 28:return this.parseTopicReferenceThenEqualsSign(40,"^");case 33:case 34:return this.parseTopicReference("hack");case 40:case 50:case 23:{const i=this.getPluginOption("pipelineOperator","proposal");if(i)return this.parseTopicReference(i);throw this.unexpected()}case 43:{const i=this.input.codePointAt(this.nextTokenStart());throw Si(i)||i===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}
5642default:if(or(s)){if(this.isContextual(123)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();const{canStartArrow:i,containsEsc:o}=this.state,l=this.parseIdentifier();if(!o&&l.name==="async"&&!this.canInsertSemicolon()){const{type:c}=this.state;if(c===64)return this.resetPreviousNodeTrailingComments(l),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(l));if(or(c))return i&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(l)):l;if(c===86)return this.resetPreviousNodeTrailingComments(l),this.parseDo(this.startNodeAtNode(l),!0)}return i&&this.match(15)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(l),[l],!1)):l}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(t,r){const n=this.getPluginOption("pipelineOperator","proposal");if(n)return this.state.type=t,this.state.value=r,this.state.pos--,this.state.end--,this.state.endLoc=Oa(this.state.endLoc,-1),this.parseTopicReference(n);throw this.unexpected()}parseTopicReference(t){const r=this.startNode(),n=this.state.startLoc,s=this.state.type;return this.next(),this.finishTopicReference(r,n,t,s)}finishTopicReference(t,r,n,s){if(this.testTopicReferenceConfiguration(n,r,s))return this.topicReferenceIsAllowedInCurrentContext()||this.raise(J.PipeTopicUnbound,r),this.registerTopicReference(),this.finishNode(t,"TopicReference");throw this.raise(J.PipeTopicUnconfiguredToken,r,{token:Jo(s)})}testTopicReferenceConfiguration(t,r,n){switch(t){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Jo(n)}]);default:throw this.raise(J.PipeTopicRequiresHackPipes,r)}}parseAsyncArrowUnaryFunction(t){this.prodParam.enter(om(!0,this.prodParam.hasYield));const r=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(J.LineTerminatorBeforeArrow,this.state.curPosition()),this.expect(15),this.parseArrowExpression(t,r,!0)}parseDo(t,r){this.expectPlugin("doExpressions"),r&&this.expectPlugin("asyncDoExpressions"),t.async=r,this.next();const n=this.state.labels;return this.state.labels=[],r?(this.prodParam.enter(2),t.body=this.parseBlock(),this.prodParam.exit()):t.body=this.parseBlock(),this.state.labels=n,this.finishNode(t,"DoExpression")}parseSuper(){const t=this.startNode();return this.next(),this.match(6)&&!this.scope.allowDirectSuper?this.raise(J.SuperNotAllowed,t):this.scope.allowSuper||this.raise(J.UnexpectedSuper,t),!this.match(6)&&!this.match(0)&&!this.match(12)&&this.raise(J.UnsupportedSuper,t),this.finishNode(t,"Super")}parsePrivateName(){const t=this.startNode(),r=this.startNodeAt(Oa(this.state.startLoc,1)),n=this.state.value;return this.next(),t.id=this.createIdentifier(r,n),this.finishNode(t,"PrivateName")}parseFunctionOrFunctionSent(){const t=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(12)){const r=this.createIdentifier(this.startNodeAtNode(t),"function");return this.next(),this.match(99)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(t,r,"sent")}return this.parseFunction(t)}parseMetaProperty(t,r,n){t.meta=r;const s=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==n||s)&&this.raise(J.UnsupportedMetaProperty,t.property,{target:r.name,onlyValidPropertyName:n}),this.finishNode(t,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(t){if(this.next(),this.isContextual(101)||this.isContextual(93)){const r=this.isContextual(101);return this.expectPlugin(r?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),t.phase=r?"source":"defer",this.parseImportCall(t)}else{const r=this.createIdentifierAt(this.startNodeAtNode(t),"import",this.state.lastTokStartLoc);return this.isContextual(97)&&(this.inModule||this.raise(J.ImportMetaOutsideModule,r),this.sawUnambiguousESM=!0),this.parseMetaProperty(t,r,"meta")}}parseLiteralAtNode(t,r,n){return this.addExtra(n,"rawValue",t),this.addExtra(n,"raw",this.input.slice(this.offsetToSourcePos(n.start),this.state.end)),n.value=t,this.next(),this.finishNode(n,r)}parseLiteral(t,r){const n=this.startNode();return this.parseLiteralAtNode(t,r,n)}parseStringLiteral(t){return this.parseLiteral(t,"StringLiteral")}parseNumericLiteral(t){return this.parseLiteral(t,"NumericLiteral")}parseBigIntLiteral(t){let r;try{r=BigInt(t)}catch{r=null}return this.parseLiteral(r,"BigIntLiteral")}parseRegExpLiteral(t){const r=this.startNode();return this.addExtra(r,"raw",this.input.slice(this.offsetToSourcePos(r.start),this.state.end)),r.pattern=t.pattern,r.flags=t.flags,this.next(),this.finishNode(r,"RegExpLiteral")}parseBooleanLiteral(t){const r=this.startNode();return r.value=t,this.next(),this.finishNode(r,"BooleanLiteral")}parseNullLiteral(){const t=this.startNode();return this.next(),this.finishNode(t,"NullLiteral")}parseParenAndDistinguishExpression(t){const r=this.state.startLoc;let n;this.next(),this.expressionScope.enter(XY());const s=this.state.startLoc,i=[],o=new lm;let l=!0,c,u;for(;!this.match(7);){if(l)l=!1;else if(this.expect(8,o.optionalParametersLoc===null?null:o.optionalParametersLoc),this.match(7)){u=this.state.startLoc;break}if(this.match(17)){const h=this.state.startLoc;if(c=this.state.startLoc,i.push(this.parseParenItem(this.parseRestBinding(),h)),!this.checkCommaAfterRest(41))break}else i.push(this.parseMaybeAssignAllowInOrVoidPattern(7,o,this.parseParenItem))}const d=this.state.lastTokEndLoc;this.expect(7);let p=this.startNodeAt(r);return t&&this.shouldParseArrow(i)&&(p=this.parseArrow(p))?(this.checkDestructuringPrivate(o),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(p,i,!1),p):(this.expressionScope.exit(),i.length||this.unexpected(this.state.lastTokStartLoc),u&&this.unexpected(u),c&&this.unexpected(c),this.checkExpressionErrors(o,!0),this.toReferencedList(i,!0),i.length>1?(n=this.startNodeAt(s),n.expressions=i,this.finishNode(n,"SequenceExpression"),this.resetEndLocation(n,d)):n=i[0],this.wrapParenthesis(r,n))}wrapParenthesis(t,r){if(!(this.optionFlags&2048))return this.addExtra(r,"parenthesized",!0),this.addExtra(r,"parenStart",t.index),this.takeSurroundingComments(r,t.index,this.state.lastTokEndLoc.index),r;const n=this.startNodeAt(t);return n.expression=r,this.finishNode(n,"ParenthesizedExpression")}shouldParseArrow(t){return!this.canInsertSemicolon()}parseArrow(t){if(this.eat(15))return t}parseParenItem(t,r){return t}parseNewOrNewTarget(){const t=this.startNode();if(this.next(),this.match(12)){const r=this.createIdentifier(this.startNodeAtNode(t),"new");this.next();const n=this.parseMetaProperty(t,r,"target");return this.scope.allowNewTarget||this.raise(J.UnexpectedNewTarget,n),n}return this.parseNew(t)}parseNew(t){if(this.parseNewCallee(t),this.eat(6)){const r=this.parseExprList(7);this.toReferencedList(r),t.arguments=r}else t.arguments=[];return this.finishNode(t,"NewExpression")}parseNewCallee(t){const r=this.match(79),n=this.parseNoCallExpr();t.callee=n,r&&n.type==="ImportExpression"&&this.raise(J.ImportCallNotNewExpression,n,n),n.type==="Import"&&this.raise(J.ImportCallNotNewExpression,n),n.type==="Super"&&this.raise(J.SuperCallNotNewExpression,n)}parseTemplateElement(t){const{start:r,startLoc:n,end:s,value:i}=this.state,o=r+1,l=this.startNodeAt(Oa(n,1));i===null&&(t||this.raise(J.InvalidEscapeSequenceTemplate,Oa(this.state.firstInvalidTemplateEscapePos,1)));const c=this.match(20),u=c?-1:-2,d=s+u;l.value={raw:this.input.slice(o,d).replace(/\r\n?/g,`
5643`),cooked:i===null?null:i.slice(1,u)},l.tail=c,this.next();const p=this.finishNode(l,"TemplateElement");return this.resetEndLocation(p,Oa(this.state.lastTokEndLoc,u)),p}parseTemplate(t){const r=this.startNode();let n=this.parseTemplateElement(t);const s=[n],i=[];for(;!n.tail;)i.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),s.push(n=this.parseTemplateElement(t));return r.expressions=i,r.quasis=s,this.finishNode(r,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(t,r,n){let s=!1,i=!0;const o=this.startNode();for(o.properties=[],this.next();!this.match(t);){if(i)i=!1;else if(this.expect(8),this.match(t)){this.addTrailingCommaExtraToNode(o);break}let c;r?c=this.parseBindingProperty():(c=this.parsePropertyDefinition(n),s=this.checkProto(c,s,n)),o.properties.push(c)}this.next();const l=r?"ObjectPattern":"ObjectExpression";return this.finishNode(o,l)}addTrailingCommaExtraToNode(t){this.addExtra(t,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(t,"trailingCommaLoc",this.state.lastTokStartLoc,!1)}maybeAsyncOrAccessorProp(t){return!t.computed&&t.key.type==="Identifier"&&(this.isLiteralPropertyName()||this.match(0)||this.match(51))}parsePropertyDefinition(t){const r=[];if(this.match(22))for(this.hasPlugin("decorators")&&this.raise(J.UnsupportedPropertyDecorator,this.state.startLoc);this.match(22);)r.push(this.parseDecorator());const n=this.startNode();let s=!1,i=!1,o;if(this.match(17))return r.length&&this.unexpected(),this.parseSpread();r.length&&(n.decorators=r),n.method=!1,t&&(o=this.state.startLoc);let l=this.eat(51);this.parsePropertyNamePrefixOperator(n);const c=this.state.containsEsc;if(this.parsePropertyName(n,t),!l&&!c&&this.maybeAsyncOrAccessorProp(n)){const{key:u}=n,d=u.name;d==="async"&&!this.hasPrecedingLineBreak()&&(s=!0,this.resetPreviousNodeTrailingComments(u),l=this.eat(51),this.parsePropertyName(n)),(d==="get"||d==="set")&&(i=!0,this.resetPreviousNodeTrailingComments(u),n.kind=d,this.match(51)&&(l=!0,this.raise(J.AccessorIsGenerator,this.state.curPosition(),{kind:d}),this.next()),this.parsePropertyName(n))}return this.parseObjPropValue(n,o,l,s,!1,i,t)}getGetterSetterExpectedParamCount(t){return t.kind==="get"?0:1}getObjectOrClassMethodParams(t){return t.params}checkGetterSetterParams(t){var s;const r=this.getGetterSetterExpectedParamCount(t),n=this.getObjectOrClassMethodParams(t);n.length!==r&&this.raise(t.kind==="get"?J.BadGetterArity:J.BadSetterArity,t),t.kind==="set"&&((s=n[n.length-1])==null?void 0:s.type)==="RestElement"&&this.raise(J.BadSetterRestParameter,t)}parseObjectMethod(t,r,n,s,i){if(i){const o=this.parseMethod(t,r,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(o),o}if(n||r||this.match(6))return s&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,r,n,!1,!1,"ObjectMethod")}parseObjectProperty(t,r,n,s){if(t.shorthand=!1,this.eat(10))return t.value=n?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(4,s),this.finishObjectProperty(t);if(!t.computed&&t.key.type==="Identifier"){if(this.checkReservedWord(t.key.name,t.key.start,!0,!1),n)t.value=this.parseMaybeDefault(r,this.cloneIdentifier(t.key));else if(this.match(25)){const i=this.state.startLoc;s!=null?s.shorthandAssignLoc===null&&(s.shorthandAssignLoc=i):this.raise(J.InvalidCoverInitializedName,i),t.value=this.parseMaybeDefault(r,this.cloneIdentifier(t.key))}else t.value=this.cloneIdentifier(t.key);return t.shorthand=!0,this.finishObjectProperty(t)}}finishObjectProperty(t){return this.finishNode(t,"ObjectProperty")}parseObjPropValue(t,r,n,s,i,o,l){const c=this.parseObjectMethod(t,n,s,i,o)||this.parseObjectProperty(t,r,i,l);return c||this.unexpected(),c}parsePropertyName(t,r){if(this.eat(0))t.computed=!0,t.key=this.parseMaybeAssignAllowIn(),this.expect(1);else{const{type:n,value:s}=this.state;let i;if(ti(n))i=this.parseIdentifier(!0);else switch(n){case 131:i=this.parseNumericLiteral(s);break;case 130:i=this.parseStringLiteral(s);break;case 132:i=this.parseBigIntLiteral(s);break;case 134:{const o=this.state.startLoc;r!=null?r.privateKeyLoc===null&&(r.privateKeyLoc=o):this.raise(J.UnexpectedPrivateField,o),i=this.parsePrivateName();break}default:this.unexpected()}t.key=i,n!==134&&(t.computed=!1)}}initFunction(t,r){t.id=null,t.generator=!1,t.async=r}parseMethod(t,r,n,s,i,o,l=!1){this.initFunction(t,n),t.generator=r,this.scope.enter(530|(l?576:0)|(i?32:0)),this.prodParam.enter(om(n,t.generator)),this.parseFunctionParams(t,s);const c=this.parseFunctionBodyAndFinish(t,o,!0);return this.prodParam.exit(),this.scope.exit(),c}parseArrayLike(t,r){const n=this.startNode();return this.next(),n.elements=this.parseExprList(t,!0,r,n),this.finishNode(n,"ArrayExpression")}parseArrowExpression(t,r,n,s){this.scope.enter(518);let i=om(n,!1);return this.match(2)||(i|=this.prodParam.currentFlags()&24),this.prodParam.enter(i),this.initFunction(t,n),r&&this.setArrowFunctionParameters(t,r,s),this.parseFunctionBody(t,!0),this.prodParam.exit(),this.scope.exit(),this.finishNode(t,"ArrowFunctionExpression")}setArrowFunctionParameters(t,r,n){this.toAssignableList(r,n,!1),t.params=r}parseFunctionBodyAndFinish(t,r,n=!1){return this.parseFunctionBody(t,!1,n),this.finishNode(t,r)}parseFunctionBody(t,r,n=!1){const s=r&&!this.match(2);if(this.expressionScope.enter(AI()),s)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,r,!1);else{const i=this.state.strict,o=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),t.body=this.parseBlock(!0,!1,l=>{const c=!this.isSimpleParamList(t.params);l&&c&&this.raise(J.IllegalLanguageModeDirective,(t.kind==="method"||t.kind==="constructor")&&t.key?this.optionFlags&256?t.key.loc.end:t.key:t);const u=!i&&this.state.strict;this.checkParams(t,!this.state.strict&&!r&&!n&&!c,r,u),this.state.strict&&t.id&&this.checkIdentifier(t.id,65,u)}),this.prodParam.exit(),this.state.labels=o}this.expressionScope.exit()}isSimpleParameter(t){return t.type==="Identifier"}isSimpleParamList(t){for(let r=0,n=t.length;r<n;r++)if(!this.isSimpleParameter(t[r]))return!1;return!0}checkParams(t,r,n,s=!0){const i=!r&&new Set,o={type:"FormalParameters"};for(const l of t.params)this.checkLVal(l,o,5,i,s)}parseExprList(t,r,n,s){const i=[];let o=!0;for(;!this.eat(t);){if(o)o=!1;else if(this.expect(8),this.match(t)){s&&this.addTrailingCommaExtraToNode(s),this.next();break}i.push(this.parseExprListItem(t,r,n))}return i}parseExprListItem(t,r,n,s){let i;if(this.match(8))r||this.raise(J.UnexpectedToken,this.state.curPosition(),{unexpected:","}),i=null;else if(this.match(17)){const o=this.state.startLoc;i=this.parseParenItem(this.parseSpread(n),o)}else if(this.match(13)){this.expectPlugin("partialApplication"),s||this.raise(J.UnexpectedArgumentPlaceholder,this.state.startLoc);const o=this.startNode();this.next(),i=this.finishNode(o,"ArgumentPlaceholder")}else i=this.parseMaybeAssignAllowInOrVoidPattern(t,n,this.parseParenItem);return i}parseIdentifier(t){const r=this.startNode(),n=this.parseIdentifierName(t);return this.createIdentifier(r,n)}createIdentifier(t,r){return t.name=r,this.optionFlags&256&&(t.loc.identifierName=r),this.finishNode(t,"Identifier")}createIdentifierAt(t,r,n){return t.name=r,this.optionFlags&256&&(t.loc.identifierName=r),this.finishNodeAt(t,"Identifier",n)}parseIdentifierName(t){let r;const{start:n,type:s}=this.state;ti(s)?r=this.state.value:this.unexpected();const i=nY(s);return t?i&&this.replaceToken(128):this.checkReservedWord(r,this.sourceToOffsetPos(n),i,!1),this.next(),r}checkReservedWord(t,r,n,s){if(t.length>10||!wY(t))return;if(n&&yY(t)){this.raise(J.UnexpectedKeyword,r,{keyword:t});return}if((this.state.strict?s?NI:wI:vI)(t,this.inModule)){this.raise(J.UnexpectedReservedWord,r,{reservedWord:t});return}else if(t==="yield"){if(this.prodParam.hasYield){this.raise(J.YieldBindingIdentifier,r);return}}else if(t==="await"){if(this.prodParam.hasAwait){this.raise(J.AwaitBindingIdentifier,r);return}if(this.scope.inStaticBlock){this.raise(J.AwaitBindingIdentifierInStaticBlock,r);return}this.expressionScope.recordAsyncArrowParametersError(r)}else if(t==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(J.ArgumentsInClass,r);return}}recordAwaitIfAllowed(){const t=this.prodParam.hasAwait;return t&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),t}parseAwait(t,r){const n=t.index;this.setLoc(t);const s=this.startNodeAt(t);return this.expressionScope.recordParameterInitializerError(J.AwaitExpressionFormalParameter,n),this.eat(51)&&this.raise(J.ObsoleteAwaitStar,t),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguou
5643sESM=!0),r||(s.argument=this.parseMaybeUnary(null,!0)),this.finishNode(s,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;const{type:t}=this.state;return t===49||t===6||t===0||j0(t)||t===98&&!this.state.containsEsc||t===133||t===52||this.hasPlugin("v8intrinsic")&&t===50}parseYield(t){this.setLoc(t);const r=this.startNodeAt(t);this.expressionScope.recordParameterInitializerError(J.YieldInParameter,t.index);let n=!1,s=null;if(!this.hasPrecedingLineBreak())switch(n=this.eat(51),this.state.type){case 9:case 135:case 4:case 7:case 1:case 5:case 10:case 8:if(!n)break;default:s=this.parseMaybeAssign()}return r.delegate=n,r.argument=s,this.finishNode(r,"YieldExpression")}parseImportCall(t){this.next();const r=this.parseCallExpressionArguments();if(r.length===0||r.length>2)this.raise(J.ImportCallArity,t,t);else for(const n of r)n.type==="SpreadElement"&&this.raise(J.ImportCallSpreadArgument,n,t);return t.source=r[0],t.options=r[1]??null,this.finishNode(t,"ImportExpression")}withTopicBindingContext(t){const r=this.state.inHackPipelineBody;this.state.inHackPipelineBody=!0;const n=this.state.seenTopicReference;this.state.seenTopicReference=!1;try{return t()}finally{this.state.inHackPipelineBody=r,this.state.seenTopicReference=n}}allowInAnd(t){const r=this.prodParam.currentFlags();if(24&~r){this.prodParam.enter(r|8|16);try{return t()}finally{this.prodParam.exit()}}return t()}disallowInAnd(t){const r=this.prodParam.currentFlags(),n=8&r,s=16&~r;if(n||s){this.prodParam.enter(r&-9|16);try{return t()}finally{this.prodParam.exit()}}return t()}registerTopicReference(){this.state.seenTopicReference=!0}topicReferenceIsAllowedInCurrentContext(){return this.state.inHackPipelineBody}topicReferenceWasUsedInCurrentContext(){return this.state.seenTopicReference}parseFSharpPipelineBody(t){const r=this.state.startLoc;this.prodParam.enter(this.prodParam.currentFlags()&-17);let n;if(this.isContextual(92)&&this.recordAwaitIfAllowed()){this.next(),n=this.parseAwait(r,!0);const s=this.state.type;h2(s)&&s!==35&&(this.prodParam.hasIn||s!==54)&&this.raise(J.PipelineUnparenthesized,r)}else this.state.canStartArrow=!0,n=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,t);return this.prodParam.exit(),n}parseModuleExpression(){this.expectPlugin("moduleBlocks");const t=this.startNode();this.next(),this.match(2)||this.unexpected(null,2);const r=this.startNodeAt(this.state.endLoc);this.next();const n=this.initializeScopes(!0);this.enterInitialScopes();try{t.body=this.parseProgram(r,4,"module")}finally{n()}return this.finishNode(t,"ModuleExpression")}parseVoidPattern(t){this.expectPlugin("discardBinding");const r=this.startNode();return t!=null&&(t.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(r,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(t,r,n){if(r!=null&&this.match(84)){const s=this.lookaheadCharCode();if(s===44||s===(t===1?93:t===4?125:41)||s===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(r))}return this.parseMaybeAssignAllowIn(r,n)}parsePropertyNamePrefixOperator(t){}}const Jy={kind:1},sJ={kind:2},aJ=/[\uD800-\uDFFF]/u,Xy=/in(?:stanceof)?/y;function _I(e){for(let t=0;t<e.length;t++){const r=e[t],{type:n}=r;typeof n=="number"&&(r.type=xI(n))}return e}class iJ extends rJ{parseTopLevel(t,r){return t.program=this.parseProgram(r,135,this.options.sourceType==="module"?"module":"script"),t.comments=this.comments,this.optionFlags&512&&(t.tokens=_I(this.tokens)),this.finishNode(t,"File")}parseProgram(t,r,n){if(t.sourceType=n,t.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(t,!0,!0,r),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(const[i,o]of Array.from(this.scope.undefinedExports))this.raise(J.ModuleExportUndefined,o,{localName:i});this.addExtra(t,"topLevelAwait",this.state.hasTopLevelAwait)}let s;return r===135?s=this.finishNode(t,"Program"):s=this.finishNodeAt(t,"Program",Oa(this.state.startLoc,-1)),s}stmtToDirective(t){const r=this.castNodeTo(t,"Directive"),n=this.castNodeTo(t.expression,"DirectiveLiteral"),s=n.value,i=this.input.slice(this.offsetToSourcePos(n.start),this.offsetToSourcePos(n.end)),o=n.value=i.slice(1,-1);return this.addExtra(n,"raw",i),this.addExtra(n,"rawValue",o),this.addExtra(n,"expressionValue",s),r.value=n,delete t.expression,r}parseInterpreterDirective(){if(!this.match(24))return null;const t=this.startNode();return t.value=this.state.value,this.next(),this.finishNode(t,"InterpreterDirective")}isLet(){return this.isContextual(96)?this.hasFollowingBindingAtom():!1}isUsing(){return this.isContextual(103)?this.nextTokenIsIdentifierOnSameLine():!1}isForUsing(){if(!this.isContextual(103))return!1;const t=this.nextTokenInLineStart(),r=this.codePointAtPos(t);if(this.isUnparsedContextual(t,"of")){const n=this.lookaheadCharCodeSince(t+2);if(n!==61&&n!==58&&n!==59)return!1}return!!(this.chStartsBindingIdentifier(r,t)||this.isUnparsedContextual(t,"void"))}nextTokenIsIdentifierOnSameLine(){const t=this.nextTokenInLineStart(),r=this.codePointAtPos(t);return this.chStartsBindingIdentifier(r,t)}isAwaitUsing(){if(!this.isContextual(92))return!1;let t=this.nextTokenInLineStart();if(this.isUnparsedContextual(t,"using")){t=this.nextTokenInLineStartSince(t+5);const r=this.codePointAtPos(t);if(this.chStartsBindingIdentifier(r,t))return!0}return!1}chStartsBindingIdentifier(t,r){if(Si(t)){if(Xy.lastIndex=r,Xy.test(this.input)){const n=this.codePointAtPos(Xy.lastIndex);if(!ec(n)&&n!==92)return!1}return!0}else return t===92}chStartsBindingPattern(t){return t===91||t===123}hasFollowingBindingAtom(){const t=this.nextTokenStart(),r=this.codePointAtPos(t);return this.chStartsBindingPattern(r)||this.chStartsBindingIdentifier(r,t)}hasInLineFollowingBindingIdentifierOrBrace(){const t=this.nextTokenInLineStart(),r=this.codePointAtPos(t);return r===123||this.chStartsBindingIdentifier(r,t)}allowsUsing(){return(this.scope.inModule||!this.scope.inTopLevel)&&!this.scope.inBareCaseStatement}parseModuleItem(){return this.parseStatementLike(15)}parseStatementListItem(){return this.parseStatementLike(6|(!this.options.annexB||this.state.strict?0:8))}parseStatementOrSloppyAnnexBFunctionDeclaration(t=!1){let r=0;return this.options.annexB&&!this.state.strict&&(r|=4,t&&(r|=8)),this.parseStatementLike(r)}
5643parseStatement(){return this.parseStatementLike(0)}parseStatementLike(t){let r=null;return this.match(22)&&(r=this.parseDecorators(!0)),this.parseStatementContent(t,r)}parseStatementContent(t,r){const n=this.state.type,s=this.startNode(),i=!!(t&2),o=!!(t&4),l=t&1;switch(n){case 56:return this.parseBreakContinueStatement(s,!0);case 59:return this.parseBreakContinueStatement(s,!1);case 60:return this.parseDebuggerStatement(s);case 86:return this.parseDoWhileStatement(s);case 87:return this.parseForStatement(s);case 64:if(this.lookaheadCharCode()===46)break;return o||this.raise(this.state.strict?J.StrictFunction:this.options.annexB?J.SloppyFunctionAnnexB:J.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(s,!1,!i&&o);case 76:return i||this.unexpected(),this.parseClass(this.maybeTakeDecorators(r,s),!0);case 65:return this.parseIfStatement(s);case 66:return this.parseReturnStatement(s);case 67:return this.parseSwitchStatement(s);case 68:return this.parseThrowStatement(s);case 69:return this.parseTryStatement(s);case 92:if(this.isAwaitUsing())return this.allowsUsing()?i?this.recordAwaitIfAllowed()||this.raise(J.AwaitUsingNotInAsyncContext,s):this.raise(J.UnexpectedLexicalDeclaration,s):this.raise(J.UnexpectedUsingDeclaration,s),this.next(),this.parseVarStatement(s,"await using");break;case 103:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?i||this.raise(J.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(J.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(s,"using");case 96:{if(this.state.containsEsc)break;const d=this.nextTokenStart(),p=this.codePointAtPos(d);if(p!==91&&(!i&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(p,d)&&p!==123))break}case 71:i||this.raise(J.UnexpectedLexicalDeclaration,this.state.startLoc);case 70:{const d=this.state.value;return this.parseVarStatement(s,d)}case 88:return this.parseWhileStatement(s);case 72:return this.parseWithStatement(s);case 2:return this.parseBlock();case 9:return this.parseEmptyStatement(s);case 79:{const d=this.lookaheadCharCode();if(d===40||d===46)break}case 78:{!(this.optionFlags&8)&&!l&&this.raise(J.UnexpectedImportExport,this.state.startLoc),this.next();let d;return n===79?d=this.parseImport(s):d=this.parseExport(s,r),this.assertModuleNodeAllowed(d),d}default:if(this.isAsyncFunction())return i||this.raise(J.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(s,!0,!i&&o)}const c=this.state.value,u=this.parseExpression();return or(n)&&u.type==="Identifier"&&this.eat(10)?this.parseLabeledStatement(s,c,u,t):this.parseExpressionStatement(s,u,r)}assertModuleNodeAllowed(t){!(this.optionFlags&8)&&!this.inModule&&this.raise(J.ImportOutsideModule,t)}maybeTakeDecorators(t,r,n){var s;return t&&((s=r.decorators)!=null&&s.length?(this.raise(J.DecoratorsBeforeAfterExport,r.decorators[0]),r.decorators.unshift(...t)):r.decorators=t,this.resetStartLocationFromNode(r,t[0]),n&&this.resetStartLocationFromNode(n,r)),r}canHaveLeadingDecorator(){return this.match(76)}parseDecorators(t){const r=[];do r.push(this.parseDecorator());while(this.match(22));if(this.match(78))t||this.unexpected();else if(!this.canHaveLeadingDecorator())throw this.raise(J.UnexpectedLeadingDecorator,this.state.startLoc);return r}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);const t=this.startNode();if(this.next(),this.hasPlugin("decorators")){const r=this.state.startLoc;let n;if(this.match(6)){const s=this.state.startLoc;this.next(),n=this.parseExpression(),this.expect(7),n=this.wrapParenthesis(s,n);const i=this.state.startLoc;t.expression=this.parseMaybeDecoratorArguments(n,s),t.expression!==n&&this.raise(J.DecoratorArgumentsOutsideParentheses,i)}else{for(n=this.parseIdentifier(!1);this.eat(12);){const s=this.startNodeAt(r);s.object=n,this.match(134)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),s.property=this.parsePrivateName()):s.property=this.parseIdentifier(!0),s.computed=!1,n=this.finishNode(s,"Member
5643Expression")}t.expression=this.parseMaybeDecoratorArguments(n,r)}}else this.state.canStartArrow=!1,t.expression=this.parseExprSubscripts();return this.finishNode(t,"Decorator")}parseMaybeDecoratorArguments(t,r){if(this.eat(6)){const n=this.startNodeAt(r);return n.callee=t,n.arguments=this.parseCallExpressionArguments(),this.toReferencedList(n.arguments),this.finishNode(n,"CallExpression")}return t}parseBreakContinueStatement(t,r){return this.next(),this.isLineTerminator()?t.label=null:(t.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(t,r),this.finishNode(t,r?"BreakStatement":"ContinueStatement")}verifyBreakContinue(t,r){let n;for(n=0;n<this.state.labels.length;++n){const s=this.state.labels[n];if((t.label==null||s.name===t.label.name)&&(s.kind!=null&&(r||s.kind===1)||t.label&&r))break}if(n===this.state.labels.length){const s=r?"BreakStatement":"ContinueStatement";this.raise(J.IllegalBreakContinue,t,{type:s})}}parseDebuggerStatement(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")}parseHeaderExpression(){this.expect(6);const t=this.parseExpression();return this.expect(7),t}parseDoWhileStatement(t){return this.next(),this.state.labels.push(Jy),t.body=this.parseStatement(),this.state.labels.pop(),this.expect(88),t.test=this.parseHeaderExpression(),this.eat(9),this.finishNode(t,"DoWhileStatement")}parseForStatement(t){this.next(),this.state.labels.push(Jy);let r=null;if(this.isContextual(92)&&this.recordAwaitIfAllowed()&&(r=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(6),this.match(9))return r!==null&&this.unexpected(r),this.parseFor(t,null);const n=this.isContextual(96);{const c=this.isAwaitUsing(),u=c||this.isForUsing(),d=n&&this.hasFollowingBindingAtom()||u;if(this.match(70)||this.match(71)||d){const p=this.startNode();let h;c?(h="await using",this.recordAwaitIfAllowed()||this.raise(J.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):h=this.state.value,this.next(),this.parseVar(p,!0,h);const f=this.finishNode(p,"VariableDeclaration"),x=this.match(54);return x&&u&&this.raise(J.ForInUsing,f),(x||this.isContextual(98))&&f.declarations.length===1?this.parseForIn(t,f,r):(r!==null&&this.unexpected(r),this.parseFor(t,f))}}const s=this.isContextual(91),i=new lm,o=this.parseExpression(!0,i),l=this.isContextual(98);if(l&&(n&&this.raise(J.ForOfLet,o),r===null&&s&&o.type==="Identifier"&&this.raise(J.ForOfAsync,o)),l||this.match(54)){this.checkDestructuringPrivate(i),this.toAssignable(o,!0);const c=l?"ForOfStatement":"ForInStatement";return this.checkLVal(o,{type:c}),this.parseForIn(t,o,r)}else this.checkExpressionErrors(i,!0);return r!==null&&this.unexpected(r),this.parseFor(t,o)}parseFunctionStatement(t,r,n){return this.next(),this.parseFunction(t,1|(n?2:0)|(r?8:0))}parseIfStatement(t){return this.next(),t.test=this.parseHeaderExpression(),t.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration(),t.alternate=this.eat(62)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null,this.finishNode(t,"IfStatement")}
5643parseReturnStatement(t){return this.prodParam.hasReturn||this.raise(J.IllegalReturn,this.state.startLoc),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")}parseSwitchStatement(t){this.next(),t.discriminant=this.parseHeaderExpression();const r=t.cases=[];this.expect(2),this.state.labels.push(sJ),this.scope.enter(256);let n;for(let s;!this.match(4);)if(this.match(57)||this.match(61)){const i=this.match(57);n&&this.finishNode(n,"SwitchCase"),r.push(n=this.startNode()),n.consequent=[],this.next(),i?n.test=this.parseExpression():(s&&this.raise(J.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),s=!0,n.test=null),this.expect(10)}else n?n.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),n&&this.finishNode(n,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")}parseThrowStatement(t){return this.next(),this.hasPrecedingLineBreak()&&this.raise(J.NewlineAfterThrow,this.state.lastTokEndLoc),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")}parseCatchClauseParam(){const t=this.parseBindingAtom();return this.scope.enter(this.options.annexB&&t.type==="Identifier"?8:0),this.checkLVal(t,{type:"CatchClause"},9),t}parseTryStatement(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(58)){const r=this.startNode();this.next(),this.match(6)?(this.expect(6),r.param=this.parseCatchClauseParam(),this.expect(7)):(r.param=null,this.scope.enter(0)),r.body=this.parseBlock(!1,!1),this.scope.exit(),t.handler=this.finishNode(r,"CatchClause")}return t.finalizer=this.eat(63)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(J.NoCatchOrFinally,t),this.finishNode(t,"TryStatement")}parseVarStatement(t,r,n=!1){return this.next(),this.parseVar(t,!1,r,n),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(Jy),t.body=this.parseStatement(),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(J.StrictWith,this.state.startLoc),this.next(),t.object=this.parseHeaderExpression(),t.body=this.parseStatement(),this.finishNode(t,"WithStatement")}parseEmptyStatement(t){return this.next(),this.finishNode(t,"EmptyStatement")}parseLabeledStatement(t,r,n,s){for(const o of this.state.labels)o.name===r&&this.raise(J.LabelRedeclaration,n,{labelName:r});const i=aY(this.state.type)?1:this.match(67)?2:null;for(let o=this.state.labels.length-1;o>=0;o--){const l=this.state.labels[o];if(l.statementStart===t.start)l.statementStart=this.sourceToOffsetPos(this.state.start),l.kind=i;else break}return this.state.labels.push({name:r,kind:i,statementStart:this.sourceToOffsetPos(this.state.start)}),t.body=s&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),t.label=n,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,r,n){return t.expression=r,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,r=!0,n){const s=this.startNode();return t&&this.state.strictErrors.clear(),this.expect(2),r&&this.scope.enter(0),this.parseBlockBody(s,t,!1,4,n),r&&this.scope.exit(),this.finishNode(s,"BlockStatement")}isValidDirective(t){return t.type==="ExpressionStatement"&&t.expression.type==="StringLiteral"&&!t.expression.extra.parenthesized}parseBlockBody(t,r,n,s,i){const o=t.body=[],l=t.directives=[];this.parseBlockOrModuleBlockBody(o,r?l:void 0,n,s,i)}parseBlockOrModuleBlockBody(t,r,n,s,i){const o=this.state.strict;let l=!1,c=!1;for(;!this.match(s);){const u=n?this.parseModuleItem():this.parseStatementListItem();if(r&&!c){if(this.isValidDirective(u)){const d=this.stmtToDirective(u);r.push(d),!l&&d.value.value==="use strict"&&(l=!0,this.setStrict(!0));continue}c=!0,this.state.strictErrors.clear()}t.push(u)}i==null||i.call(this,l),o||this.setStrict(!1),this.next()}parseFor(t,r){return t.init=r,this.semicolon(!1),t.test=this.match(9)?null:this.parseExpression(),this.semicolon(!1),t.update=this.match(7)?null:this.parseExpression(),this.expect(7),t.body=this.parseStatement
vendor: 1,489 bytes, line 5643
5643(),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,"ForStatement")}parseForIn(t,r,n){const s=this.match(54);return this.next(),s?n!==null&&this.unexpected(n):t.await=n!==null,r.type==="VariableDeclaration"&&r.declarations[0].init!=null&&(!s||!this.options.annexB||this.state.strict||r.kind!=="var"||r.declarations[0].id.type!=="Identifier")&&this.raise(J.ForInOfLoopInitializer,r,{type:s?"ForInStatement":"ForOfStatement"}),r.type==="AssignmentPattern"&&this.raise(J.InvalidLhs,r,{ancestor:{type:"ForStatement"}}),t.left=r,t.right=s?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(7),t.body=this.parseStatement(),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,s?"ForInStatement":"ForOfStatement")}parseVar(t,r,n,s=!1){const i=t.declarations=[];for(t.kind=n;;){const o=this.startNode();if(this.parseVarId(o,n),o.init=this.eat(25)?r?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,o.init===null&&!s&&(o.id.type!=="Identifier"&&!(r&&(this.match(54)||this.isContextual(98)))?this.raise(J.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(n==="const"||n==="using"||n==="await using")&&!(this.match(54)||this.isContextual(98))&&this.raise(J.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:n})),i.push(this.finishNode(o,"VariableDeclarator")),!this.eat(8))break}return t}parseVarId(t,r){const n=this.parseBindingAtom();r==="using"||r==="await using"?(n.type==="ArrayPattern"||n.type==="Ob
5643jectPattern")&&this.raise(J.UsingDeclarationHasBindingPattern,n):n.type==="VoidPattern"&&this.raise(J.UnexpectedVoidPattern,n),this.checkLVal(n,{type:"VariableDeclarator"},r==="var"?5:8201),t.id=n}parseAsyncFunctionExpression(t){return this.parseFunction(t,8)}parseFunction(t,r=0){const n=r&2,s=!!(r&1),i=s&&!(r&4),o=!!(r&8);return this.initFunction(t,o),this.match(51)&&(n&&this.raise(J.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),t.generator=!0),s&&(t.id=this.parseFunctionId(i)),this.scope.enter(514),this.prodParam.enter(om(o,t.generator)),s||(t.id=this.parseFunctionId()),this.parseFunctionParams(t,!1),this.parseFunctionBodyAndFinish(t,s?"FunctionDeclaration":"FunctionExpression"),this.prodParam.exit(),this.scope.exit(),s&&!n&&this.registerFunctionStatementId(t),t}parseFunctionId(t){return t||or(this.state.type)?this.parseIdentifier():null}parseFunctionParams(t,r){this.expect(6),this.expressionScope.enter(JY()),t.params=this.parseBindingList(7,41,2|(r?4:0)),this.expressionScope.exit()}registerFunctionStatementId(t){t.id&&this.scope.declareName(t.id.name,!this.options.annexB||this.state.strict||t.generator||t.async?this.scope.treatFunctionsAsVar?5:8201:17,t.id.start)}parseClass(t,r,n){this.next();const s=this.state.strict;return this.state.strict=!0,this.parseClassId(t,r,n),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,s),this.finishNode(t,r?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(25)||this.match(9)||this.match(4)}isClassMethod(){return this.match(6)}nameIsConstructor(t){return t.type==="Identifier"&&t.name==="constructor"||t.type==="StringLiteral"&&t.value==="constructor"}isNonstaticConstructor(t){return!t.computed&&!t.static&&this.nameIsConstructor(t.key)}parseClassBody(t,r){this.classScope.enter();const n={hadConstructor:!1,hadSuperClass:t};let s=[];const i=this.startNode();for(i.body=[],this.expect(2);!this.match(4);){if(this.eat(9)){if(s.length>0)throw this.raise(J.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(22)){s.push(this.parseDecorator());continue}const o=this.startNode();s.length&&(o.decorators=s,this.resetStartLocationFromNode(o,s[0]),s=[]),this.parseClassMember(i,o,n)}if(this.state.strict=r,this.next(),s.length)throw this.raise(J.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(i,"ClassBody")}parseClassMemberFromModifier(t,r){const n=this.parseIdentifier(!0);if(this.isClassMethod()){const s=r;return s.kind="method",s.computed=!1,s.key=n,s.static=!1,this.pushClassMethod(t,s,!1,!1,!1,!1),!0}else if(this.isClassProperty()){const s=r;return s.computed=!1,s.key=n,s.static=!1,t.body.push(this.parseClassProperty(s)),!0}return this.resetPreviousNodeTrailingComments(n),!1}parseClassMember(t,r,n){const s=this.isContextual(102);if(s){if(this.parseClassMemberFromModifier(t,r))return;if(this.eat(2)){this.parseClassStaticBlock(t,r);return}}this.parseClassMemberWithIsStatic(t,r,n,s)}parseClassMemberWithIsStatic(t,r,n,s){const i=r,o=r,l=r,c=r,u=r,d=i,p=i;if(r.static=s,this.parsePropertyNamePrefixOperator(r),this.eat(51)){d.kind="method";const b=this.match(134);if(this.parseClassElementName(d),this.parsePostMemberNameModifiers(d),b){this.pushClassPrivateMethod(t,o,!0,!1);return}this.isNonstaticConstructor(i)&&this.raise(J.ConstructorIsGenerator,i.key),this.pushClassMethod(t,i,!0,!1,!1,!1);return}const h=!this.state.containsEsc&&or(this.state.type),f=this.parseClassElementName(r),x=h?f.name:null,g=this.isPrivateName(f),y=this.state.startLoc;if(this.parsePostMemberNameModifiers(p),this.isClassMethod()){if(d.kind="method",g){this.pushClassPrivateMethod(t,o,!1,!1);return}const b=this.isNonstaticConstructor(i);let v=!1;b&&(i.kind="constructor",i.decorators&&i.decorators.length>0&&this.raise(J.DecoratorConstructor,r),n.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(J.DuplicateConstructor,f),b&&this.hasPlugin("typescript")&&r.override&&this.raise(J.OverrideOnConstructor,f),n.hadConstructor=!0,v=n.hadSuperClass),this.pushClassMethod(t,i,!1,!1,b,v)}else if(this.isClassProperty())g?this.pushClassPrivateProperty(t,c):this.pushClassProperty(t,l);else if(x==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(f);const b=this.eat(51);p.optional&&this.unexpected(y),d.kind="method";const v=this.match(134);this.parseClassElementName(d),this.parsePostMemberNameModifiers(p),v?this.pushClassPrivateMethod(t,o,b,!0):(this.isNonstaticConstructor(i)&&this.raise(J.ConstructorIsAsync,i.key),this.pushClassMethod(t,i,b,!0,!1,!1))}else if((x==="get"||x==="set")&&!(this.match(51)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(f),d.kind=x;const b=this.match(134);this.parseClassElementName(i),b?this.pushClassPrivateMethod(t,o,!1,!1):(this.isNonstaticConstructor(i)&&this.raise(J.ConstructorIsAccessor,i.key),this.pushClassMethod(t,i,!1,!1,
5643!1,!1)),this.checkGetterSetterParams(i)}else if(x==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);const b=this.match(134);this.parseClassElementName(l),this.pushClassAccessorProperty(t,u,b)}else this.isLineTerminator()?g?this.pushClassPrivateProperty(t,c):this.pushClassProperty(t,l):this.unexpected()}parseClassElementName(t){const{type:r,value:n}=this.state;if((r===128||r===130)&&t.static&&n==="prototype"&&this.raise(J.StaticPrototype,this.state.startLoc),r===134){n==="constructor"&&this.raise(J.ConstructorClassPrivateField,this.state.startLoc);const s=this.parsePrivateName();return t.key=s,s}return this.parsePropertyName(t),t.key}parseClassStaticBlock(t,r){var i;this.scope.enter(720);const n=this.state.labels;this.state.labels=[],this.prodParam.enter(0);const s=r.body=[];this.parseBlockOrModuleBlockBody(s,void 0,!1,4),this.prodParam.exit(),this.scope.exit(),this.state.labels=n,t.body.push(this.finishNode(r,"StaticBlock")),(i=r.decorators)!=null&&i.length&&this.raise(J.DecoratorStaticBlock,r)}pushClassProperty(t,r){!r.computed&&this.nameIsConstructor(r.key)&&this.raise(J.ConstructorClassField,r.key),t.body.push(this.parseClassProperty(r))}pushClassPrivateProperty(t,r){const n=this.parseClassPrivateProperty(r);t.body.push(n),this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),0,n.key.start)}pushClassAccessorProperty(t,r,n){!n&&!r.computed&&this.nameIsConstructor(r.key)&&this.raise(J.ConstructorClassField,r.key);const s=this.parseClassAccessorProperty(r);t.body.push(s),n&&this.classScope.declarePrivateName(this.getPrivateNameSV(s.key),0,s.key.start)}pushClassMethod(t,r,n,s,i,o){t.body.push(this.parseMethod(r,n,s,i,o,"ClassMethod",!0))}pushClassPrivateMethod(t,r,n,s){const i=this.parseMethod(r,n,s,!1,!1,"ClassPrivateMethod",!0);t.body.push(i);const o=i.kind==="get"?i.static?6:2:i.kind==="set"?i.static?5:1:0;this.declareClassPrivateMethodInScope(i,o)}declareClassPrivateMethodInScope(t,r){this.classScope.declarePrivateName(this.getPrivateNameSV(t.key),r,t.key.start)}parsePostMemberNameModifiers(t){}parseClassPrivateProperty(t){return this.parseInitializer(t),this.semicolon(),this.finishNode(t,"ClassPrivateProperty")}parseClassProperty(t){return this.parseInitializer(t),this.semicolon(),this.finishNode(t,"ClassProperty")}parseClassAccessorProperty(t){return this.parseInitializer(t),this.semicolon(),this.finishNode(t,"ClassAccessorProperty")}parseInitializer(t){this.scope.enter(592),this.expressionScope.enter(AI()),this.prodParam.enter(0),t.value=this.eat(25)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(t,r,n,s=8331){if(or(this.state.type))t.id=this.parseIdentifier(),r&&this.declareNameFromIdentifier(t.id,s);else if(n||!r)t.id=null;else throw this.raise(J.MissingClassName,this.state.startLoc)}parseClassSuper(t){this.eat(77)?(this.state.canStartArrow=!1,t.superClass=this.parseExprSubscripts()):t.superClass=null}parseExport(t,r){var h;const n=this.parseMaybeImportPhase(t,!0),s=this.maybeParseExportDefaultSpecifier(t,n),i=!s||this.eat(8),o=i&&this.eatExportStar(t),l=o&&this.maybeParseExportNamespaceSpecifier(t),c=i&&(!l||this.eat(8)),u=s||o;if(o&&!l){if(s&&this.unexpected(),r)throw this.raise(J.UnsupportedDecoratorExport,t);return this.parseExportFrom(t,!0),this.sawUnambiguousESM=!0,this.finishNode(t,"ExportAllDeclaration")}const d=this.maybeParseExportNamedSpecifiers(t);s&&i&&!o&&!d&&this.unexpected(null,2),l&&c&&this.unexpected(null,94);let p;if(u||d){if(p=!1,r)throw this.raise(J.UnsupportedDecoratorExport,t);this.parseExportFrom(t,u)}else p=this.maybeParseExportDeclaration(t);if(u||d||p){const f=t;if(this.checkExport(f,!0,!1,!!f.source),((h=f.declaration)==null?void 0:h.type)==="ClassDeclaration")this.maybeTakeDecorators(r,f.declaration,f);else if(r)throw this.raise(J.UnsupportedDecoratorExport,t);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportNamedDeclaration")}if(this.eat(61)){const f=t,x=this.parseExportDefaultExpression();if(f.declaration=x,x.type==="ClassDeclaration")this.maybeTakeDecorators(r,x,f);else if(r)throw this.raise(J.UnsupportedDecoratorExport,t);
5643return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,2)}eatExportStar(t){return this.eat(51)}maybeParseExportDefaultSpecifier(t,r){if(r||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",r==null?void 0:r.start);const n=r||this.parseIdentifier(!0),s=this.startNodeAtNode(n);return s.exported=n,t.specifiers=[this.finishNode(s,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual(89)){t.specifiers??(t.specifiers=[]);const r=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),r.exported=this.parseModuleExportName(),t.specifiers.push(this.finishNode(r,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(t){if(this.match(2)){const r=t;r.specifiers||(r.specifiers=[]);const n=r.exportKind==="type";return r.specifiers.push(...this.parseExportSpecifiers(n)),r.source=null,r.attributes=[],r.declaration=null,!0}return!1}maybeParseExportDeclaration(t){return this.shouldParseExportDeclaration()?(t.specifiers=[],t.source=null,t.attributes=[],t.declaration=this.parseExportDeclaration(t),!0):!1}isAsyncFunction(){if(!this.isContextual(91))return!1;const t=this.nextTokenInLineStart();return this.isUnparsedContextual(t,"function")}parseExportDefaultExpression(){const t=this.startNode();if(this.match(64))return this.next(),this.parseFunction(t,5);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(t,13);if(this.match(76))return this.parseClass(t,!0,!0);if(this.match(22))return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(71)||this.match(70)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(J.UnsupportedDefaultExport,this.state.startLoc);const r=this.parseMaybeAssignAllowIn();return this.semicolon(),r}parseExportDeclaration(t){return this.match(76)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){const{type:t}=this.state;if(or(t)){if(t===91&&!this.state.containsEsc||t===96)return!1;if((t===126||t===125)&&!this.state.containsEsc){const s=this.nextTokenStart(),i=this.input.charCodeAt(s);if(i===123||this.chStartsBindingIdentifier(i,s)&&!this.input.startsWith("from",s))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(61))return!1;const r=this.nextTokenStart(),n=this.isUnparsedContextual(r,"from");if(this.input.charCodeAt(r)===44||or(this.state.type)&&n)return!0;if(this.match(61)&&n){const s=this.input.charCodeAt(this.nextTokenStartSince(r+4));return s===34||s===39}return!1}parseExportFrom(t,r){this.eatContextual(94)?(t.source=this.parseImportSource(),this.checkExport(t),this.maybeParseImportAttributes(t)):r&&this.unexpected(),this.semicolon()}shouldParseExportDeclaration(){const{type:t}=this.state;return t===22&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))?!0:this.isUsing()?(this.raise(J.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(J.UsingDeclarationExport,this.state.startLoc),!0):t===70||t===71||t===64||t===76||this.isLet()||this.isAsyncFunction()}checkExport(t,r,n,s){var i,o;if(r){if(n){if(this.checkDuplicateExports(t,"default"),this.hasPlugin("exportDefaultFrom")){const l=t.declaration;l.type==="Identifier"&&l.name==="from"&&l.end-l.start===4&&!((i=l.extra)!=null&&i.parenthesized)&&this.raise(J.ExportDefaultFromAsIdentifier,l)}}else if((o=t.specifiers)!=null&&o.length)for(const l of t.specifiers){const{exported:c}=l,u=c.type==="Identifier"?c.name:c.value;if(this.checkDuplicateExports(l,u),!s&&l.local){const{local:d}=l;d.type!=="Identifier"?this.raise(J.ExportBindingIsString,l,{localName:d.value,exportName:u}):(this.checkReservedWord(d.name,d.start,!0,!1),this.scope.checkLocalExport(d))}}else if(t.declaration){const l=t.declaration;if(l.type==="FunctionDeclaration"||l.type==="ClassDeclaration"){const{id:c}=l;if(!c)throw new Error("Assertion failure");this.checkDuplicateExports(t,c.name)}else if(l.type==="VariableDeclaration")for(const c of l.declarations)this.checkDeclaration(c.id)}}}checkDeclaration(t){if(t.type==="Identifier")this.checkDuplicateE
5643xports(t,t.name);else if(t.type==="ObjectPattern")for(const r of t.properties)this.checkDeclaration(r);else if(t.type==="ArrayPattern")for(const r of t.elements)r&&this.checkDeclaration(r);else t.type==="ObjectProperty"?this.checkDeclaration(t.value):t.type==="RestElement"?this.checkDeclaration(t.argument):t.type==="AssignmentPattern"&&this.checkDeclaration(t.left)}checkDuplicateExports(t,r){this.exportedIdentifiers.has(r)&&(r==="default"?this.raise(J.DuplicateDefaultExport,t):this.raise(J.DuplicateExport,t,{exportName:r})),this.exportedIdentifiers.add(r)}parseExportSpecifiers(t){const r=[];let n=!0;for(this.expect(2);!this.eat(4);){if(n)n=!1;else if(this.expect(8),this.eat(4))break;const s=this.isContextual(126),i=this.match(130),o=this.startNode();o.local=this.parseModuleExportName(),r.push(this.parseExportSpecifier(o,i,t,s))}return r}parseExportSpecifier(t,r,n,s){return this.eatContextual(89)?t.exported=this.parseModuleExportName():r?t.exported=this.cloneStringLiteral(t.local):t.exported||(t.exported=this.cloneIdentifier(t.local)),this.finishNode(t,"ExportSpecifier")}parseModuleExportName(){if(this.match(130)){const t=this.parseStringLiteral(this.state.value),r=aJ.exec(t.value);return r&&this.raise(J.ModuleExportNameHasLoneSurrogate,t,{surrogateCharCode:r[0].charCodeAt(0)}),t}return this.parseIdentifier(!0)}checkImportPhase(t){const{specifiers:r}=t,n=r.length===1?r[0].type:null;t.phase==="source"?n!=="ImportDefaultSpecifier"&&this.raise(J.SourcePhaseImportRequiresDefault,r[0]):t.phase==="defer"&&n!=="ImportNamespaceSpecifier"&&this.raise(J.DeferImportRequiresNamespace,r[0])}isPotentialImportPhase(t){return t?!1:this.isContextual(101)||this.isContextual(93)}applyImportPhase(t,r,n,s){r||(n==="source"?(this.expectPlugin("sourcePhaseImports",s),t.phase="source"):n==="defer"?(this.expectPlugin("deferredImportEvaluation",s),t.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(t.phase=null))}parseMaybeImportPhase(t,r){if(!this.isPotentialImportPhase(r))return this.applyImportPhase(t,r,null),null;const n=this.startNode(),s=this.parseIdentifierName(!0),{type:i}=this.state;return(ti(i)?i!==94||this.lookaheadCharCode()===102:i!==8)?(this.applyImportPhase(t,r,s,n.start),null):(this.applyImportPhase(t,r,null),this.createIdentifier(n,s))}isPrecedingIdImportPhase(t){const{type:r}=this.state;return or(r)?r!==94||this.lookaheadCharCode()===102:r!==8}parseImport(t){return this.match(130)?this.parseImportSourceAndAttributes(t):this.parseImportSpecifiersAndAfter(t,this.parseMaybeImportPhase(t,!1))}parseImportSpecifiersAndAfter(t,r){t.specifiers=[];const s=!this.maybeParseDefaultImportSpecifier(t,r)||this.eat(8),i=s&&this.maybeParseStarImportSpecifier(t);return s&&!i&&this.parseNamedImportSpecifiers(t),this.expectContextual(94),this.parseImportSourceAndAttributes(t)}parseImportSourceAndAttributes(t){return t.specifiers??(t.specifiers=[]),t.source=this.parseImportSource(),this.maybeParseImportAttributes(t),this.checkImportPhase(t),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.match(130)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(t,r,n){r.local=this.parseIdentifier(),t.specifiers.push(this.finishImportSpecifier(r,n))}finishImportSpecifier(t,r,n=8201){return this.checkLVal(t.local,{type:r},n),this.finishNode(t,r)}parseImportAttributes(){this.expect(2);const t=[],r=new Set;do{if(this.match(4))break;const n=this.startNode(),s=this.state.value;if(r.has(s)&&this.raise(J.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:s}),r.add(s),this.match(130)?n.key=this.parseStringLiteral(s):n.key=this.parseIdentifier(!0),this.expect(10),!this.match(130))throw this.raise(J.ModuleAttributeInvalidValue,this.state.startLoc);n.value=this.parseStringLiteral(this.state.value),t.push(this.finishNode(n,"ImportAttribute"))}while(this.eat(8));return this.expect(4),t}maybeParseImportAttributes(t){let r;if(this.match(72)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),r=this.parseImportAttributes()}else r=[];t.attributes=r}maybeParseDefaultImportSpecifier(t,r){if(r){const n=this.startNodeAtNode(r);return n.local=r,t.specifiers.push(this.finishImportSpecifier(n,"ImportDefaultSpecifier")),!0}else if(ti(this.state.type))return this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier"),!0;return!1}maybeParseStarImportSpecifier(t){if(this.match(51)){const r=this.startNode();return this.next(),this.expectContextual(89),this.parseImportSpecifierLocal(t,r,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(t){let r=!0;for(this.expect(2);!this.eat(4);){if(r)r=!1;else{if(this.eat(10))throw this.raise(J.DestructureNamedImport,this.state.startLoc);if(this.expect(8),this.eat(4))break}const n=this.startNode(),s=this.match(130),i=this.isContextual(126);n.imported=this.parseModuleExportName();const o=this.parseImportSpecifier(n,s,t.importKind==="type"||t.importKind==="typeof",i,void 0);t.specifiers.push(o)}}parseImportSpecifier(t,r,n,s,i){if(this.eatContextual(89))t.local=this.parseIdentifier();else{const{imported:o}=t;if(r)throw this.raise(J.ImportBindingIsString,t,{importName:o.value});this.checkReservedWord(o.name,t.start,!0,!0),t.local||(t.local=this.cloneIdentifier(o))}return this.finishImportSpecifier(t,"ImportSpecifier",i)}isThisParam(t){return t.type==="Identifier"&&t.name==="this"}}const Zy=/in(?:stanceof)?|as|satisfies/y;function oJ(e){if(e==null)throw new Error(`Unexpected ${e} value.`);return e}function b2(e){if(!e)throw new Error("Assert fail")}const lJ={AbstractMethodHasImplementation:({methodName:e})=>`Method '${e}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:e})=>`Property '${e}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",ConstructorHasTypeParameters:"Type parameters cannot appear on a constructor declaration.",DeclareAccessor:({kind:e})=>`'declare' is not allowed in ${e}
5643ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DecoratorAbstractMethod:({kind:e})=>`Decorators can't be used with ${e.startsWith("a")?"an":"a"} ${e}.`,DuplicateAccessibilityModifier:({modifier:e})=>`Accessibility modifier already seen: '${e}'.`,DuplicateModifier:({modifier:e})=>`Duplicate modifier: '${e}'.`,EmptyHeritageClauseType:({token:e})=>`'${e}' list cannot be empty.`,EmptyTypeArguments:"Type argument list cannot be empty.",EmptyTypeParameters:"Type parameter list cannot be empty.",ExpectedAmbientAfterExportDeclare:"'export declare' must be followed by an ambient declaration.",ExportAssignmentInTSNamespace:"An export assignment cannot be used in a namespace.",ExportInTSNamespace:"Export declarations are not permitted in a namespace.",ImportAliasHasImportType:"An import alias can not use 'import type'.",ImportInTSNamespace:"Import declarations in a namespace cannot reference a module.",IncompatibleModifiers:({modifiers:e})=>`'${e[0]}' modifier cannot be used with '${e[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:e})=>`Index signatures cannot have an accessibility modifier ('${e}').`,IndexSignatureHasDeclare:"Index signatures cannot have the 'declare' modifier.",IndexSignatureHasOverride:"'override' modifier cannot appear on an index signature.",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier.",InitializerNotAllowedInAmbientContext:"Initializers are not allowed in ambient contexts.",InlineModuleDeclarationMustUseString:"`module ... {}` declarations must have a string name. Use `namespace ... {}` instead.",InvalidHeritageClauseType:({token:e})=>`'${e}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:e=>`'${e}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:e})=>`'${e}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:e})=>`'${e}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:e})=>`'${e}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:e=>`'${e}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:e})=>`'${e[0]}' modifier must precede '${e[1]}' modifier.`,InvalidPropertyAccessAfterInstantiationExpression:"Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",InvalidTupleMemberLabel:"Tuple members must be labeled with a simple identifier.",MissingInterfaceName:"'interface' declarations must be followed by an identifier.",NamespaceExportInTSNamespace:"Global module exports may only appear at top level.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifier:"'abstract' modifier can only appear on a class, method, or property declaration.",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",OverrideNotInSubClass:"This member cannot have an 'override' modifier because its containing class does not extend another class.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:({modifier:e})=>`Private elements cannot have an accessibility modifier ('${e}').`,ReadonlyForMethodSignature:"'readonly' modifier can only appear on a property declaration or index signature.",ReservedArrowTypeParam:"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:e})=>`Single type parameter ${e} should have a trailing comma. Example usage: <${e},>.`,StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterInitializer:"A parameter initializer is only allowed in a function or constructor implementation.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnexpectedTypeDeclaration:e=>`'${e}' declarations can only be declared inside a block.`,UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:({type:e})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${e}.`,UsingDeclarationInAmbientContext:e=>`'${e}' declarations are not allowed in ambient contexts.`},qe=Za`typescript`(lJ);function cJ(e){switch(e){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}function v2(e){return e==="private"||e==="public"||e==="protected"}function uJ(e){return e==="in"||e==="out"}function C0(e){var t;if((t=e.extra)!=null&&t.parenthesized)return!1;switch(e.type){case"Identifier":return!0;case"MemberExpression":return!e.computed&&C0(e.object);case"TSInstantiationExpression":return C0(e.expression);default:return!1}}const dJ=e=>class extends e{constructor(){super(...arguments);Qe(this,"tsParseInOutModifiers",this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:qe.InvalidModifierOnTypeParameter}));Qe(this,"tsParseConstModifier",this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:qe.InvalidModifierOnTypeParameterPositions}));Qe(this,"tsParseInOutConstModifiers",this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:qe.InvalidModifierOnTypeParameter}))}getScopeHandler(){return LY}tsIsIdentifier(){return or(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(2)||this.match(51)||this.match(17)||this.match(134)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){return this.next(),this.hasPrecedingLineBreak()?!1:this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){return this.match(102)?(this.next(),this.tsTokenCanFollowModifier()):this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(n,s,i){if(!or(this.state.type)&&this.state.type!==54&&this.state.type!==71)return;const o=this.state.value;if(n.includes(o)){if(i&&this.match(102)||s&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return o}}tsParseModifiers({allowedModifiers:n,disallowedModifiers:s,stopOnStartOfClassStaticBlock:i,errorTemplate:o=qe.InvalidModifierOnTypeMember},l){const c=(d,p,h,f)=>{p===h&&l[f]&&this.raise(qe.InvalidModifiersOrder,d,{orderedModifiers:[h,f]})},u=(d,p,h,f)=>{(l[h]&&p===f||l[f]&&p===h)&&this.raise(qe.IncompatibleModifiers,d,{modifiers:[h,f]})};for(;;){const{startLoc:d}=this.state,p=this.tsParseModifier(n.concat(s??[]),i,l.static);if(!p)break;v2(p)?l.accessibility?this.raise(qe.DuplicateAccessibilityModifier,d,{modifier:p}):(c(d,p,p,"override"),c(d,p,p,"static"),c(d,p,p,"readonly"),l.accessibility=p):uJ(p)?(l[p]&&this.raise(qe.DuplicateModifier,d,{modifier:p}),l[p]=!0,c(d,p,"in","out")):(Object.hasOwn(l,p)?this.raise(qe.DuplicateModifier,d,{modifier:p}):(c(d,p,"static","readonly"),c(d,p,"static","override"),c(d,p,"override","readonly"),c(d,p,"abstract","override"),u(d,p,"declare","override"),u(d,p,"static","abstract")),l[p]=!0),s!=null&&s.includes(p)&&this.raise(o,d,{modifier:p})}}tsIsListTerminator(n){switch(n){case"EnumMembers":case"TypeMembers":return this.match(4);case"HeritageClauseElement":return this.match(2);case"TupleElementTypes":return this.match(1);case"TypeParametersOrArguments":return this.match(44)}}tsParseList(n,s){const i=[];for(;!this.tsIsListTerminator(n);)i.push(s());return i}tsParseDelimitedList(n,s,i){return oJ(this.tsParseDelimitedListWorker(n,s,!0,i))}tsParseDelimitedListWorker(n,s,i,o){const l=[];let c=-1;for(;!this.tsIsListTerminator(n);){c=-1;const u=s();if(u==null)return;if(l.push(u),this.eat(8)){c=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(n))break;i&&this.expect(8);return}return o&&(o.value=c),l}tsParseBracketedList(n,s,i,o,l){o||(i?this.expect(0):this.expect(43));const c=this.tsParseDelimitedList(n,s,l);return i?this.expect(1):this.expect(44),c}tsParseImportType(){const n=this.startNode();return this.expect(79),this.expect(6),this.match(130)?n.source=this.parseStringLiteral(this.state.value):(this.raise(qe.UnsupportedImportTypeArgument,this.state.startLoc),n.source=this.tsParseNonConditionalType()),this.eat(8)?n.options=this.tsParseImportTypeOptions():n.options=null,this.expect(7),this.eat(12)&&(n.qualifier=this.tsParseEntityName(3)),this.match(43)&&(n.typeArguments=this.tsParseTypeArguments()),this.finishNode(n,"TSImportType")}tsParseImportTypeOptions(){const n=this.startNode();this.expect(2);const s=this.startNode();return this.isContextual(72)?(s.method=!1,s.key=this.parseIdentifier(!0),s.computed=!1,s.shorthand=!1):this.unexpected(null,72),this.expect(10),s.value=this.tsParseImportTypeWithPropertyValue(),n.properties=[this.finishObjectProperty(s)],this.eat(8),this.expect(4),this.finishNode(n,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){const n=this.startNode(),s=[];for(this.expect(2);!this.match(4);){const i=this.state.type;or(i)||i===130?s.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(8)}return n.properties=s,this.next(),this.finishNode(n,"ObjectExpression")}tsParseEntityName(n){let s;if(n&1&&this.match(74))if(n&2)s=this.parseIdentifier(!0);else{const i=this.startNode();this.next(),s=this.finishNode(i,"ThisExpression")}
5643else s=this.parseIdentifier(!!(n&1));for(;this.eat(12);){const i=this.startNodeAtNode(s);i.left=s,i.right=this.parseIdentifier(!!(n&1)),s=this.finishNode(i,"TSQualifiedName")}return s}tsParseTypeReference(){const n=this.startNode();return n.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(43)&&(n.typeArguments=this.tsParseTypeArguments()),this.finishNode(n,"TSTypeReference")}tsParseThisTypePredicate(n){this.next();const s=this.startNodeAtNode(n);return s.parameterName=n,s.typeAnnotation=this.tsParseTypeAnnotation(!1),s.asserts=!1,this.finishNode(s,"TSTypePredicate")}tsParseThisTypeNode(){const n=this.startNode();return this.next(),this.finishNode(n,"TSThisType")}tsParseTypeQuery(){const n=this.startNode();return this.expect(83),this.match(79)?n.exprName=this.tsParseImportType():n.exprName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(43)&&(n.typeArguments=this.tsParseTypeArguments()),this.finishNode(n,"TSTypeQuery")}tsParseTypeParameter(n){const s=this.startNode();return n(s),s.name=this.tsParseTypeParameterName(),s.constraint=this.tsEatThenParseType(77),s.default=this.tsEatThenParseType(25),this.finishNode(s,"TSTypeParameter")}tsTryParseTypeParameters(n){if(this.match(43))return this.tsParseTypeParameters(n)}tsParseTypeParameters(n){const s=this.startNode();this.match(43)||this.match(138)?this.next():this.unexpected();const i={value:-1};return s.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,n),!1,!0,i),s.params.length===0&&this.raise(qe.EmptyTypeParameters,s),i.value!==-1&&this.addExtra(s,"trailingComma",i.value),this.finishNode(s,"TSTypeParameterDeclaration")}tsFillSignature(n,s){const i=n===15,o="params",l="returnType";s.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(6),s[o]=this.tsParseBindingListForSignature(),i?s[l]=this.tsParseTypeOrTypePredicateAnnotation(n):this.match(n)&&(s[l]=this.tsParseTypeOrTypePredicateAnnotation(n))}tsParseBindingListForSignature(){const n=super.parseBindingList(7,41,2);for(const s of n){const{type:i}=s;(i==="AssignmentPattern"||i==="TSParameterProperty")&&this.raise(qe.UnsupportedSignatureParameterKind,s,{type:i})}return n}tsParseTypeMemberSemicolon(){!this.eat(8)&&!this.isLineTerminator()&&this.expect(9)}tsParseSignatureMember(n,s){return this.tsFillSignature(10,s),this.tsParseTypeMemberSemicolon(),this.finishNode(s,n)}tsIsUnambiguouslyIndexSignature(){return this.next(),or(this.state.type)?(this.next(),this.match(10)):!1}tsTryParseIndexSignature(n){if(!(this.match(0)&&this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))))return;this.expect(0);const s=this.parseIdentifier();s.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(s),this.expect(1),n.parameters=[s];const i=this.tsTryParseTypeAnnotation();return i&&(n.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(n,"TSIndexSignature")}tsParsePropertyOrMethodSignature(n,s){if(this.eat(13)&&(n.optional=!0),this.match(6)||this.match(43)){s&&this.raise(qe.ReadonlyForMethodSignature,n);const i=n;if(i.kind&&this.match(43)&&this.raise(qe.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(10,i),this.tsParseTypeMemberSemicolon(),i.kind==="get")i.params.length>0&&(this.raise(J.BadGetterArity,this.state.curPosition()),this.isThisParam(i.params[0])&&this.raise(qe.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(i.kind==="set"){if(i.params.length!==1)this.raise(J.BadSetterArity,this.state.curPosition());else{const o=i.params[0];this.isThisParam(o)&&this.raise(qe.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(qe.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(qe.SetAccessorCannotHaveRestParameter,this.state.curPosition())}i.returnType&&this.raise(qe.SetAccessorCannotHaveReturnType,i.returnType)}else i.kind="method";return this.finishNode(i,"TSMethodSignature")}else{const i=n;s&&(i.readonly=!0);const o=this.tsTryParseTypeAnnotation();return o&&(i.typeAnnotation=o),this.tsParseTypeMemberSemicolon(),this.finishNode(i,"TSPro
5643pertySignature")}}tsParseTypeMember(){const n=this.startNode();if(this.match(6)||this.match(43))return this.tsParseSignatureMember("TSCallSignatureDeclaration",n);if(this.match(73)){const i=this.startNode();return this.next(),this.match(6)||this.match(43)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",n):(n.key=this.createIdentifier(i,"new"),this.tsParsePropertyOrMethodSignature(n,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},n);const s=this.tsTryParseIndexSignature(n);return s||(super.parsePropertyName(n),!n.computed&&n.key.type==="Identifier"&&(n.key.name==="get"||n.key.name==="set")&&this.tsTokenCanFollowModifier()&&(n.kind=n.key.name,super.parsePropertyName(n),!this.match(6)&&!this.match(43)&&this.unexpected(null,6)),this.tsParsePropertyOrMethodSignature(n,!!n.readonly))}tsParseTypeLiteral(){const n=this.startNode();return n.members=this.tsParseObjectTypeMembers(),this.finishNode(n,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(2);const n=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(4),n}tsIsStartOfMappedType(){return this.next(),this.eat(49)?this.isContextual(118):(this.isContextual(118)&&this.next(),!this.match(0)||(this.next(),!this.tsIsIdentifier())?!1:(this.next(),this.match(54)))}tsParseMappedType(){const n=this.startNode();return this.expect(2),this.match(49)?(n.readonly=this.state.value,this.next(),this.expectContextual(118)):this.eatContextual(118)&&(n.readonly=!0),this.expect(0),n.key=this.tsParseTypeParameterName(),n.constraint=this.tsExpectThenParseType(54),n.nameType=this.eatContextual(89)?this.tsParseType():null,this.expect(1),this.match(49)?(n.optional=this.state.value,this.next(),this.expect(13)):this.eat(13)&&(n.optional=!0),n.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(4),this.finishNode(n,"TSMappedType")}tsParseTupleType(){const n=this.startNode();n.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let s=!1;return n.elementTypes.forEach(i=>{const{type:o}=i;s&&o!=="TSRestType"&&o!=="TSOptionalType"&&!(o==="TSNamedTupleMember"&&i.optional)&&this.raise(qe.OptionalTypeBeforeRequired,i),s||(s=o==="TSNamedTupleMember"&&i.optional||o==="TSOptionalType")}),this.finishNode(n,"TSTupleType")}tsParseTupleElementType(){const n=this.state.startLoc,s=this.eat(17),{startLoc:i}=this.state;let o,l,c,u;const p=ti(this.state.type)?this.lookaheadCharCode():null;if(p===58)o=!0,c=!1,l=this.parseIdentifier(!0),this.expect(10),u=this.tsParseType();else if(p===63){c=!0;const h=this.state.value,f=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(o=!0,l=this.createIdentifier(this.startNodeAt(i),h),this.expect(13),this.expect(10),u=this.tsParseType()):(o=!1,u=f,this.expect(13))}else u=this.tsParseType(),c=this.eat(13),o=this.eat(10);if(o){let h;l?(h=this.startNodeAt(i),h.optional=c,h.label=l,h.elementType=u,this.eat(13)&&(h.optional=!0,this.raise(qe.TupleOptionalAfterType,this.state.lastTokStartLoc))):(h=this.startNodeAt(i),h.optional=c,this.raise(qe.InvalidTupleMemberLabel,u),h.label=u,h.elementType=this.tsParseType()),u=this.finishNode(h,"TSNamedTupleMember")}else if(c){const h=this.startNodeAt(i);h.typeAnnotation=u,u=this.finishNode(h,"TSOptionalType")}if(s){const h=this.startNodeAt(n);h.typeAnnotation=u,u=this.finishNode(h,"TSRestType")}return u}tsParseParenthesizedType(){const n=this.startNode();return this.expect(6),n.typeAnnotation=this.tsParseType(),this.expect(7),this.finishNode(n,"TSParenthesizedType")}tsParseFunctionOrConstructorType(n,s){const i=this.startNode();return n==="TSConstructorType"&&(i.abstract=!!s,s&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(15,i)),this.finishNode(i,n)}tsParseLiteralTypeNode(){const n=this.startNode();switch(this.state.type){case 131:case 132:case 130:case 81:case 82:n.literal=super.parseExprAtom();break;default:this.unexpected()}return this.finishNode(n,"TSLiteralType")}tsParseTemplateLiteralType(){const n=this.state.startLoc;let s=this.parseTemplateElement(!1);const i=[s];if(s.tail){const o=this.startNodeAt(n),l=this.startNodeAt(n);return l.expressions=[],l.quasis=i,o.literal=this.finishNode(l,"TemplateLiteral"),this.finishNode(o,"TSLiteralType")}else{const o=[];for(;!s.tail;)o.push(this.tsParseType()),this.readTemplateContinuation(),i.push(s=this.parseTemplateElement(!1));const l=this.startNodeAt(n);return l.types=o,l.quasis=i,this.finishNode(l,"TSTemplateLiteralType")}}parseTemplateSubstitution(){return this.state.inType?this.tsParseType():super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){const n=this.tsParseThisTypeNode();return this.isContextual(112)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(n):n}tsParseNonArrayType(){switch(this.state.type){case 130:case 131:case 132:case 81:case 82:return this.tsParseLiteralTypeNode();case 49:if(this.state.value==="-"){const n=this.startNode(),s=this.lookahead();return s.type!==131&&s.type!==132&&this.unexpected(),n.literal=this.parseMaybeUnary(),this.finishNode(n,"TSLiteralType")}break;case 74:return this.tsParseThisTypeOrThisTypePredicate();case 83:return this.tsParseTypeQuery();case 79:return this.tsParseImportType();case 2:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 6:if(!(this.optionFlags&2048)){const n=this.state.startLoc;this.next();const s=this.tsParseType();return this.expect(7),this.addExtra(s,"parenthesized",!0),this.addExtra(s,"parenStart",n.index),s}return this.tsParseParenthesizedType();case 21:case 20:return this.tsParseTemplateLiteralType();default:{const{type:n}=this.state;if(or(n)||n===84||n===80){const s=n===84?"TSVoidKeyword":n===80?"TSNullKeyword":cJ(this.state.value);if(s!==void 0&&this.lookaheadCharCode()!==46){const i=this.startNode();return this.next(),this.finishNode(i,s)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){const{startLoc:n}=this.state;let s=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(1)){const i=this.startNodeAt(n);i.elementType=s,this.expect(1),s=this.finishNode(i,"TSArrayType")}else{const i=this.startNodeAt(n);i.objectType=s,i.indexType=this.tsParseType(),this.expect(1),s=this.finishNode(i,"TS
5643IndexedAccessType")}return s}tsParseTypeOperator(){const n=this.startNode(),s=this.state.value;return this.next(),n.operator=s,n.typeAnnotation=this.tsParseTypeOperatorOrHigher(),s==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(n),this.finishNode(n,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(n){switch(n.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(qe.UnexpectedReadonly,n)}}tsParseInferType(){const n=this.startNode();this.expectContextual(111);const s=this.startNode();return s.name=this.tsParseTypeParameterName(),s.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),n.typeParameter=this.finishNode(s,"TSTypeParameter"),this.finishNode(n,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(77)){const n=this.tsInDisallowConditionalTypesContext(()=>this.tsParseType());if(this.state.inDisallowConditionalTypesContext||!this.match(13))return n}}tsParseTypeOperatorOrHigher(){return lY(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(111)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(n,s,i){const o=this.startNode(),l=this.eat(i),c=[];do c.push(s());while(this.eat(i));return c.length===1&&!l?c[0]:(o.types=c,this.finishNode(o,n))}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),41)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),39)}tsIsStartOfFunctionType(){return this.match(43)?!0:this.match(6)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(or(this.state.type)||this.match(74))return this.next(),!0;if(this.match(2)){const{errors:n}=this.state,s=n.length;try{return this.parseObjectLike(4,!0),n.length===s}catch{return!1}}if(this.match(0)){this.next();const{errors:n}=this.state,s=n.length;try{return super.parseBindingList(1,93,1),n.length===s}catch{return!1}}return!1}tsIsUnambiguouslyStartOfFunctionType(){return this.next(),!!(this.match(7)||this.match(17)||this.tsSkipParameterStart()&&(this.match(10)||this.match(8)||this.match(13)||this.match(25)||this.match(7)&&(this.next(),this.match(15))))}tsParseTypeOrTypePredicateAnnotation(n){return this.tsInType(()=>{const s=this.startNode();this.expect(n);const i=this.startNode(),o=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(o&&this.match(74)){let u=this.tsParseThisTypeOrThisTypePredicate();return u.type==="TSThisType"?(i.parameterName=u,i.asserts=!0,i.typeAnnotation=null,u=this.finishNode(i,"TSTypePredicate")):(this.resetStartLocationFromNode(u,i),u.asserts=!0),s.typeAnnotation=u,this.finishNode(s,"TSTypeAnnotation")}const l=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!l)return o?(i.parameterName=this.parseIdentifier(),i.asserts=o,i.typeAnnotation=null,s.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(s,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,s);const c=this.tsParseTypeAnnotation(!1);return i.parameterName=l,i.typeAnnotation=c,i.asserts=o,s.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(s,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){if(this.match(10))return this.tsParseTypeOrTypePredicateAnnotation(10)}tsTryParseTypeAnnotation(){if(this.match(10))return this.tsParseTypeAnnotation()}tsTryParseType(){return this.tsEatThenParseType(10)}tsParseTypePredicatePrefix(){const n=this.parseIdentifier();if(this.isContextual(112)&&!this.hasPrecedingLineBreak())return this.next(),n}tsParseTypePredicateAsserts(){if(this.state.type!==105)return!1;const n=this.state.containsEsc;return this.next(),!or(this.state.type)&&!this.match(74)?!1:(n&&this.raise(J.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(n=!0,s=this.startNode()){return this.tsInType(()=>{n&&this.expect(10),s.typeAnnotation=this.tsParseType()}),this.finishNode(s,"TSTypeAnnotation")}tsParseType(){b2(this.state.inType);const n=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(77))return n;const s=this.startNodeAtNode(n);return s.checkType=n,s.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(13),s.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(10),s.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(s,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(120)&&this.isLookaheadContextual("new")}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(73)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(qe.ReservedTypeAssertion,this.state.startLoc);const n=this.startNode();return n.typeAnnotation=this.tsInType(()=>(this.next(),this.match(71)?this.tsParseTypeReference():this.tsParseType())),this.expect(44),n.expression=this.parseMaybeUnary(),this.finishNode(n,"TSTypeAssertion")}tsParseHeritageClause(n){const s=this.state.startLoc,i=this.tsParseDelimitedList("HeritageClauseElement",()=>{const o=(this.state.canStartArrow=!1,super.parseExprSubscripts());C0(o)||this.raise(qe.InvalidHeritageClauseType,o.start,{token:n});const l=n==="extends"?"TSInterfaceHeritage":"TSClassImplements";if(o.type==="TSInstantiationExpression")return o.type=l,o;const c=this.startNodeAtNode(o);return c.expression=o,(this.match(43)||this.match(47))&&(c.typeArguments=this.tsParseTypeArgumentsInExpression()),this.finishNode(c,l)});return i.length||this.raise(qe.EmptyHeritageClauseType,s,{token:n}),i}tsParseInterfaceDeclaration(n,s={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(125),s.declare&&(n.declare=!0),or(this.state.type)?(n.id=this.parseIdentifier(),this.checkIdentifier(n.id,130)):(n.id=null,this.raise(qe.MissingInterfaceName,this.state.startLoc)),n.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(77)&&(n.extends=this.tsParseHeritageClause("extends"));const i=this.startNode();return i.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),n.body=this.finishNode(i,"TS
5643InterfaceBody"),this.finishNode(n,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(n){return n.id=this.parseIdentifier(),this.checkIdentifier(n.id,2),n.typeAnnotation=this.tsInType(()=>{if(n.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutModifiers),this.expect(25),this.isContextual(110)&&this.lookaheadCharCode()!==46){const s=this.startNode();return this.next(),this.finishNode(s,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(n,"TSTypeAliasDeclaration")}tsInTopLevelContext(n){if(this.curContext()!==Nr.brace){const s=this.state.context;this.state.context=[s[0]];try{return n()}finally{this.state.context=s}}else return n()}tsInType(n){const s=this.state.inType;this.state.inType=!0;try{return n()}finally{this.state.inType=s}}tsInDisallowConditionalTypesContext(n){const s=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return n()}finally{this.state.inDisallowConditionalTypesContext=s}}tsInAllowConditionalTypesContext(n){const s=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return n()}finally{this.state.inDisallowConditionalTypesContext=s}}tsEatThenParseType(n){if(this.match(n))return this.tsNextThenParseType()}tsExpectThenParseType(n){return this.tsInType(()=>(this.expect(n),this.tsParseType()))}tsNextThenParseType(){return this.tsInType(()=>(this.next(),this.tsParseType()))}tsParseEnumMember(){const n=this.startNode();return n.id=this.match(130)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(25)&&(n.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(n,"TSEnumMember")}tsParseEnumDeclaration(n,s={}){return s.const&&(n.const=!0),s.declare&&(n.declare=!0),this.expectContextual(122),n.id=this.parseIdentifier(),this.checkIdentifier(n.id,n.const?8971:8459),n.body=this.tsParseEnumBody(),this.finishNode(n,"TSEnumDeclaration")}tsParseEnumBody(){const n=this.startNode();return this.expect(2),n.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(4),this.finishNode(n,"TSEnumBody")}tsParseModuleBlock(n){const s=this.startNode();return n||this.scope.enter(0),this.expect(2),super.parseBlockOrModuleBlockBody(s.body=[],void 0,!0,4),n||this.scope.exit(),this.finishNode(s,"TSModuleBlock")}tsParseNamespaceDeclaration(n){return n.id=this.tsParseEntityName(0),n.id.type==="Identifier"&&this.checkIdentifier(n.id,1024),this.scope.enter(2048),this.prodParam.enter(0),n.body=this.tsParseModuleBlock(!1),this.prodParam.exit(),this.scope.exit(),this.finishNode(n,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(n){const s=this.isContextual(108);return s?(n.kind="global",n.id=this.parseIdentifier()):(n.kind="module",n.id=super.parseStringLiteral(this.state.value)),this.match(2)?(s||this.scope.enter(1024),this.prodParam.enter(0),n.body=this.tsParseModuleBlock(s),this.prodParam.exit(),s||this.scope.exit()):this.semicolon(),this.finishNode(n,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(n,s){n.id=s||this.parseIdentifier(),this.checkIdentifier(n.id,4096),this.expect(25);const i=this.tsParseModuleReference();return n.importKind==="type"&&i.type!=="TSExternalModuleReference"&&this.raise(qe.ImportAliasHasImportType,i),n.moduleReference=i,this.semicolon(),this.finishNode(n,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(115)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){const n=this.startNode();return this.expectContextual(115),this.expect(6),this.match(130)||this.unexpected(),n.expression=super.parseExprAtom(),this.expect(7),this.sawUnambiguousESM=!0,this.finishNode(n,"TSExternalModuleReference")}tsLookAhead(n){const s=this.state.clone(),i=n();return this.state=s,i}tsTryParseAndCatch(n){const s=this.tryParse(i=>n()||i());if(!(s.aborted||!s.node))return s.error&&(this.state=s.failState),s.node}tsTryParse(n){const s=this.state.clone(),i=n();if(i!==void 0&&i!==!1)return i;this.state=s}tsTryParseDeclare(n){if(this.isLineTerminator())return;const s=this.state.type;return this.tsInAmbientContext(()=>{switch(s){case 64:return n.declare=!0,super.parseFunctionStatement
5643(n,!1,!1);case 76:return n.declare=!0,this.parseClass(n,!0,!1);case 122:return this.tsParseEnumDeclaration(n,{declare:!0});case 108:return this.tsParseAmbientExternalModuleDeclaration(n);case 96:if(this.state.containsEsc)return;case 71:case 70:return!this.match(71)||!this.isLookaheadContextual("enum")?(n.declare=!0,this.parseVarStatement(n,this.state.value,!0)):(this.expect(71),this.tsParseEnumDeclaration(n,{const:!0,declare:!0}));case 103:if(this.isUsing())return this.raise(qe.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),n.declare=!0,this.parseVarStatement(n,"using",!0);break;case 92:if(this.isAwaitUsing())return this.raise(qe.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),n.declare=!0,this.next(),this.parseVarStatement(n,"await using",!0);break;case 125:{const i=this.tsParseInterfaceDeclaration(n,{declare:!0});if(i)return i}default:if(or(s))return this.tsParseDeclaration(n,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(n,s,i,o){switch(s){case 120:if(this.tsCheckLineTerminator(i)&&(this.match(76)||or(this.state.type)))return this.tsParseAbstractDeclaration(n,o);break;case 123:if(this.tsCheckLineTerminator(i))return this.tsParseAmbientExternalModuleDeclaration(n);break;case 124:if(this.tsCheckLineTerminator(i)&&or(this.state.type))return n.kind="namespace",this.tsParseNamespaceDeclaration(n);break;case 126:if(this.tsCheckLineTerminator(i)&&or(this.state.type))return this.tsParseTypeAliasDeclaration(n);break}}tsCheckLineTerminator(n){return n?this.hasFollowingLineBreak()?!1:(this.next(),!0):!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(n){if(!this.match(43))return;const s=this.tsTryParseAndCatch(()=>{const i=this.startNodeAt(n);return i.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(i),i.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(15),i});if(s)return super.parseArrowExpression(s,null,!0)}tsParseTypeArgumentsInExpression(){if(this.reScan_lt()===43)return this.tsParseTypeArguments()}tsParseTypeArguments(){const n=this.startNode();return n.params=this.tsInType(()=>this.tsInTopLevelContext(()=>(this.expect(43),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),n.params.length===0?this.raise(qe.EmptyTypeArguments,n):!this.state.inType&&this.curContext()===Nr.brace&&this.reScan_lt_gt(),this.expect(44),this.finishNode(n,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return cY(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(n,s){const i=s.length?null:this.state.startLoc,o={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},o);const l=o.accessibility,c=o.override,u=o.readonly;!(n&4)&&(l||u||c)&&this.raise(qe.UnexpectedParameterModifier,i||s[0]);const d=this.state.startLoc,p=this.parseMaybeDefault(d);n&2&&this.parseFunctionParamType(p);const h=this.parseMaybeDefault(d,p);if(l||u||c){const f=i?this.startNodeAt(i):this.startNodeAtNode(s[0]);return s.length?f.decorators=s:this.setLoc(i),l&&(f.accessibility=l),u&&(f.readonly=u),c&&(f.override=c),h.type!=="Identifier"&&h.type!=="AssignmentPattern"&&this.raise(qe.UnsupportedParameterPropertyKind,i||s[0]),f.parameter=h,this.finishNode(f,"TSParameterProperty")}return s.length&&(p.decorators=s),h}isSimpleParameter(n){return n.type==="TSParameterProperty"&&super.isSimpleParameter(n.parameter)||super.isSimpleParameter(n)}tsDisallowOptionalPattern(n){for(const s of n.params)s.type!=="Identifier"&&s.optional&&!this.state.isAmbientContext&&this.raise(qe.PatternIsOptional,s)}setArrowFunctionParameters(n,s,i){super.setArrowFunctionParameters(n,s,i),this.tsDisallowOptionalPattern(n)}parseFunctionBodyAndFinish(n,s,i=!1){this.match(10)&&(n.returnType=this.tsParseTypeOrTypePredicateAnnotation(10));const o=s==="FunctionDeclaration"?"TSDeclareFunction":s==="ClassMethod"||s==="ClassPrivateMethod"?"TSDeclareMethod":void 0;if(o&&!this.match(2)&&this.isLineTerminator()){if(o==="TSDeclareMethod"&&n.kind==="constructor")for(const l of n.params)l.type==="TSParameterProperty"?this.raise(qe.UnexpectedParameterModifier,l):l.type==="AssignmentPattern"&&this.raise(qe.UnexpectedParameterInitializer,l);else for(const l of n.params)l.type==="AssignmentPattern"&&this.raise(qe.UnexpectedParameterInitializer,l);return this.finishNode(n,o)}return o&&this.state.isAmbientContext&&(this.raise(qe.DeclareFunctionHasImplementation,this.state.startLoc),o==="TSDeclareFunction"&&n.declare)?super.parseFunctionBodyAndFinish(n,o,i):(this.tsDisallowOptionalPattern(n),super.parseFunctionBodyAndFinish(n,s,i))}registerFunctionStatementId(n){!n.body&&n.id?this.checkIdentifier(n.id,1024):super.registerFunctionStatementId(n)}
5643tsCheckForInvalidTypeCasts(n){n.forEach(s=>{(s==null?void 0:s.type)==="TSTypeCastExpression"&&this.raise(qe.UnexpectedTypeAnnotation,s.typeAnnotation)})}toReferencedList(n,s){return this.tsCheckForInvalidTypeCasts(n),n}parseArrayLike(n,s){const i=super.parseArrayLike(n,s);return i.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(i.elements),i}parseSubscript(n,s,i,o){if(!this.hasPrecedingLineBreak()&&this.match(31)){this.state.canStartJSXElement=!1,this.next();const c=this.startNodeAt(s);return c.expression=n,this.finishNode(c,"TSNonNullExpression")}let l=!1;if(this.match(14)&&this.lookaheadCharCode()===60){if(i)return o.stop=!0,n;o.optionalChainMember=l=!0,this.next()}if(this.match(43)||this.match(47)){let c;const u=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(n)){const f=this.tsTryParseGenericAsyncArrowFunction(s);if(f)return o.stop=!0,f}const d=this.tsParseTypeArgumentsInExpression();if(!d)return;if(l&&!this.match(6)){c=this.state.curPosition();return}if(j0(this.state.type)){const f=super.parseTaggedTemplateExpression(n,s,o);return f.typeArguments=d,f}if(!i&&this.eat(6)){const f=this.startNodeAt(s);return f.callee=n,f.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(f.arguments),f.typeArguments=d,o.optionalChainMember&&(f.optional=l),this.finishCallExpression(f,o.optionalChainMember)}const p=this.state.type;if(p===44||p===48||p!==6&&p!==89&&p!==116&&rp(p)&&!this.hasPrecedingLineBreak())return;const h=this.startNodeAt(s);return h.expression=n,h.typeArguments=d,this.finishNode(h,"TSInstantiationExpression")});if(c&&this.unexpected(c,6),u)return u.type==="TSInstantiationExpression"&&((this.match(12)||this.match(14)&&this.lookaheadCharCode()!==40)&&this.raise(qe.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(12)&&!this.match(14)&&(u.expression=super.stopParseSubscript(n,o))),u}return super.parseSubscript(n,s,i,o)}parseNewCallee(n){var i;super.parseNewCallee(n);const{callee:s}=n;s.type==="TSInstantiationExpression"&&!((i=s.extra)!=null&&i.parenthesized)&&(n.typeArguments=s.typeArguments,n.callee=s.expression)}parseExprOp(n,s,i){let o;if(im(54)>i&&!this.hasPrecedingLineBreak()&&(this.isContextual(89)||(o=this.isContextual(116)))){const l=this.startNodeAt(s);l.expression=n,l.typeAnnotation=this.tsInType(()=>(this.next(),this.match(71)?(o&&this.raise(J.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType()));const c=this.finishNode(l,o?"TSSatisfiesExpression":"TSAsExpression");return this.reScan_lt_gt(),this.parseExprOp(c,s,i)}return super.parseExprOp(n,s,i)}checkReservedWord(n,s,i,o){this.state.isAmbientContext||super.checkReservedWord(n,s,i,o)}checkDuplicateExports(){}isPotentialImportPhase(n){if(super.isPotentialImportPhase(n))return!0;if(this.isContextual(126)){const s=this.lookaheadCharCode();return n?s===123||s===42:s!==61}return!n&&this.isContextual(83)}applyImportPhase(n,s,i,o){super.applyImportPhase(n,s,i,o),s?n.exportKind=i==="type"?"type":"value":n.importKind=i==="type"||i==="typeof"?i:"value"}parseImport(n){if(this.match(130))return n.importKind="value",this.scope.inTSNamespace&&this.raise(qe.ImportInTSNamespace,n),super.parseImport(n);let s;if(or(this.state.type)&&this.lookaheadCharCode()===61){n.importKind="value";const i=this.tsParseImportEqualsDeclaration(n);return this.scope.inTSNamespace&&i.moduleReference.type==="TSExternalModuleReference"&&this.raise(qe.ImportInTSNamespace,n),i}else if(this.isContextual(126)){const i=this.parseMaybeImportPhase(n,!1);if(this.lookaheadCharCode()===61)return this.scope.inTSNamespace&&this.raise(qe.ImportInTSNamespace,n),this.tsParseImportEqualsDeclaration(n,i);s=super.parseImportSpecifiersAndAfter(n,i)}else s=super.parseImport(n);return s.importKind==="type"&&s.specifiers.length>1&&s.specifiers[0].type==="ImportDefaultSpecifier"?this.raise(qe.TypeImportCannotSpecifyDefaultAndNamed,s):this.scope.inTSNamespace&&this.raise(qe.ImportInTSNamespace,s),s}parseExport(n,s){if(this.match(79)){const i=this.startNode();this.next();let o=null;this.isContextual(126)&&this.isPotentialImportPhase(!1)?o=this.parseMaybeImportPhase(i,!1):i.importKind="value";const l=this.tsParseImportEqualsDeclaration(i,o);
5643return n.attributes=[],n.declaration=l,n.exportKind="value",n.source=null,n.specifiers=[],this.finishNode(n,"ExportNamedDeclaration")}else if(this.eat(25)){const i=n;return i.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.scope.inTSNamespace&&this.raise(qe.ExportAssignmentInTSNamespace,i),this.finishNode(i,"TSExportAssignment")}else if(this.eatContextual(89)){const i=n;return this.expectContextual(124),i.id=this.parseIdentifier(),this.checkIdentifier(i.id,8201),this.semicolon(),this.scope.inTSNamespace&&this.raise(qe.NamespaceExportInTSNamespace,i),this.finishNode(i,"TSNamespaceExportDeclaration")}else{const i=super.parseExport(n,s);return this.scope.inTSNamespace&&(i.type!=="ExportNamedDeclaration"||i.source||!i.declaration&&!this.state.isAmbientContext)&&this.raise(qe.ExportInTSNamespace,i),i}}isAbstractClass(){return this.isContextual(120)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){const n=this.startNode();return this.next(),n.abstract=!0,this.parseClass(n,!0,!0)}if(this.match(125)){const n=this.tsParseInterfaceDeclaration(this.startNode());if(n)return n}return super.parseExportDefaultExpression()}parseVarStatement(n,s,i=!1){const{isAmbientContext:o}=this.state,l=super.parseVarStatement(n,s,i||o);if(!o)return l;if(!n.declare&&(s==="using"||s==="await using"))return this.raiseOverwrite(qe.UsingDeclarationInAmbientContext,n,s),l;for(const{id:c,init:u}of l.declarations)u&&(s==="var"||s==="let"||c.typeAnnotation?this.raise(qe.InitializerNotAllowedInAmbientContext,u):hJ(u,this.hasPlugin("estree"))||this.raise(qe.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,u));return l}parseStatementContent(n,s){const i=!!(n&2);if(!this.state.containsEsc)switch(this.state.type){case 71:{if(this.isLookaheadContextual("enum")){const o=this.startNode();return this.next(),this.tsParseEnumDeclaration(o,{const:!0})}break}case 120:case 121:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){const o=this.state.type,l=this.startNode();this.next();const c=o===121?this.tsTryParseDeclare(l):this.tsParseAbstractDeclaration(l,s);return c?(o===121&&(c.declare=!0),c):(l.expression=this.createIdentifier(this.startNodeAtNode(l),o===121?"declare":"abstract"),this.semicolon(!1),this.finishNode(l,"ExpressionStatement"))}break}case 122:return this.tsParseEnumDeclaration(this.startNode());case 108:{if(this.lookaheadCharCode()===123){const l=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(l)}break}case 125:{const o=this.tsParseInterfaceDeclaration(this.startNode());if(o)return i||this.raise(qe.UnexpectedTypeDeclaration,o,"interface"),o;break}case 123:{if(this.nextTokenIsStringLiteralOnSameLine()){const o=this.startNode();return this.next(),this.tsParseDeclaration(o,123,!1,s)}else if(this.nextTokenIsIdentifierOnSameLine()){this.raise(qe.InlineModuleDeclarationMustUseString,this.state.startLoc);const o=this.startNode();return this.next(),this.tsParseDeclaration(o,124,!1,s)}break}case 124:{if(this.nextTokenIsIdentifierOnSameLine()){const o=this.startNode();return this.next(),this.tsParseDeclaration(o,124,!1,s)}break}case 126:{if(this.nextTokenIsIdentifierOnSameLine()){const o=this.startNode();return i||this.raise(qe.UnexpectedTypeDeclaration,o,"type"),this.next(),this.tsParseTypeAliasDeclaration(o)}break}}return super.parseStatementContent(n,s)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(n,s){return s.some(i=>v2(i)?n.accessibility===i:!!n[i])}tsIsStartOfStaticBlocks(){return this.isContextual(102)&&this.lookaheadCharCode()===123}parseClassMember(n,s,i){const o=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:o,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:qe.InvalidModifierOnTypeParameterPositions},s);const l=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(s,o)&&this.raise(qe.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(n,s)):this.parseClassMemberWithIsStatic(n,s,i,!!s.static)};s.declare?this.tsInAmbientContext(l):l(),s.decorators&&s.decorators.length>0&&!this.hasPlugin("decorators-legacy")&&(s.type==="TSAbstractMethodDefinition"||s.type==="TSDeclareMethod"?this.raise(qe.DecoratorAbstractMethod,s,{kind:"abstract method"}):(s.type==="ClassProperty"&&s.abstract||s.type==="ClassProperty"&&s.declare||s.type==="TSAbstractPropertyDefinition"||s.type==="PropertyDefinition"&&s.declare)&&this.raise(qe.DecoratorAbstractMethod,s,{kind:s.declare?"declare field":"abstract field"}))}parseClassMemberWithIsStatic(n,s,i,o){const l=this.tsTryParseIndexSignature(s);if(l){n.body.push(l),s.abstract&&this.raise(qe.IndexSignatureHasAbstract,s),s.accessibility&&this.raise(qe.IndexSignatureHasAccessibility,s,{modifier:s.accessibility}),s.declare&&this.raise(qe.IndexSignatureHasDeclare,s),s.override&&this.raise(qe.IndexSignatureHasOverride,s);return}!this.state.inAbstractClass&&s.abstract&&this.raise(qe.NonAbstractClassHasAb
5643stractMethod,s),s.override&&(i.hadSuperClass||this.raise(qe.OverrideNotInSubClass,s)),super.parseClassMemberWithIsStatic(n,s,i,o)}parsePostMemberNameModifiers(n){this.eat(13)&&(n.optional=!0),n.readonly&&this.match(6)&&this.raise(qe.ClassMethodHasReadonly,n),n.declare&&this.match(6)&&this.raise(qe.ClassMethodHasDeclare,n)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(n,s,i){if(!this.match(13))return n;if(i!=null){const c=this.lookaheadCharCode();if(c===44||c===61||c===58||c===41)return this.setOptionalParametersError(i),n}this.next();const o=this.startNodeAt(s);o.test=n;const l=this.state.inConditionalConsequent;return this.state.inConditionalConsequent=!0,o.consequent=this.parseMaybeAssignAllowIn(),this.state.inConditionalConsequent=l,this.expect(10),o.alternate=this.parseMaybeAssign(),this.finishNode(o,"ConditionalExpression")}parseParenItem(n,s){const i=super.parseParenItem(n,s);if(this.eat(13)&&(i.optional=!0,this.resetEndLocation(n)),this.match(10)){const o=this.startNodeAt(s);return o.expression=n,o.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(o,"TSTypeCastExpression")}return n}parseExportDeclaration(n){if(!this.state.isAmbientContext&&this.isContextual(121))return this.tsInAmbientContext(()=>this.parseExportDeclaration(n));const s=this.state.startLoc,i=this.eatContextual(121);if(i&&(this.isContextual(121)||!this.shouldParseExportDeclaration()))throw this.raise(qe.ExpectedAmbientAfterExportDeclare,this.state.startLoc);const l=or(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(n);return l?((l.type==="TSInterfaceDeclaration"||l.type==="TSTypeAliasDeclaration"||i)&&(n.exportKind="type"),i&&l.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(l,s),l.declare=!0),l):null}parseClassId(n,s,i,o){if((!s||i)&&this.isContextual(109)){n.id=null;return}super.parseClassId(n,s,i,n.declare?1024:8331);const l=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);l&&(n.typeParameters=l)}parseClassPropertyAnnotation(n){n.optional||(this.eat(31)?n.definite=!0:this.eat(13)&&(n.optional=!0));const s=this.tsTryParseTypeAnnotation();s&&(n.typeAnnotation=s)}parseClassProperty(n){if(this.parseClassPropertyAnnotation(n),this.state.isAmbientContext&&!(n.readonly&&!n.typeAnnotation)&&this.match(25)&&this.raise(qe.DeclareClassFieldHasInitializer,this.state.startLoc),n.abstract&&this.match(25)){const{key:s}=n;this.raise(qe.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:s.type==="Identifier"&&!n.computed?s.name:`[${this.input.slice(this.offsetToSourcePos(s.start),this.offsetToSourcePos(s.end))}]`})}return super.parseClassProperty(n)}parseClassPrivateProperty(n){return n.abstract&&this.raise(qe.PrivateElementHasAbstract,n),n.accessibility&&this.raise(qe.PrivateElementHasAccessibility,n,{modifier:n.accessibility}),this.parseClassPropertyAnnotation(n),super.parseClassPrivateProperty(n)}parseClassAccessorProperty(n){return this.parseClassPropertyAnnotation(n),n.optional&&this.raise(qe.AccessorCannotBeOptional,n),super.parseClassAccessorProperty(n)}pushClassMethod(n,s,i,o,l,c){const u=this.tsTryParseTypeParameters(this.tsParseConstModifier);u&&l&&this.raise(qe.ConstructorHasTypeParameters,u);const{declare:d=!1,kind:p}=s;d&&(p==="get"||p==="set")&&this.raise(qe.DeclareAccessor,s,{kind:p}),u&&(s.typeParameters=u),super.pushClassMethod(n,s,i,o,l,c)}pushClassPrivateMethod(n,s,i,o){const l=this.tsTryParseTypeParameters(this.tsParseConstModifier);l&&(s.typeParameters=l),super.pushClassPrivateMethod(n,s,i,o)}declareClassPrivateMethodInScope(n,s){n.type!=="TSDeclareMethod"&&(n.type==="MethodDefinition"&&n.value.body==null||super.declareClassPrivateMethodInScope(n,s))}parseClassSuper(n){if(super.parseClassSuper(n),n.superClass)if(n.superClass.type==="TSInstantiationExpression"){const s=n.superClass,i=s.expression;this.takeSurroundingComments(i,i.start,i.end);const o=s.typeArguments;this.takeSurroundingComments(o,o.start,o.end),n.superClass=i,n.superTypeArguments=o}else(this.match(43)||this.match(47))&&(n.superTypeArguments=this.tsParseTypeArgumentsInExpression());this.eatContextual(109)&&(n.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(n,s,i,o,l,c,u){const d=this.tsTryParseTypeParameters(this.tsParseConstModifier);return d&&(n.typeParameters=d),super.parseObjPropValue(n,s,i,o,l,c,u)}parseFunctionParams(n,s){const i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(n.typeParameters=i),super.parseFunctionParams(n,s)}parseVarId(n,s){super.parseVarId(n,s),n.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(31)&&(n.definite=!0);const i=this.tsTryParseTypeAnnotation();i&&(n.id.typeAnnotation=i,this.resetEndLocation(n.id))}parseAsyncArrowFromCallExpression(n,s){return this.match(10)&&(n.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(n,s)}parseMaybeAssign(n,s){let i,o,l;if(this.hasPlugin("jsx")&&(this.match(138)||this.match(43))){if(i=this.state.clone(),o=this.tryParse(()=>super.parseMaybeAssign(n,s),i),!o.error)return o.node;const{context:d}=this.state,p=d[d.length-1];
5643(p===Nr.j_oTag||p===Nr.j_expr)&&d.pop()}if(!(o!=null&&o.error)&&!this.match(43))return super.parseMaybeAssign(n,s);(!i||i===this.state)&&(i=this.state.clone());let c;const u=this.tryParse(d=>{var h,f;c=this.tsParseTypeParameters(this.tsParseConstModifier);const p=super.parseMaybeAssign(n,s);if((p.type!=="ArrowFunctionExpression"||(h=p.extra)!=null&&h.parenthesized)&&d(),(c==null?void 0:c.params.length)!==0&&this.resetStartLocationFromNode(p,c),p.typeParameters=c,this.hasPlugin("jsx")&&p.typeParameters.params.length===1&&!((f=p.typeParameters.extra)!=null&&f.trailingComma)){const x=p.typeParameters.params[0];x.constraint||this.raise(qe.SingleTypeParameterWithoutTrailingComma,this.optionFlags&256?Oa(x.loc.end,1):x,{typeParameterName:x.name.name})}return p},i);if(!u.error&&!u.aborted)return c&&this.reportReservedArrowTypeParam(c),u.node;if(!o&&(b2(!this.hasPlugin("jsx")),l=this.tryParse(()=>super.parseMaybeAssign(n,s),i),!l.error))return l.node;if(o!=null&&o.node)return this.state=o.failState,o.node;if(u.node)return this.state=u.failState,c&&this.reportReservedArrowTypeParam(c),u.node;if(l!=null&&l.node)return this.state=l.failState,l.node;throw(o==null?void 0:o.error)||u.error||(l==null?void 0:l.error)}reportReservedArrowTypeParam(n){var s;n.params.length===1&&!n.params[0].constraint&&!((s=n.extra)!=null&&s.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(qe.ReservedArrowTypeParam,n)}parseMaybeUnary(n,s){return!this.hasPlugin("jsx")&&this.match(43)?this.tsParseTypeAssertion():super.parseMaybeUnary(n,s)}parseArrow(n){if(this.match(10)){const s=this.tryParse(i=>{const o=this.tsParseTypeOrTypePredicateAnnotation(10);return(this.canInsertSemicolon()||!this.match(15))&&i(),o});if(s.aborted)return;s.thrown||(s.error&&(this.state=s.failState),n.returnType=s.node)}return super.parseArrow(n)}parseFunctionParamType(n){this.eat(13)&&(n.optional=!0);const s=this.tsTryParseTypeAnnotation();return s&&(n.typeAnnotation=s),this.resetEndLocation(n),n}isAssignable(n,s){switch(n.type){case"TSTypeCastExpression":return this.isAssignable(n.expression,s);case"TSParameterProperty":return!0;default:return super.isAssignable(n,s)}}toAssignable(n,s=!1){switch(n.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(n,s);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":s?this.expressionScope.recordArrowParameterBindingError(qe.UnexpectedTypeCastInParameter,n):this.raise(qe.UnexpectedTypeCastInParameter,n),this.toAssignable(n.expression,s);break;case"AssignmentExpression":!s&&n.left.type==="TSTypeCastExpression"&&(n.left=this.typeCastToParameter(n.left));default:super.toAssignable(n,s)}}toAssignableParenthesizedExpression(n,s){switch(n.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(n.expression,s);break;default:super.toAssignable(n,s)}}checkToRestConversion(n,s){switch(n.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(n.expression,!1);break;default:super.checkToRestConversion(n,s)}}isValidLVal(n,s,i,o){switch(n){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(o!==64||!i)&&["expression",!0];default:return super.isValidLVal(n,s,i,o)}}parseBindingAtom(){return this.state.type===74?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(n,s){if(this.match(43)||this.match(47)){const i=this.tsParseTypeArgumentsInExpression();if(this.match(6)){const o=super.parseMaybeDecoratorArguments(n,s);return o.typeArguments=i,o}this.unexpected(null,6)}return super.parseMaybeDecoratorArguments(n,s)}checkCommaAfterRest(n){return this.state.isAmbientContext&&this.match(8)&&this.lookaheadCharCode()===n?(this.next(),!1):super.checkCommaAfterRest(n)}isClassMethod(){return this.match(43)||super.isClassMethod()}isClassProperty(){return this.match(31)||this.match(10)||super.isClassProperty()}parseMaybeDefault(n,s){const i=super.parseMaybeDefault(n,s);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(qe.TypeAnnotationAfterAssign,i.typeAnnotation),i}getTokenFromCode(n){if(this.state.inType){if(n===62){this.finishOp(44,1);return}if(n===60){this.finishOp(43,1);return}}super.getTokenFromCode(n)}reScan_lt_gt(){const{type:n}=this.state;n===43?(this.state.pos-=1,this.readToken_lt()):n===44&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){const{type:n}=this.state;return n===47?(this.state.pos-=2,this.finishOp(43,1),43):n}toAssignableListItem(n,s,i){const o=n[s];o.type==="TSTypeCastExpression"&&(n[s]=this.typeCastToParameter(o)),super.toAssignableListItem(n,s,i)}typeCastToParameter(n){return n.expression.typeAnnotation=n.typeAnnotation,this.resetEndLocationFromNode(n.expression,n.typeAnnotation),n.expression}shouldParseArrow(n){return this.match(10)?n.every(s=>this.isAssignable(s,!0)):super.shouldParseArrow(n)}shouldParseAsyncArrow(){return this.match(10)?!this.state.inConditionalConsequent:super.shouldParseAsyncArrow()}parseParenAndDistinguishExpression(n){const s=this.state.inConditionalConsequent;this.state.inConditionalConsequent=!1;const i=super.parseParenAndDistinguishExpression(n);return this.state.inConditionalConsequent=s,i}
5643canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(n){if(this.match(43)||this.match(47)){const s=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());s&&(n.typeArguments=s)}return super.jsxParseOpeningElementAfterName(n)}getGetterSetterExpectedParamCount(n){const s=super.getGetterSetterExpectedParamCount(n),o=this.getObjectOrClassMethodParams(n)[0];return o&&this.isThisParam(o)?s+1:s}parseCatchClauseParam(){const n=super.parseCatchClauseParam(),s=this.tsTryParseTypeAnnotation();return s&&(n.typeAnnotation=s,this.resetEndLocation(n)),n}tsInAmbientContext(n){const{isAmbientContext:s,strict:i}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return n()}finally{this.state.isAmbientContext=s,this.state.strict=i}}parseClass(n,s,i){const o=this.state.inAbstractClass;this.state.inAbstractClass=!!n.abstract;try{return super.parseClass(n,s,i)}finally{this.state.inAbstractClass=o}}tsParseAbstractDeclaration(n,s){if(this.match(76))return n.abstract=!0,this.maybeTakeDecorators(s,this.parseClass(n,!0,!1));if(this.isContextual(125))return this.hasFollowingLineBreak()?null:(n.abstract=!0,this.raise(qe.NonClassMethodPropertyHasAbstractModifier,n),this.tsParseInterfaceDeclaration(n));throw this.unexpected(null,76)}parseMethod(n,s,i,o,l,c,u){const d=super.parseMethod(n,s,i,o,l,c,u);if((d.abstract||d.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?d.value:d).body){const{key:f}=d;this.raise(qe.AbstractMethodHasImplementation,d,{methodName:f.type==="Identifier"&&!d.computed?f.name:`[${this.input.slice(this.offsetToSourcePos(f.start),this.offsetToSourcePos(f.end))}]`})}return d}tsParseTypeParameterName(){return this.parseIdentifier()}shouldParseAsAmbientContext(){return!!this.getPluginOption("typescript","dts")}parse(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.parse()}getExpression(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.getExpression()}parseExportSpecifier(n,s,i,o){return!s&&o?(this.parseTypeOnlyImportExportSpecifier(n,!1,i),this.finishNode(n,"ExportSpecifier")):(n.exportKind="value",super.parseExportSpecifier(n,s,i,o))}parseImportSpecifier(n,s,i,o,l){return!s&&o?(this.parseTypeOnlyImportExportSpecifier(n,!0,i),this.finishNode(n,"ImportSpecifier")):(n.importKind="value",super.parseImportSpecifier(n,s,i,o,i?4098:4096))}parseTypeOnlyImportExportSpecifier(n,s,i){const o=s?"imported":"local",l=s?"local":"exported";let c=n[o],u,d=!1,p=!0;const h=c.start;if(this.isContextual(89)){const x=this.parseIdentifier();if(this.isContextual(89)){const g=this.parseIdentifier();ti(this.state.type)?(d=!0,c=x,u=s?this.parseIdentifier():this.parseModuleExportName(),p=!1):(u=g,p=!1)}else ti(this.state.type)?(p=!1,u=s?this.parseIdentifier():this.parseModuleExportName()):(d=!0,c=x)}else ti(this.state.type)&&(d=!0,s?(c=this.parseIdentifier(!0),this.isContextual(89)||this.checkReservedWord(c.name,c.start,!0,!0)):c=this.parseModuleExportName());d&&i&&this.raise(s?qe.TypeModifierIsUsedInTypeImports:qe.TypeModifierIsUsedInTypeExports,h),n[o]=c,n[l]=u;const f=s?"importKind":"exportKind";n[f]=d?"type":"value",p&&this.eatContextual(89)&&(n[l]=s?this.parseIdentifier():this.parseModuleExportName()),n[l]||(n[l]=this.cloneIdentifier(n[o])),s&&this.checkIdentifier(n[l],d?4098:4096)}fillOptionalPropertiesForTSESLint(n){switch(n.type){case"ExpressionStatement":n.directive??(n.directive=void 0);return;case"RestElement":n.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":n.decorators??(n.decorators=[]),n.optional??(n.optional=!1),n.typeAnnotation??(n.typeAnnotation=void 0);return;case"TSParameterProperty":n.accessibility??(n.accessibility=void 0),n.decorators??(n.decorators=[]),n.override??(n.override=!1),n.readonly??(n.readonly=!1),n.static??(n.static=!1);return;case"TSEmptyBodyFunctionExpression":n.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":n.declare??(n.declare=!1),n.returnType??(n.returnType=void 0),n.typeParameters??(n.typeParameters=void 0);return;case"Property":n.optional??(n.optional=!1);return;case"TSMethodSignature":case"TSPropertySignature":n.optional??(n.optional=!1);case"TSIndexSignature":n.accessibility??(n.accessibility=void 0),n.readonly??(n.readonly=!1),n.static??(n.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":n.declare??(n.declare=!1),n.definite??(n.definite=!1),n.readonly??(n.readonly=!1),n.typeAnnotation??(n.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":n.accessibility??(n.accessibility=void 0),n.decorators??(n.decorators=[]),n.override??(n.override=!1),n.optional??(n.optional=!1);return;case"ClassExpression":n.id??(n.id=null);case"ClassDeclaration":n.abstract??(n.abstract=!1),n.declare??(n.declare=!1),n.decorators??(n.decorators=[]),n.implements??(n.implements=[]),n.superTypeArguments??(n.superTypeArguments=void 0),n.typeParameters??(n.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":n.declare??(n.declare=!1);return;case"VariableDeclarator":n.definite??(n.definite=!1);return;case"TSEnumDeclaration":n.const??(n.const=!1),n.declare??(n.declare=!1);return;case"TSEnumMember":n.computed??(n.computed=!1);return;case"TSImportType":n.qualifier??(n.qualifier=null),n.options??(n.options=null),n.typeArguments??(n.typeArguments=null);return;case"TSInterfaceDeclaration":n.declare??(n.declare=!1),n.extends??(n.extends=[]);return;case"TSMappedType":n.optional??(n.optional=!1),n.readonly??(n.readonly=void 0);return;case"TSModuleDeclaration":n.declare??(n.declare=!1),n.global??(n.global=n.kind==="global");return;case"TSTypeParameter":n.const??(n.const=!1),n.in??(n.in=!1),n.out??(n.out=!1);return}}
5643chStartsBindingIdentifierAndNotRelationalOperator(n,s){if(Si(n)){if(Zy.lastIndex=s,Zy.test(this.input)){const i=this.codePointAtPos(Zy.lastIndex);if(!ec(i)&&i!==92)return!1}return!0}else return n===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){const n=this.nextTokenInLineStart(),s=this.codePointAtPos(n);return this.chStartsBindingIdentifierAndNotRelationalOperator(s,n)}nextTokenIsStringLiteralOnSameLine(){const n=this.nextTokenInLineStart(),s=this.codePointAtPos(n);return s===34||s===39}};function pJ(e){if(e.type!=="MemberExpression")return!1;const{computed:t,property:r}=e;return t&&r.type!=="StringLiteral"&&(r.type!=="TemplateLiteral"||r.expressions.length>0)?!1:EI(e.object)}function hJ(e,t){var n;const{type:r}=e;if((n=e.extra)!=null&&n.parenthesized)return!1;if(t){if(r==="Literal"){const{value:s}=e;if(typeof s=="string"||typeof s=="boolean")return!0}}else if(r==="StringLiteral"||r==="BooleanLiteral")return!0;return!!(TI(e,t)||fJ(e,t)||r==="TemplateLiteral"&&e.expressions.length===0||pJ(e))}function TI(e,t){return t?e.type==="Literal"&&(typeof e.value=="number"||"bigint"in e):e.type==="NumericLiteral"||e.type==="BigIntLiteral"}function fJ(e,t){if(e.type==="UnaryExpression"){const{operator:r,argument:n}=e;if(r==="-"&&TI(n,t))return!0}return!1}function EI(e){return e.type==="Identifier"?!0:e.type!=="MemberExpression"||e.computed?!1:EI(e.object)}const mJ={ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."},w2=Za`placeholders`(mJ),gJ=e=>class extends e{parsePlaceholder(r){if(this.match(129)){const n=this.startNode();return this.next(),this.assertNoSpace(),n.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(129),this.finishPlaceholder(n,r)}}finishPlaceholder(r,n){let s=r;return(!s.expectedNode||!s.type)&&(s=this.finishNode(s,"Placeholder")),s.expectedNode=n,s}getTokenFromCode(r){r===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(129,2):super.getTokenFromCode(r)}parseExprAtom(r){return this.parsePlaceholder("Expression")||super.parseExprAtom(r)}parseIdentifier(r){return this.parsePlaceholder("Identifier")||super.parseIdentifier(r)}checkReservedWord(r,n,s,i){r!==void 0&&super.checkReservedWord(r,n,s,i)}cloneIdentifier(r){const n=super.cloneIdentifier(r);return n.type==="Placeholder"&&(n.expectedNode=r.expectedNode),n}cloneStringLiteral(r){return r.type==="Placeholder"?this.cloneIdentifier(r):super.cloneStringLiteral(r)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(r,n,s,i){return r==="Placeholder"||super.isValidLVal(r,n,s,i)}toAssignable(r,n){r&&r.type==="Placeholder"&&r.expectedNode==="Expression"?r.expectedNode="Pattern":super.toAssignable(r,n)}chStartsBindingIdentifier(r,n){if(super.chStartsBindingIdentifier(r,n))return!0;const s=this.nextTokenStart();return this.input.charCodeAt(s)===37&&this.input.charCodeAt(s+1)===37}verifyBreakContinue(r,n){var s;((s=r.label)==null?void 0:s.type)!=="Placeholder"&&super.verifyBreakContinue(r,n)}parseExpressionStatement(r,n){var i;if(n.type!=="Placeholder"||(i=n.extra)!=null&&i.parenthesized)return super.parseExpressionStatement(r,n);if(this.match(10)){const o=r;return o.label=this.finishPlaceholder(n,"Identifier"),this.next(),o.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(o,"LabeledStatement")}this.semicolon();const s=r;return s.name=n.name,this.finishPlaceholder(s,"Statement")}parseBlock(r,n,s){return this.parsePlaceholder("BlockStatement")||super.parseBlock(r,n,s)}parseFunctionId(r){return this.parsePlaceholder("Identifier")||super.parseFunctionId(r)}parseClass(r,n,s){const i=n?"ClassDeclaration":"ClassExpression";this.next();const o=this.state.strict,l=this.parsePlaceholder("Identifier");if(l)if(this.match(77)||this.match(129)||this.match(2))r.id=l;else{if(s||!n)return r.id=null,r.body=this.finishPlaceholder(l,"ClassBody"),this.finishNode(r,i);throw this.raise(w2.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(r,n,s);return super.parseClassSuper(r),r.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!r.superClass,o),this.finishNode(r,i)}parseExport(r,n){const s=this.parsePlaceholder("Identifier");if(!s)return super.parseExport(r,n);const i=r;if(!this.isContextual(94)&&!this.match(8))return i.specifiers=[],i.source=null,i.declaration=this.finishPlaceholder(s,"Declaration"),this.finishNode(i,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");const o=this.startNode();return o.exported=s,i.specifiers=[this.finishNode(o,"ExportDefaultSpecifier")],super.parseExport(i,n)}
5643isExportDefaultSpecifier(){if(this.match(61)){const r=this.nextTokenStart();if(this.isUnparsedContextual(r,"from")&&this.input.startsWith(Jo(129),this.nextTokenStartSince(r+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(r,n){var s;return(s=r.specifiers)!=null&&s.length?!0:super.maybeParseExportDefaultSpecifier(r,n)}checkExport(r){const{specifiers:n}=r;n!=null&&n.length&&(r.specifiers=n.filter(s=>s.exported.type==="Placeholder")),super.checkExport(r),r.specifiers=n}parseImport(r){const n=this.parsePlaceholder("Identifier");if(!n)return super.parseImport(r);if(r.specifiers=[],!this.isContextual(94)&&!this.match(8))return r.source=this.finishPlaceholder(n,"StringLiteral"),this.semicolon(),this.finishNode(r,"ImportDeclaration");const s=this.startNodeAtNode(n);return s.local=n,r.specifiers.push(this.finishNode(s,"ImportDefaultSpecifier")),this.eat(8)&&(this.maybeParseStarImportSpecifier(r)||this.parseNamedImportSpecifiers(r)),this.expectContextual(94),r.source=this.parseImportSource(),this.semicolon(),this.finishNode(r,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(w2.UnexpectedSpace,this.state.lastTokEndLoc)}},xJ=e=>class extends e{parseV8Intrinsic(){if(this.match(50)){const r=this.state.startLoc,n=this.startNode();if(this.next(),or(this.state.type)){const s=this.parseIdentifierName(),i=this.createIdentifier(n,s);if(this.castNodeTo(i,"V8IntrinsicIdentifier"),this.match(6))return i}this.unexpected(r)}}parseExprAtom(r){return this.parseV8Intrinsic()||super.parseExprAtom(r)}},j2=["fsharp","hack"],N2=["^^","@@","^","%","#"];function yJ(e){if(e.has("decorators")&&e.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");if(e.has("flow")&&e.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(e.has("placeholders")&&e.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(e.has("pipelineOperator")){const t=e.get("pipelineOperator").proposal;if(!j2.includes(t)){const r=j2.map(n=>`"${n}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${r}.`)}if(t==="hack"){if(e.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(e.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");const r=e.get("pipelineOperator").topicToken;if(!N2.includes(r)){const n=N2.map(s=>`"${s}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${n}.`)}}}if(e.has("moduleAttributes"))throw new Error("`moduleAttributes` has been removed in Babel 8, please migrate to import attributes instead.");if(e.has("importAssertions"))throw new Error("`importAssertions` has been removed in Babel 8, please use import attributes instead.");if(e.has("deprecatedImportAssert")?console.warn("`deprecatedImportAssert` has been removed in Babel 8, please use import attributes instead."):e.has("importAttributes")&&e.get("importAttributes").deprecatedAssertSyntax&&console.warn("The 'importAttributes' plugin has been removed in Babel 8. Please migrate any usage of `assert`-style attributes to `with`."),e.has("recordAndTuple"))throw new Error("The 'recordAndTuple' plugin has been removed in Babel 8. Please remove it from your configuration.");if(e.has("asyncDoExpressions")&&!e.has("doExpressions")){const t=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw t.missingPlugins="doExpressions",t}if(e.has("optionalChainingAssign")&&e.get("optionalChainingAssign").version!=="2023-07")throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.");if(e.has("discardBinding")&&e.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.");if(e.has("decimal"))throw new Error("The 'decimal' plugin has been removed in Babel 8. Please remove it from your configuration.");
5643if(e.has("importReflection"))throw new Error("The 'importReflection' plugin has been removed in Babel 8. Use 'sourcePhaseImports' instead, and replace 'import module' with 'import source' in your code.")}const II={estree:QK,jsx:DY,flow:TY,typescript:dJ,v8intrinsic:xJ,placeholders:gJ},bJ=Object.keys(II);class OI extends iJ{constructor(t,r,n){const s=ZK(t);super(s,r),this.options=s,this.initializeScopes(),this.plugins=n,this.filename=s.sourceFilename,this.startIndex=s.startIndex;let i=0;s.allowAwaitOutsideFunction&&(i|=1),s.allowReturnOutsideFunction&&(i|=2),s.allowImportExportEverywhere&&(i|=8),s.allowSuperOutsideMethod&&(i|=16),s.allowUndeclaredExports&&(i|=64),s.allowNewTargetOutsideFunction&&(i|=4),s.allowYieldOutsideFunction&&(i|=32),s.ranges&&(i|=128),s.locations===!0&&(i|=256),s.tokens&&(i|=512),s.createImportExpressions&&(i|=1024),s.createParenthesizedExpressions&&(i|=2048),s.errorRecovery&&(i|=4096),s.attachComment&&(i|=8192),s.annexB&&(i|=16384),this.optionFlags=i}getScopeHandler(){return M1}parse(){this.enterInitialScopes();const t=this.startNode(),r=this.startNode();this.nextToken(),t.errors=[];const n=this.parseTopLevel(t,r);return n.errors=this.state.errors,n.comments.length=this.state.commentsLen,n}}function RI(e,t){if((t==null?void 0:t.sourceType)==="unambiguous"){t={...t};try{t.sourceType="module";const r=Cf(t,e),n=r.parse();if(r.sawUnambiguousESM)return n;if(r.ambiguousScriptDifferentAst)try{return t.sourceType="script",Cf(t,e).parse()}catch{}else n.program.sourceType="script";return n}catch(r){try{return t.sourceType="script",Cf(t,e).parse()}catch{}throw r}}else return Cf(t,e).parse()}function vJ(e){const t={};for(const r of Object.keys(e))t[r]=xI(e[r]);return t}vJ(tY);function Cf(e,t){let r=OI;const n=new Map;if(e!=null&&e.plugins){for(const s of e.plugins){let i,o;typeof s=="string"?i=s:[i,o]=s,n.has(i)||n.set(i,o||{})}yJ(n),r=wJ(n)}return new r(e,t,n)}const k2=new Map;function wJ(e){const t=[];for(const s of bJ)e.has(s)&&t.push(s);const r=t.join("|");let n=k2.get(r);if(!n){n=OI;for(const s of t)n=II[s](n);k2.set(r,n)}return n}const jJ={text:"bg-emerald-500/10 text-emerald-600",string:"bg-emerald-500/10 text-emerald-600",number:"bg-blue-500/10 text-blue-600",integer:"bg-blue-500/10 text-blue-600",int:"bg-blue-500/10 text-blue-600",float:"bg-blue-500/10 text-blue-600",boolean:"bg-amber-500/10 text-amber-600",bool:"bg-amber-500/10 text-amber-600",uuid:"bg-purple-500/10 text-purple-600",json:"bg-pink-500/10 text-pink-600",jsonb:"bg-pink-500/10 text-pink-600",timestamp:"bg-orange-500/10 text-orange-600",timestamptz:"bg-orange-500/10 text-orange-600",date:"bg-orange-500/10 text-orange-600"};function NJ({table:e,expanded:t,onToggle:r}){return a.jsxs("div",{className:"border rounded-xl bg-card overflow-hidden",children:[a.jsxs("button",{onClick:r,className:"w-full flex items-center gap-2.5 px-3 py-2.5 hover:bg-secondary/30 transition-colors text-left",children:[t?a.jsx(Yr,{className:"w-3.5 h-3.5 text-muted-foreground"}):a.jsx(ia,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx(Di,{className:"w-4 h-4 text-primary"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-sm font-semibold text-foreground",children:e.displayName}),a.jsx("span",{className:"text-[10px] text-muted-foreground ml-2 font-mono",children:e.tableName})]}),a.jsxs("span",{className:"text-[10px] text-muted-foreground bg-secondary px-2 py-0.5 rounded-full",children:[e.columns.length," cols"]})]}),t&&a.jsxs("div",{className:"border-t px-3 py-2 space-y-1",children:[e.description&&a.jsx("p",{className:"text-[11px] text-muted-foreground mb-2",children:e.description}),a.jsx("div",{className:"space-y-0.5",children:e.columns.map(n=>a.jsxs("div",{className:"flex items-center gap-2 py-1 px-2 rounded-lg hover:bg-secondary/20",children:[a.jsx(uT,{className:"w-3 h-3 text-muted-foreground shrink-0"}),a.jsx("span",{className:"text-xs font-mono font-medium text-foreground min-w-[80px]",children:n.name}),a.jsx("span",{className:L("text-[10px] font-mono px-1.5 py-0.5 rounded",jJ[n.type.toLowerCase()]||"bg-secondary text-muted-foreground"),children:n.type}),n.is_primary&&a.jsx("span",{className:"text-[9px] font-semibold text-primary bg-primary/10 px-1.5 py-0.5 rounded",children:"PK"}),!n.nullable&&!n.is_primary&&a.jsx("span",{className:"text-[9px] text-muted-foreground",children:"NOT NULL"}),n.default_value&&a.jsxs("span",{className:"text-[9px] text-muted-foreground font-mono truncate",children:["= ",n.default_value]})]},n.name))}),a.jsx("p",{className:"text-[10px] text-muted-foreground italic pt-1 border-t border-dashed",children:"+ id, created_at, updated_at auto-added if not present"})]})]})}function kJ({proposal:e,onApprove:t,onReject:r,status:n}){const[s,i]=m.useState(new Set(e.tables.map(c=>c.tableName))),o=c=>{i(u=>{const d=new Set(u);return d.has(c)?d.delete(c):d.add(c),d})},l=n==="approved"||n==="rejected";return a.jsxs("div",{className:L("space-y-3",l&&"opacity-60 pointer-events-none"),children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center",children:a.jsx(Hn,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Database Schema Proposal"}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[e.tables.length," table",e.tables.length>
56431?"s":""," will be created in your project database"]})]})]}),e.intro&&a.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:e.intro}),a.jsx("div",{className:"space-y-2",children:e.tables.map(c=>a.jsx(NJ,{table:c,expanded:s.has(c.tableName),onToggle:()=>o(c.tableName)},c.tableName))}),e.seedData&&Object.keys(e.seedData).length>0&&a.jsxs("div",{className:"text-[10px] text-muted-foreground bg-secondary/30 rounded-lg px-3 py-2",children:["📦 Includes seed data for: ",Object.keys(e.seedData).join(", ")]}),n==="pending"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Q,{onClick:t,size:"sm",className:"flex-1 gap-1.5 rounded-xl",children:[a.jsx(Wn,{className:"w-3.5 h-3.5"}),"Approve & Create"]}),a.jsxs(Q,{onClick:r,variant:"outline",size:"sm",className:"gap-1.5 rounded-xl",children:[a.jsx(qn,{className:"w-3.5 h-3.5"}),"Reject"]})]}),n==="creating"&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-primary",children:[a.jsx(ze,{className:"w-4 h-4 animate-spin"}),"Creating tables..."]}),n==="approved"&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-emerald-600",children:[a.jsx(Wn,{className:"w-4 h-4"}),"Tables created successfully"]}),n==="rejected"&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[a.jsx(qn,{className:"w-4 h-4"}),"Schema proposal rejected"]})]})}function SJ({request:e,onComplete:t,projectId:r}){const[n,s]=m.useState({}),[i,o]=m.useState({}),[l,c]=m.useState(!1),[u,d]=m.useState(!1),[p,h]=m.useState(null),f=e.secrets.filter(g=>g.required!==!1).every(g=>(n[g.key]||"").trim().length>0),x=async()=>{if(!r){h("No project selected");return}c(!0),h(null);try{const g=e.secrets.filter(v=>(n[v.key]||"").trim()).map(v=>({key:v.key,value:n[v.key].trim()})),{data:y,error:b}=await G.functions.invoke("store-secret",{body:{projectId:r,secrets:g}});if(b||y!=null&&y.error)throw new Error((b==null?void 0:b.message)||(y==null?void 0:y.error)||"Failed to store secrets");d(!0),W.success(`${g.length} secret${g.length>1?"s":""} saved securely`),t(g.map(v=>v.key))}catch(g){h(g.message||"Failed to save secrets"),W.error("Failed to save secrets")}finally{c(!1)}};return u?a.jsx("div",{className:"mt-3 p-4 rounded-xl border-2 border-primary/20 bg-primary/5",children:a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/15 flex items-center justify-center",children:a.jsx(Wn,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Secrets saved securely"}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:e.secrets.filter(g=>(n[g.key]||"").trim()).map(g=>g.label).join(", ")})]})]})}):a.jsxs("div",{className:"mt-3 rounded-xl border-2 border-amber-500/20 bg-amber-500/5 overflow-hidden",children:[a.jsxs("div",{className:"px-4 py-3 bg-amber-500/10 border-b border-amber-500/15 flex items-center gap-2.5",children:[a.jsx("div",{className:"w-7 h-7 rounded-lg bg-amber-500/20 flex items-center justify-center",children:a.jsx(os,{className:"w-3.5 h-3.5 text-amber-600"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Secure Credential Input"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Encrypted and stored securely — never visible in chat"})]})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-xs text-muted-foreground",children:e.intro}),e.secrets.map(g=>a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("label",{className:"flex items-center gap-1.5 text-xs font-semibold text-foreground",children:[a.jsx(Bs,{className:"w-3 h-3 text-muted-foreground"}),g.label,g.required!==!1&&a.jsx("span",{className:"text-destructive",children:"*"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:g.description}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:i[g.key]?"text":"password",value:n[g.key]||"",onChange:y=>s(b=>
5643({...b,[g.key]:y.target.value})),placeholder:g.placeholder||`Enter ${g.label}...`,className:L("w-full h-9 px-3 pr-9 rounded-lg border bg-background text-xs font-mono","placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary/40","transition-all"),autoComplete:"off",spellCheck:!1,"data-1p-ignore":!0}),a.jsx("button",{type:"button",onClick:()=>o(y=>({...y,[g.key]:!y[g.key]})),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors",children:i[g.key]?a.jsx(ku,{className:"w-3.5 h-3.5"}):a.jsx(ys,{className:"w-3.5 h-3.5"})})]})]},g.key)),p&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-destructive",children:[a.jsx(is,{className:"w-3.5 h-3.5 shrink-0"}),a.jsx("span",{children:p})]}),a.jsxs(Q,{onClick:x,disabled:!f||l,className:"w-full gap-2 h-9 text-xs font-semibold",size:"sm",children:[l?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(os,{className:"w-3.5 h-3.5"}),l?"Encrypting & saving...":"Save Securely"]}),a.jsx("p",{className:"text-[10px] text-muted-foreground text-center",children:"🔒 Credentials are encrypted and stored in your project's secure vault. They are never exposed in chat or code."})]})]})}const $1=[{id:"ui-ux-pro-max",name:"UI/UX Pro Max",description:"Pro design intelligence — accessibility, layout, typography, color, states & polish (composes with Motion).",url:"https://github.com/nextlevelbuilder/ui-ux-pro-max-skill",guidance:`UI/UX PRO MAX — Apply professional design intelligence to every screen and component, in this priority order:
56441) ACCESSIBILITY (critical): text contrast ≥ 4.5:1 (3:1 large), visible focus rings (never remove them), alt text, aria-label on icon-only buttons, logical tab order + full keyboard support, sequential heading hierarchy, and never convey meaning by color alone (add icon/text).
56452) TOUCH & INTERACTION (critical): min 44×44px hit targets with ≥8px spacing, click/tap for primary actions (don't rely on hover), disable buttons during async + show a spinner, and give visual feedback within ~100ms.
56463) PERFORMANCE: lazy-load below-the-fold media, set width/height or aspect-ratio to avoid layout shift (CLS), code-split by route, use skeletons for >1s loads.
56474) STYLE: pick one coherent style for the product type (minimal, glassmorphism, bento, brutalism, neumorphism, flat, dark mode, etc.) and keep it consistent across pages; SVG icons (lucide-react) — NEVER emoji as icons; one primary CTA per screen with secondary actions subordinate; a consistent elevation/shadow scale.
56485) LAYOUT: mobile-first responsive breakpoints, no horizontal scroll, fluid containers (no fixed px widths).
56496) TYPOGRAPHY & COLOR: 16px base body, line-height ~1.5, a curated font pairing, and semantic color tokens (Tailwind/CSS vars) — no raw hex scattered in components, no gray-on-gray, no <12px body text.
56507) ANIMATION: durations 150–300ms, motion must convey meaning (spatial continuity, state changes), animate transform/opacity only, and always respect prefers-reduced-motion. When the Motion skill is enabled, implement these with Motion (\`motion/react\`).
56518) FORMS: visible labels (not placeholder-only), inline errors near the field, helper text, progressive disclosure.
56529) NAVIGATION: predictable back behavior, bottom nav ≤5 items, clear active state.
565310) CHARTS/DATA: legends + tooltips, accessible colors, never color-only encoding.
5654Goal: ship interfaces that look and feel professionally designed, not generic. Reference: ui-ux-pro-max (50+ styles, 161 palettes, 57 font pairings, 99 UX guidelines).`},{id:"motion",name:"Motion (animations)",description:"Production-grade animations & micro-interactions via Motion (motion.dev).",url:"https://motion.dev/",npm:"motion",guidance:"ANIMATIONS — Use Motion (motion.dev) for animations and micro-interactions. Add the `motion` package to package.json and import from `motion/react` (e.g. `import { motion, AnimatePresence } from 'motion/react'`). Prefer `motion.<tag>` elements with `initial`/`animate`/`exit`/`transition`, `whileHover`/`whileTap` for interaction feedback, layout animations, and `AnimatePresence` for mou
5654nt/unmount. Keep motion subtle and performant — animate transform/opacity, respect `prefers-reduced-motion`, and avoid animating layout-thrashing properties."},{id:"charts",name:"Data charts (Recharts)",description:"Responsive charts & dashboards with Recharts.",url:"https://recharts.org/",npm:"recharts",guidance:"DATA VISUALIZATION — When the app shows metrics, trends, or dashboards, use Recharts (`recharts`) for charts. Wrap charts in `ResponsiveContainer`, pick the right chart type (Line/Area/Bar/Pie), and theme colors from the design system. Keep axes/legends readable and handle empty/loading states."},{id:"three",name:"3D (React Three Fiber)",description:"Interactive 3D scenes with three.js via React Three Fiber.",url:"https://r3f.docs.pmnd.rs/",npm:"@react-three/fiber",guidance:"3D GRAPHICS — For 3D scenes/visuals, use React Three Fiber (`@react-three/fiber`) with `@react-three/drei` helpers. Render the `<Canvas>` lazily, keep scenes lightweight, dispose resources, and provide a 2D fallback for low-power devices."},{id:"gsap",name:"GSAP (advanced animation)",description:"Timeline & scroll-triggered animations.",url:"https://gsap.com/",npm:"gsap",guidance:"ADVANCED ANIMATION — For complex sequenced timelines or scroll-driven effects, use GSAP (`gsap`) with ScrollTrigger. Prefer it over Motion when you need precise multi-step timelines, scrubbing, or pinning. Clean up tweens on unmount and respect prefers-reduced-motion."},{id:"lottie",name:"Lottie (vector animations)",description:"Play designer JSON / After Effects animations.",url:"https://lottiefiles.com/",npm:"lottie-react",guidance:"VECTOR ANIMATIONS — Use `lottie-react` to play Lottie JSON animations (hero illustrations, success checks, empty states). Lazy-load the JSON, set sensible loop/autoplay, keep files small."},{id:"auto-animate",name:"Auto Animate",description:"One-line automatic list/layout transitions.",url:"https://auto-animate.formkit.com/",npm:"@formkit/auto-animate",guidance:"EFFORTLESS TRANSITIONS — Use `@formkit/auto-animate` for instant add/remove/reorder animations on lists and layout changes (one `useAutoAnimate()` ref on the parent). Good for to-do lists, tables, and accordions where full Motion choreography is overkill."},{id:"confetti",name:"Confetti",description:"Celebration / success burst effects.",url:"https://www.kirilv.com/canvas-confetti/",npm:"canvas-confetti",guidance:"CELEBRATION FX — Use `canvas-confetti` for success moments (signup complete, purchase, milestone). Fire sparingly on genuine wins, keep bursts short, and respect prefers-reduced-motion."},{id:"particles",name:"Particles background",description:"Animated particle / interactive backgrounds.",url:"https://particles.js.org/",npm:"@tsparticles/react",guidance:"PARTICLE BACKGROUNDS — Use `@tsparticles/react` (with `@tsparticles/slim`) for animated hero/section backgrounds. Keep particle counts low for performance, pause when offscreen, and keep foreground text readable (contrast)."},{id:"nivo",name:"Nivo (rich charts)",description:"Heatmaps, calendars, sankey, treemaps & more.",url:"https://nivo.rocks/",npm:"@nivo/core",guidance:"RICH CHARTS — For heatmaps, calendars, sankey, treemaps, or stream graphs, use Nivo (`@nivo/core` + the specific package, e.g. `@nivo/line`/`@nivo/bar`). Use the Responsive wrappers, accessible color scales, and always include legends/tooltips."},{id:"tanstack-table",name:"TanStack Table",description:"Sortable, filterable, paginated data grids.",url:"https://tanstack.com/table",npm:"@tanstack/react-table",guidance:"DATA TABLES — For non-trivial tables (sorting, filtering, pagination, column visibility), use `@tanstack/react-table` (headless) styled with the existing Tailwind/shadcn table primitives. Virtualize when rows exceed ~50."},{id:"spline",name:"Spline (designer 3D)",description:"Drop-in interactive 3D scenes from Spline.",url:"https://spline.design/",npm:"@splinetool/react-spline",guidance:"DESIGNER 3D — To embed a ready-made interactive 3D scene, use `@splinetool/react-spline` with a scene URL. Lazy-load it, show a fallback while loading, and prefer this over hand-coding R3F when the asset comes from Spline."}
5654,{id:"leaflet",name:"Maps (Leaflet)",description:"Open-source interactive maps.",url:"https://react-leaflet.js.org/",npm:"react-leaflet",guidance:"MAPS — Use `react-leaflet` (+ `leaflet`) for interactive maps (stores, locations, routes). Import Leaflet's CSS, set an explicit container height, cluster many markers, and add accessible labels."},{id:"tiptap",name:"Rich text editor (Tiptap)",description:"Notion-style WYSIWYG editor.",url:"https://tiptap.dev/",npm:"@tiptap/react",guidance:"RICH TEXT EDITOR — Use Tiptap (`@tiptap/react` + `@tiptap/starter-kit`) for WYSIWYG editing (notes, comments, CMS content). Provide a toolbar, serialize to HTML or JSON, and handle empty/placeholder states."},{id:"markdown",name:"Markdown rendering",description:"Render markdown content safely.",url:"https://github.com/remarkjs/react-markdown",npm:"react-markdown",guidance:"MARKDOWN — Use `react-markdown` (with `remark-gfm` for tables/checklists) to render markdown (docs, blog posts, AI responses). Style via the existing prose/typography classes; never dangerouslySetInnerHTML raw markdown."},{id:"dnd-kit",name:"Drag & drop",description:"Reorderable lists, kanban boards.",url:"https://dndkit.com/",npm:"@dnd-kit/core",guidance:"DRAG & DROP — Use `@dnd-kit/core` (+ `@dnd-kit/sortable`) for reorderable lists, kanban boards, and sortable grids. Keep it keyboard-accessible, show a drag overlay, and persist the new order."},{id:"seo",name:"SEO & meta tags",description:"Per-page titles, meta, Open Graph tags.",url:"https://github.com/staylor/react-helmet-async",npm:"react-helmet-async",guid
5654ance:"SEO — Use `react-helmet-async` to set per-page <title>, meta description, and Open Graph/Twitter tags. Wrap the app in HelmetProvider, give every route a unique title/description, and add canonical + social images."},{id:"zustand",name:"Lightweight state (Zustand)",description:"Simple global state without boilerplate.",url:"https://zustand.docs.pmnd.rs/",npm:"zustand",guidance:"GLOBAL STATE — When state must be shared across distant components (cart, auth UI, theme, multi-step flows), use a small Zustand store (`zustand`) instead of deep prop-drilling or overusing context. Keep stores small and colocate selectors."}],DI="sj_skills_v1";function MI(){try{const e=localStorage.getItem(DI);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const r=new Set($1.map(n=>n.id));return t.filter(n=>typeof n=="string"&&r.has(n))}catch{return[]}}function LI(e){try{localStorage.setItem(DI,JSON.stringify(e))}catch{}}function CJ(e){const t=$1.filter(n=>e.includes(n.id));return t.length===0?"":`ENABLED BUILDER SKILLS — the user has explicitly enabled these capabilities for this build. Apply them where relevant and add the named packages to package.json so they install in the preview:
5655${t.map(n=>{const s=n.npm?` (install: \`${n.npm}\`)`:"";return`- ${n.guidance}${s}`}).join(`
5656`)}`}function $I({value:e,onChange:t,isBuilding:r,placement:n="above",triggerClassName:s}){const[i,o]=m.useState(!1),l=new Set(e),c=e.length,u=d=>{t(l.has(d)?e.filter(p=>p!==d):[...e,d])};return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!i),disabled:r,className:L("flex items-center gap-1.5 px-2 py-1 rounded-lg text-[11px] font-medium transition-all border","hover:bg-secondary/80",i?"bg-secondary border-primary/20":"bg-transparent border-transparent",r&&"opacity-50 cursor-not-allowed",s),children:[a.jsx(Ok,{className:"w-3.5 h-3.5 shrink-0 text-violet-500"}),a.jsx("span",{className:"hidden min-[380px]:inline text-foreground",children:c>0?`Skills · ${c}`:"Skills"}),a.jsx(Yr,{className:L("w-3 h-3 text-muted-foreground transition-transform",i&&"rotate-180")})]}),i&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>o(!1)}),a.jsxs("div",{className:L("absolute left-0 w-80 bg-card border rounded-xl shadow-xl z-50 overflow-hidden",n==="below"?"top-full mt-2":"bottom-full mb-1.5"),children:[a.jsxs("div",{className:"px-3 py-2 border-b",children:[a.jsx("span",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Builder skills"}),a.jsx("p",{className:"mt-0.5 text-[9.5px] text-muted-foreground",children:"Opt-in capabilities the AI uses when building. None are on by default."})]}),a.jsx("div",{className:"py-1 max-h-[360px] overflow-y-auto",children:$1.map(d=>{const p=l.has(d.id);return a.jsxs("button",{type:"button",onClick:()=>u(d.id),className:L("w-full text-left px-3 py-2 transition-colors",p?"bg-primary/5":"hover:bg-secondary/50"),children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:L("flex h-4 w-4 items-center justify-center rounded border shrink-0",p?"bg-primary border-primary text-primary-foreground":"border-border"),children:p&&a.jsx(Wn,{className:"h-3 w-3"})}),a.jsx("span",{className:L("text-xs font-semibold",p&&"text-primary"),children:d.name}),d.url&&a.jsx("a",{href:d.url,target:"_blank",rel:"noreferrer",onClick:h=>h.stopPropagation(),className:"ml-auto text-muted-foreground hover:text-foreground",title:d.url,children:a.jsx(Is,{className:"h-3 w-3"})})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground ml-6 mt-0.5",children:d.description})]},d.id)})}),a.jsx("div",{className:"px-3 py-2 border-t bg-secondary/30",children:a.jsxs("p",{className:"text-[9px] text-muted-foreground",children:[a.jsx(Ok,{className:"w-3 h-3 inline mr-1 -mt-0.5"}),"Enabled skills are applied to every build until you turn them off."]})})]})]})]})}const Vc={builder:"auto",fixer:"claude-sonnet-4-6",reviewer:"gpt-5-5",visual:"gpt-5-5"},FI="sj_model_roles_v1";function PJ(){try{const e=localStorage.getItem(FI);if(!e)return Vc;const t=JSON.parse(e);return{builder:t.builder||Vc.builder,fixer:t.fixer||Vc.fixer,reviewer:t.reviewer||Vc.reviewer,visual:t.visual||Vc.visual}}catch{return Vc}}function AJ(e){try{localStorage.setItem(FI,JSON.stringify(e))}catch{}}const Qy=[{id:"auto",label:"Auto",tagline:"AI picks based on your brief's domain",icon:Dn,swatch:["#0E0E10","#FAFAFA","#3F65F5","#FFB347","#22C55E","#A855F7"]},{id:"linear",label:"Linear",tagline:"Modern minimal SaaS — clean, opinionated",icon:tl,swatch:["#0E0E10","#FAFAFA","#52525B","#A1A1AA","#6366F1","#E4E4E7"]},{id:"vercel",label:"Vercel",tagline:"Bold tech / dev-tool — sharp, confident",icon:rT,swatch:["#000000","#FFFFFF","#0070F3","#FF0080","#7928CA","#171717"]}
5656,{id:"stripe",label:"Stripe",tagline:"Corporate fintech — professional, gradient",icon:F$,swatch:["#0A2540","#635BFF","#00D4FF","#FFFFFF","#425466","#F6F9FC"]},{id:"apple",label:"Apple",tagline:"Premium minimal — heroic typography",icon:R$,swatch:["#F5F5F7","#1D1D1F","#0066CC","#FFFFFF","#86868B","#E8E8ED"]},{id:"editorial",label:"Editorial",tagline:"Magazine / longform — warm, asymmetric",icon:Wg,swatch:["#FAF6EF","#1F1B16","#BF7344","#688857","#A8A29E","#FCF7F0"]},{id:"brutalist",label:"Brutalist",tagline:"Raw, bold, anti-design — chunky borders",icon:M$,swatch:["#FFFFFF","#000000","#FCEE0A","#FF4F8B","#FF6B00","#000000"]},{id:"glassmorphic",label:"Glassmorphic",tagline:"Apple-Vision aurora — frosted glass + vibrant gradients",icon:H$,swatch:["#A78BFA","#60A5FA","#F472B6","#FACC15","#FFFFFF80","#1E1B4B"]},{id:"playful",label:"Y2K Playful",tagline:"Consumer / kids / lifestyle — bright, rounded",icon:u6,swatch:["#FFB3BA","#BAFFC9","#BAE1FF","#FFFFBA","#FFC8A2","#E0BBE4"]}];function _J(e){return e.id==="auto"?"Design":e.label}function TJ({value:e,onChange:t,isBuilding:r}){const[n,s]=m.useState(!1),i=m.useRef(null),[o,l]=m.useState(null),c=Qy.find(p=>p.id===e)||Qy[0],u=c.id==="auto"?Ai:c.icon;m.useEffect(()=>{if(!n||!i.current)return;const p=()=>{const h=i.current.getBoundingClientRect(),f=Math.min(384,window.innerWidth-16),x=Math.min(Math.max(8,h.left),window.innerWidth-f-8);l({top:h.top-8,left:x,width:f})};return p(),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[n]);const d=n&&o?bw.createPortal(a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[200]",onClick:()=>s(!1)}),a.jsxs("div",{className:"fixed z-[201] bg-card border rounded-xl shadow-xl overflow-hidden",style:{top:o.top,left:o.left,width:o.width,transform:"translateY(-100%)"},role:"menu",children:[a.jsx("div",{className:"px-3 py-2 border-b",children:a.jsx("span",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Design aesthetic"})}),a.jsx("div",{className:"py-1 max-h-[min(30rem,calc(100vh-12rem))] overflow-y-auto",children:Qy.map(p=>{const h=p.id===e,f=p.icon;return a.jsx("button",{type:"button",onClick:()=>{t(p.id),s(!1)},role:"menuitemradio","aria-checked":h,className:L("w-full text-left px-3 py-2.5 transition-colors",h?"bg-primary/5":"hover:bg-secondary/50"),children:a.jsxs("div",{className:"flex items-start gap-2.5",children:[a.jsx("div",{className:L("shrink-0 w-7 h-7 rounded-lg flex items-center justify-center",h?"bg-primary/15 text-primary":"bg-muted text-foreground"),children:a.jsx(f,{className:"w-3.5 h-3.5"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:L("text-sm font-semibold",h&&"text-primary"),children:p.label}),h&&a.jsx("span",{className:"text-[8px] bg-primary/10 text-primary px-1.5 py-0.5 rounded-full font-medium",children:"Active"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5 leading-snug",children:p.tagline}),a.jsx("div",{className:"flex gap-1 mt-1.5",children:p.swatch.map((x,g)=>a.jsx("div",{className:"w-3.5 h-3.5 rounded-full border border-black/10",style:{background:x}},g))})]})]})},p.id)})}),a.jsx("div",{className:"px-3 py-2 border-t bg-secondary/30",children:a.jsxs("p",{className:"text-[9px] text-muted-foreground",children:[a.jsx(Dn,{className:"w-3 h-3 inline mr-1 -mt-0.5"}),a.jsx("strong",{children:"Auto"})," uses the LLM intent classifier to pick a fitting aesthetic per domain. Override here to lock the look."]})})]})]}),document.body):null;return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{ref:i,type:"button",onClick:()=>s(p=>!p),disabled:r,"aria-expanded":n,"aria-haspopup":"menu",className:L("flex items-center gap-1.5 px-2 py-1 rounded-lg text-[11px] font-medium transition-all border","hover:bg-secondary/80",n?"bg-secondary border-primary/20":"bg-transparent border-transparent",r&&"opacity-50 cursor-not-allowed"),title:`Design aesthetic: ${c.label} — ${c.tagline}`,children:[a.jsx(u,{className:"w-3.5 h-3.5 shrink-0 text-foreground"}),a.jsx("span",{className:"hidden min-[420px]:inline text-foreground",children:_J(c)}),a.jsx(Yr,{className:L("w-3 h-3 text-muted-foreground transition-transform",n&&"rotate-180")}
5656)]}),d]})}const S2={starter:"Starter",pro:"Pro",studio:"Studio"};function EJ({className:e}){const{balance:t,plan:r,isLow:n,isOut:s,loading:i}=ld();if(i&&!r)return null;const o=s?"bg-rose-500/10 text-rose-700 border-rose-500/30":n?"bg-amber-500/10 text-amber-700 border-amber-500/30":"bg-primary/10 text-primary border-primary/20";return a.jsxs(Xf,{to:pp.BILLING,className:L("inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[11px] font-semibold border transition-all hover:opacity-90",o,e),title:`${t} credits remaining${r?` on ${S2[r]||r} plan`:""} — click to manage`,children:[a.jsx(hr,{className:L("w-3 h-3",s&&"animate-pulse")}),a.jsx("span",{className:"tabular-nums",children:t.toLocaleString()}),r&&a.jsx("span",{className:"text-[9px] uppercase tracking-wider opacity-70",children:S2[r]||r})]})}function IJ(){const{balance:e,plan:t,isLow:r,isOut:n,noPlan:s}=ld(),{project:i}=gn(),o=i&&i.isOwner===!1;return o&&s&&!r&&!n||!s&&!r&&!n?null:s&&!o?a.jsxs("div",{className:"px-3 py-2.5 border-t bg-rose-500/8 flex items-center gap-3 text-xs",children:[a.jsx(Ar,{className:"w-4 h-4 text-rose-600 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-rose-800 font-medium",children:"Credits required"}),a.jsx("p",{className:"text-rose-700/80 text-[11px] leading-snug",children:"Pick a plan or top up credits to use the studio."})]}),a.jsx(Q,{asChild:!0,size:"sm",className:"h-7 gap-1.5 text-[11px] bg-rose-600 hover:bg-rose-700",children:a.jsxs(Xf,{to:pp.BILLING,children:[a.jsx(rT,{className:"w-3 h-3"}),"See plans"]})})]}):n?a.jsxs("div",{className:"px-3 py-2.5 border-t bg-rose-500/8 flex items-center gap-3 text-xs",children:[a.jsx(Ar,{className:"w-4 h-4 text-rose-600 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-rose-800 font-medium",children:"Out of credits"}),a.jsxs("p",{className:"text-rose-700/80 text-[11px] leading-snug",children:["You need at least ",Ts," credits to start a build. Top up or upgrade to keep building."]})]}),a.jsx(Q,{asChild:!0,size:"sm",className:"h-7 gap-1.5 text-[11px] bg-rose-600 hover:bg-rose-700",children:a.jsx(Xf,{to:pp.BILLING,children:"Top up"})})]}):r?a.jsxs("div",{className:"px-3 py-2 border-t bg-amber-500/8 flex items-center gap-3 text-xs",children:[a.jsx(Lr,{className:"w-3.5 h-3.5 text-amber-600 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("p",{className:"text-amber-900 font-medium",children:["Running low — ",e," credit",e===1?"":"s"," left"]}),a.jsx("p",{className:"text-amber-800/80 text-[11px] leading-snug",children:"Builds cost 1–30 credits depending on complexity."})]}),a.jsx(Q,{asChild:!0,size:"sm",variant:"outline",className:"h-7 gap-1.5 text-[11px] border-amber-400 text-amber-900",children:a.jsx(Xf,{to:pp.BILLING,children:"Top up"})})]}):null}function Ih(){const e=il(),t=e==null?void 0:e.project,r=(t==null?void 0:t.currentUserRole)??null;return{canEdit:r==="owner"||r==="editor",isOwner:r==="owner",role:r,isCollaborator:r==="editor"||r==="viewer"}}function OJ({className:e=""}){const{role:t}=Ih();return t!=="viewer"?null:a.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 border-b bg-amber-50/60 dark:bg-amber-950/30 text-[12px] ${e}`,children:[a.jsx(ys,{className:"w-3.5 h-3.5 text-amber-600 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"font-semibold text-amber-700 dark:text-amber-400",children:"View-only access"}),a.jsx("span",{className:"text-muted-foreground ml-1.5",children:"— you can read this project but not edit. Ask the owner to upgrade your role to editor."})]})]})}var hx="Popover",[BI,_ve]=sl(hx,[qg]),Oh=qg(),[RJ,dl]=BI(hx),UI=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:s,onOpenChange:i,modal:o=!1}=e,l=Oh(t),c=m.useRef(null),[u,d]=m.useState(!1),[p,h]=ac({prop:n,defaultProp:s??!1,onChange:i,caller:hx});return a.jsx(F_,{...l,children:a.jsx(RJ,{scope:t,contentId:io(),triggerRef:c,open:p,onOpenChange:h,onOpenToggle:m.useCallback(()=>h(f=>!f),[h]),hasCustomAnchor:u,onCustomAnchorAdd:m.useCallback(()=>d(!0),[]),onCustomAnchorRemove:m.useCallback(()=>d(!1),[]),modal:o,children:r})})};UI.displayName=hx;var zI="PopoverAnchor",DJ=m.forwardRef((e,t)=>
vendor: 2,861 bytes, line 5656
5656{const{__scopePopover:r,...n}=e,s=dl(zI,r),i=Oh(r),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=s;return m.useEffect(()=>(o(),()=>l()),[o,l]),a.jsx(hw,{...i,...n,ref:t})});DJ.displayName=zI;var qI="PopoverTrigger",HI=m.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=dl(qI,r),i=Oh(r),o=Tr(t,s.triggerRef),l=a.jsx(En.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":YI(s.open),...n,ref:o,onClick:vn(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?l:a.jsx(hw,{asChild:!0,...i,children:l})});HI.displayName=qI;var F1="PopoverPortal",[MJ,LJ]=BI(F1,{forceMount:void 0}),WI=e=>{const{__scopePopover:t,forceMount:r,children:n,container:s}=e,i=dl(F1,t);return a.jsx(MJ,{scope:t,forceMount:r,children:a.jsx(Fa,{present:r||i.open,children:a.jsx(dw,{asChild:!0,container:s,children:n})})})};WI.displayName=F1;var Au="PopoverContent",VI=m.forwardRef((e,t)=>{const r=LJ(Au,e.__scopePopover),{forceMount:n=r.forceMount,...s}=e,i=dl(Au,e.__scopePopover);return a.jsx(Fa,{present:n||i.open,children:i.modal?a.jsx(FJ,{...s,ref:t}):a.jsx(BJ,{...s,ref:t})})});VI.displayName=Au;var $J=pw("PopoverContent.RemoveScroll"),FJ=m.forwardRef((e,t)=>{const r=dl(Au,e.__scopePopover),n=m.useRef(null),s=Tr(t,n),i=m.useRef(!1);return m.useEffect(()=>{const o=n.current;if(o)return gw(o)},[]),a.jsx(mw,{as:$J,allowPinchZoom:!0,children:a.jsx(GI,{...e,ref:s,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:vn(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),i.current||(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:vn(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:vn(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),BJ=m.forwardRef((e,t)=>{const r=dl(Au,e.__scopePopover),n=m.useRef(!1),s=m.useRef(!1);return a.jsx(GI,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,i),i.defaultPrevented||(n.current||(l=r.triggerRef.current)==null||l.focus(),i.preventDefault()),n.current=!1,s.current=!1},onInteractOutside:i=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const o=i.target;((u=r.triggerRef.current)==null?void 0:u.contains(o))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),GI=m.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onInteractOutside:d,...p}=e,h=dl(Au,r),f=Oh(r);return xw(),a.jsx(yw,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:s,onUnmountAutoFocus:i,children:a.jsx(u
5656w,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:d,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:u,onDismiss:()=>h.onOpenChange(!1),children:a.jsx(L_,{"data-state":YI(h.open),role:"dialog",id:h.contentId,...f,...p,ref:t,style:{...p.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)"}})})})}),KI="PopoverClose",UJ=m.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=dl(KI,r);return a.jsx(En.button,{type:"button",...n,ref:t,onClick:vn(e.onClick,()=>s.onOpenChange(!1))})});UJ.displayName=KI;var zJ="PopoverArrow",qJ=m.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,s=Oh(r);return a.jsx($_,{...s,...n,ref:t})});qJ.displayName=zJ;function YI(e){return e?"open":"closed"}var HJ=UI,WJ=HI,VJ=WI,JI=VI;const B1=HJ,U1=WJ,fx=m.forwardRef(({className:e,align:t="center",sideOffset:r=4,...n},s)=>a.jsx(VJ,{children:a.jsx(JI,{ref:s,align:t,sideOffset:r,className:L("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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",e),...n})}));fx.displayName=JI.displayName;function GJ({onAttach:e,onReference:t,onConnectors:r,disabled:n}){const[s,i]=m.useState(!1),[o,l]=m.useState(""),c=[{id:"attach",icon:ym,label:"Attach",description:"Use PPTX, DOCX, XLSX, images, or data",onSelect:e},{id:"reference",icon:Yo,label:"Reference",description:"Mirror a website's design",onSelect:t},{id:"connectors",icon:Ma,label:"Connectors",description:"Stripe, Resend, Twilio, and more",onSelect:r}],u=o.trim()?c.filter(p=>p.label.toLowerCase().includes(o.toLowerCase())||p.description.toLowerCase().includes(o.toLowerCase())):c,d=p=>{i(!1),l(""),p.onSelect()};return a.jsxs(B1,{open:s,onOpenChange:i,children:[a.jsx(U1,{asChild:!0,children:a.jsx("button",{type:"button",disabled:n,className:L("h-8 w-8 rounded-lg flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors",n&&"opacity-50 cursor-not-allowed"),title:"Add to message","aria-label":"Add to message",children:a.jsx(Kr,{className:"w-4 h-4"})})}),a.jsxs(fx,{side:"top",align:"start",sideOffset:8,className:"w-72 p-0 overflow-hidden",children:[a.jsx("div",{className:"px-3 py-2 border-b",children:a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[a.jsx(ja,{className:"w-3.5 h-3.5"}),a.jsx("input",{autoFocus:!0,value:o,onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&u[0]&&d(u[0]),p.key==="Escape"&&i(!1)},placeholder:"Search actions…",className:"flex-1 bg-transparent text-xs placeholder:text-muted-foreground focus:outline-none"})]})}),a.jsxs("ul",{className:"py-1 max-h-72 overflow-y-auto",children:[u.length===0&&a.jsx("li",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:"No matches"}),u.map(p=>{const h=p.icon;return a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>d(p),className:"w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-secondary/60 transition-colors",children:[a.jsx("div",{className:"w-7 h-7 rounded-md bg-primary/8 flex items-center justify-center shrink-0",children:a.jsx(h,{className:"w-3.5 h-3.5 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[12.5px] font-medium text-foreground",children:p.label}),a.jsx("p",{className:"text-[10.5px] text-muted-foreground truncate",children:p.description})]})]})},p.id)})]})]})]})}const lo=[{id:"page-gen",name:"Page Generator",category:"code",icon:"📄",description:"Generates complete HTML/React pages from prompts",color:"bg-blue-500/15 text-blue-600 border-blue-500/20",action:{type:"prompt",prompt:"Generate a new page with",toast:"Page Generator ready — describe your page"}},{id:"component-gen",name:"Component Builder",category:"code",icon:"🧩",description:"Creates reusable UI components with props and variants",color:"bg-blue-500/15 text-blue-600 border-blue-500/20",action:{type:"prompt",prompt:"Create a reusable component for",toast:"Component Builder ready — describe your component"}},{id:"scaffold",name:"App Scaffolder",category:"code",icon:"🏗️",description:"Scaffolds full application structure with routing and layout",color:"bg-blue-500/15 text-blue-600 border-blue-500/20",action:{type:"prompt",prompt:"Scaffold a full application for",toast:"App Scaffolder ready — describe your app"}},{id:"auth-gen",name:"Auth Generator",category:"code",icon:"🔐",description:"Generates authentication flows (login, signup, password reset)",color:"bg-blue-500/15 text-blue-600 border-blue-500/20",action:{type:"prompt",prompt:"Add authentication with login, signup, and password reset",toast:"Auth Generator activated"}},{id:"api-gen",name:"API Generator",category:"code",icon:"🔌",description:"Generates REST API routes and endpoint definitions",color:"bg-blue-500/15 text-blue-600 border-blue-500/20",action:{type:"navigate",tab:"api",toast:"Opening API tab"}},{id:"schema-builder",name:"Schema Builder",category:"database",icon:"🗂️",description:"Designs and creates database table schemas from requirements",color:"bg-emerald-500/15 text-emerald-600 border-emerald-500/20",workflowNodeType:"save_lead",action:{type:"navigate",tab:"schema",toast:"Opening Schema Builder"}},{id:"migration-runner",name:"Migration Runner",category:"database",icon:"🔄",de
5656scription:"Executes database migrations and schema changes",color:"bg-emerald-500/15 text-emerald-600 border-emerald-500/20",action:{type:"prompt",prompt:"Run database migration to",toast:"Migration Runner ready"}},{id:"seed-gen",name:"Seed Generator",category:"database",icon:"🌱",description:"Creates realistic sample data for tables",color:"bg-emerald-500/15 text-emerald-600 border-emerald-500/20",action:{type:"prompt",prompt:"Generate seed data for my database tables",toast:"Seed Generator activated"}},{id:"query-optimizer",name:"Query Optimizer",category:"database",icon:"⚡",description:"Analyzes and optimizes SQL queries for performance",color:"bg-emerald-500/15 text-emerald-600 border-emerald-500/20",action:{type:"navigate",tab:"query",toast:"Opening Query Runner"}},{id:"introspect",name:"DB Introspector",category:"database",icon:"🔍",description:"Reads and maps existing database schemas",color:"bg-emerald-500/15 text-emerald-600 border-emerald-500/20",action:{type:"navigate",tab:"diagram",toast:"Opening Schema Diagram"}},{id:"theme-gen",name:"Theme Generator",category:"design",icon:"🎨",description:"Generates color palettes, typography, and design tokens",color:"bg-purple-500/15 text-purple-600 border-purple-500/20",action:{type:"prompt",prompt:"Generate a custom theme with colors and typography for",toast:"Theme Generator ready"}},{id:"responsive-check",name:"Responsive Checker",category:"design",icon:"📱",description:"Validates and fixes responsive breakpoints across devices",color:"bg-purple-500/15 text-purple-600 border-purple-500/20",action:{type:"prompt",prompt:"Check and fix responsive design for mobile and tablet",toast:"Responsive Checker activated"}},{id:"a11y-audit",name:"Accessibility Auditor",category:"design",icon:"♿",description:"Checks color contrast, ARIA labels, and keyboard navigation",color:"bg-purple-500/15 text-purple-600 border-purple-500/20",action:{type:"prompt",prompt:"Run accessibility audit and fix ARIA labels, contrast, and keyboard nav",toast:"Accessibility Auditor activated"}},{id:"layout-engine",name:"Layout Engine",category:"design",icon:"📐",description:"Builds complex grid and flexbox layouts from descriptions",color:"bg-purple-500/15 text-purple-600 border-purple-500/20",action:{type:"prompt",prompt:"Create a responsive layout with",toast:"Layout Engine ready"}},{id:"deploy-helper",name:"Deploy Helper",category:"devops",icon:"🚀",description:"Prepares and deploys to Vercel, GitHub Pages, or custom hosts",color:"bg-amber-500/15 text-amber-600 border-amber-500/20",action:{type:"dialog",dialogId:"vercel-deploy",toast:"Opening Deploy dialog"}},{id:"edge-fn-gen",name:"Edge Function Generator",category:"devops",icon:"⚡",description:"Creates serverless edge functions for backend API logic",color:"bg-amber-500/15 text-amber-600 border-amber-500/20",action:{type:"prompt",prompt:"Create an edge function for",toast:"Edge Function Generator ready"}},{id:"env-config",name:"Env Configurator",category:"devops",icon:"⚙️",description:"Manages environment variables and configuration files",color:"bg-amber-500/15 text-amber-600 border-amber-500/20",action:{type:"prompt",prompt:"Configure environment variables for",toast:"Env Configurator ready"}},{id:"github-push",name:"GitHub Pusher",category:"devops",icon:"📤",description:"Pushes generated code to GitHub repositories",color:"bg-amber-500/15 text-amber-600 border-amber-500/20",action:{type:"navigate",tab:"github",toast:"Opening GitHub"}},{id:"domain-config",name:"Domain Manager",category:"devops",icon:"🌐",description:"Configures custom domains and DNS settings",color:"bg-amber-500/15 text-amber-600 border-amber-500/20",action:{type:"prompt",prompt:"Configure custom domain for my project",toast:"Domain Manager ready"}},{id:"supabase-connect",name:"Supabase Connector",category:"integration",icon:"🔗",description:"Connects to Supabase for auth, storage, and real-time data",color:"bg-rose-500/15 text-rose-600 border-rose-500/20",action:{type:"navigate",tab:"autodb",toast:"Opening Auto DB"}},{id:"mcp-bridge",name:"MCP Bridge",category:"integration",icon:"🤖",description:"Connects external MCP servers for tool discovery",color:"bg-rose-500/15 text-rose-600 border-rose-500/20",action:{type:"navigate",tab:"mcp",toast:"Opening MCP Panel"}},{id:"rest-proxy",name:"REST Proxy",category:"integration",icon:"🔀",description:"Routes API calls through the universal REST gateway",color:"bg-rose-500/15 text-rose-600 border-rose-500/20",workflowNodeType:"api_call",action:{type:"navigate",tab:"api",toast:"Opening API tab"}},{id:"webhook-gen",name:"Webhook Generator",category:"integration",icon:"📡",description:"Creates webhook endpoints and event handlers",color:"bg-rose-500/15 text-rose-600 border-rose-500/20",workflowNodeType:"webhook",action:{type:"prompt",prompt:"Create a webhook endpoint for",toast:"Webhook Generator ready"}},{id:"sdk-gen",name:"SDK Generator",category:"integration",icon:"📦",description:"Generates client SDKs for Fetch, Axios, or Supabase JS",color:"bg-rose-500/15 text-rose-600 border-rose-500/20",action:{type:"navigate",tab:"api",toast:"Opening SDK Generator"}},{id:"connector-slack",name:"Slack Connector",category:"connector",icon:"💬",description:"Send messages and interact with Slack workspaces",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",workflowNodeType:"send_message",action:{type:"prompt",prompt:"Integrate Slack messaging to send notifications when",toast:"Slack Connector ready"}},{id:"connector-twilio",name:"Twilio Connector",category:"connector",icon:"📞",description:"Send SMS, voice calls, and WhatsApp messages",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",workflowNodeType:"send_message",action:{type:"prompt",prompt:"Add Twilio SMS notifications for",toast:"Twilio Connector ready"}},{id:"connector-stripe",name:"Stripe Connector",category:"connector",icon:"💳",description:"Process payments, subscriptions, and invoices",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",action:{type:"prompt",prompt:"Add Stripe payment processing with checkout for",toast:"Str
5656ipe Connector ready"}},{id:"connector-email",name:"Email Connector",category:"connector",icon:"📧",description:"Send transactional and marketing emails",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",workflowNodeType:"send_email",action:{type:"prompt",prompt:"Set up email notifications for",toast:"Email Connector ready"}},{id:"connector-telegram",name:"Telegram Connector",category:"connector",icon:"✈️",description:"Send messages via Telegram Bot API",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",workflowNodeType:"send_message",action:{type:"prompt",prompt:"Add Telegram bot messaging for",toast:"Telegram Connector ready"}},{id:"connector-firecrawl",name:"Firecrawl Connector",category:"connector",icon:"🕷️",description:"AI-powered web scraping and data extraction",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",action:{type:"prompt",prompt:"Scrape and extract data from website",toast:"Firecrawl Connector ready"}},{id:"connector-elevenlabs",name:"ElevenLabs Connector",category:"connector",icon:"🔊",description:"AI voice generation and text-to-speech",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",action:{type:"prompt",prompt:"Add text-to-speech voice generation for",toast:"ElevenLabs Connector ready"}},{id:"connector-perplexity",name:"Perplexity Connector",category:"connector",icon:"🧠",description:"AI-powered search and answer engine",color:"bg-sky-500/15 text-sky-600 border-sky-500/20",workflowNodeType:"knowledge_search",action:{type:"prompt",prompt:"Add AI-powered search using Perplexity for",toast:"Perplexity Connector ready"}}],KJ=[{id:"code",label:"Code Generation",icon:"💻"},{id:"database",label:"Database",icon:"🗄️"},{id:"design",label:"Design",icon:"🎨"},{id:"devops",label:"DevOps",icon:"🚀"},{id:"integration",label:"Integration",icon:"🔗"},{id:"connector",label:"Connectors",icon:"🔌"}];function P0(e){return lo.find(t=>t.id===e)}function A0(e){return lo.filter(t=>t.category===e)}function YJ(){return lo.filter(e=>e.workflowNodeType)}function JJ(e){return lo.filter(t=>t.workflowNodeType===e)}function XJ(e){const t=e.toLowerCase(),r=new Set,n={"page-gen":["page","landing","homepage","website"],"component-gen":["component","widget","card","button","modal"],scaffold:["full app","application","complete app","build me"],"auth-gen":["login","signup","auth","register","password"],"api-gen":["api","endpoint","rest","crud"],"schema-builder":["database","table","schema","data model"],"seed-gen":["seed","sample data","mock data","test data"],"theme-gen":["theme","colors","branding","palette","dark mode"],"responsive-check":["responsive","mobile","tablet"],"edge-fn-gen":["edge function","serverless","backend function","webhook handler"],"deploy-helper":["deploy","publish","host"],"github-push":["github","push","repository","git"],"connector-slack":["slack","slack message"],"connector-twilio":["sms","twilio","phone","whatsapp"],"connector-stripe":["payment","stripe","checkout","subscription"],"connector-email":["email","send email","newsletter"],"connector-telegram":["telegram","telegram bot"],"connector-firecrawl":["scrape","crawl","extract data from website"],"connector-elevenlabs":["voice","text to speech","tts"],"connector-perplexity":["search","perplexity","ai search"],"supabase-connect":["supabase","database connection"],"mcp-bridge":["mcp","model context protocol"],"rest-proxy":["rest proxy","api proxy","data fetch"],"webhook-gen":["webhook","callback url"],"sdk-gen":["sdk","client library"]};for(const[s,i]of Object.entries(n))i.some(o=>t.includes(o))&&r.add(s);return Array.from(r)}function _0(e,t){const r=new Set;return(e.includes("```html")||e.includes("```htm"))&&r.add("page-gen"),(e.includes("```tsx")||e.includes("```jsx"))&&r.add("component-gen"),(e.match(/```(html|htm|tsx|jsx|css)/g)||[]).length>=4&&r.add("scaffold"),(e.toLowerCase().includes("login")||e.toLowerCase().includes("signup")||e.toLowerCase().includes("auth"))&&r.add("auth-gen"),(e.includes("routes.ts")||e.includes("api/")||e.includes("endpoint"))&&r.add("api-gen"),(e.includes("CREATE TABLE")||e.includes("schema.sql")||e.includes("```sql"))&&r.add("schema-builder"),t.some(n=>n.id.startsWith("db-create"))&&r.add("migration-runner"),t.some(n=>n.id==="db-seed")&&r.add("seed-gen"),(e.includes("introspect")||e.includes("cached_schema"))&&r.add("introspect"),(e.includes("--primary")||e.includes("theme")||e.includes("color-scheme")||e.includes("palette"))&&r.add("theme-gen"),(e.includes("responsive")||e.includes("@media")||e.includes("md:")||e.includes("lg:"))&&r.add("responsive-check"),(e.includes("aria-")||e.includes("role=")||e.includes("alt="))&&r.add("a11y-audit"),(e.includes("grid")||e.includes("flex")||e.includes("layout"))&&r.add("layout-engine"),t.some(n=>n.title.toLowerCase().includes("deploy"))&&r.add("deploy-helper"),(e.includes("edge function")||e.includes("edge-function")||e.includes("Deno.serve")||e.includes("supabase/functions")||e.includes("```typescript supabase/functions"))&&r.add("edge-fn-gen"),(e.includes("github")||t.some(n=>n.title.toLowerCase().includes("github")))&&r.add("github-push"),(e.includes("supabase")||e.includes("createClient"))&&r.add("supabase-connect"),(e.includes("fetch(")||e.includes("autodb-rest")||e.includes("db-crud"))&&r.add("rest-proxy"),(e.includes("sdk")||e.includes("SDK"))&&r.add("sdk-gen"),e.toLowerCase().includes("slack")&&r.add("connector-slack"),(e.toLowerCase().includes("twilio")||e.toLowerCase().includes("sms"))&&r.add("connector-twilio"),(e.toLowerCase().includes("stripe")||e.toLowerCase().includes("payment"))&&r.add("connector-stripe"),(e.includes("send_email")||e.includes("sendgrid")||e.includes("email notification"))&&r.add("connector-email"),e.toLowerCase().includes("telegram")&&r.add("connector-telegram"),(e.toLowerCase().includes("firecrawl")||e.toLowerCase().includes("scrape"))&&r.add("connector-firecrawl"),(e.toLowerCase().includes("elevenlabs")||e.toLowerCase().includes("text-to-speech"))&&r.add("connector-elevenlabs"),e.toLowerCase().includes("perplexity")&&r.add("connector-perplexity"),Array.from(r)}function ZJ(e){const t=new Set;for(const r of e)lo.filter(s=>s.workflowNodeType===r).forEach(s=>t.add(s.id));return e.length>0&&t.add("rest-proxy"),Array.from(t)}function Rh(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1),i=m.useCallback(async()=>
5656{if(!e)return;s(!0);const{data:h}=await G.from("db_connections").select("*").eq("project_id",e).order("created_at",{ascending:!1});r(h||[]),s(!1)},[e]),o=m.useCallback(async h=>{if(!e)return null;const{data:f,error:x}=await G.from("db_connections").insert({project_id:e,name:h.name,db_type:h.db_type,host:h.host||null,port:h.port||null,database_name:h.database_name||null,username:h.username||null,password_encrypted:h.password||null,connection_string:h.connection_string||null,ssl:h.ssl||!1}).select().single();if(x)return console.error("Failed to save connection:",x),null;const g=f;return r(y=>[g,...y]),g},[e]),l=m.useCallback(async h=>{await G.from("db_connections").delete().eq("id",h),r(f=>f.filter(x=>x.id!==h))},[]),c=m.useCallback(async(h,f,x)=>{const{data:{session:g}}=await G.auth.getSession();if(!g)throw new Error("Not authenticated");const y=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/db-proxy",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g.access_token}`},body:JSON.stringify({action:h,connectionId:f,query:x})}),b=await y.json();if(!y.ok)throw new Error(b.error||"Proxy call failed");return b},[]),u=m.useCallback(async h=>c("test",h),[c]),d=m.useCallback(async h=>{const f=await c("introspect",h);return r(x=>x.map(g=>g.id===h?{...g,cached_schema:f,last_introspected_at:new Date().toISOString()}:g)),f},[c]),p=m.useCallback(async(h,f)=>c("query",h,f),[c]);return{connections:t,loading:n,loadConnections:i,addConnection:o,deleteConnection:l,testConnection:u,introspect:d,runQuery:p}}function z1(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1),i=m.useCallback(async()=>{if(!e)return;s(!0);const{data:d}=await G.from("mcp_connections").select("*").eq("project_id",e).order("created_at",{ascending:!1});r(d||[]),s(!1)},[e]);m.useEffect(()=>{e&&i()},[e,i]);const o=m.useCallback(async d=>{if(!e)return null;const{data:p,error:h}=await G.from("mcp_connections").insert({project_id:e,name:d.name,url:d.url,auth_type:d.auth_type,auth_token:d.auth_token||null}).select().single();if(h)return console.error("Failed to save MCP connection:",h),null;const f=p;return r(x=>[f,...x]),f},[e]),l=m.useCallback(async d=>{await G.from("mcp_connections").delete().eq("id",d),r(p=>p.filter(h=>h.id!==d))},[]),c=m.useCallback(async d=>{var p;try{const h={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};d.auth_type==="bearer"&&d.auth_token?h.Authorization=`Bearer ${d.auth_token}`:d.auth_type==="api-key"&&d.auth_token&&(h["X-API-Key"]=d.auth_token),await fetch(d.url,{method:"POST",headers:h,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"studio-matters",version:"1.0.0"}}})});const g=((p=(await(await fetch(d.url,{method:"POST",headers:h,body:JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list",params:{}})})).json()).result)==null?void 0:p.tools)||[];return await G.from("mcp_connections").update({cached_tools:g,last_connected_at:new Date().toISOString()}).eq("id",d.id),r(y=>y.map(b=>b.id===d.id?{...b,cached_tools:g,last_connected_at:new Date().toISOString()}:b)),g}catch(h){throw console.error("MCP tool discovery failed:",h),h}},[]),u=m.useCallback(async(d,p,h)=>{const f={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};d.auth_type==="bearer"&&d.auth_token?f.Authorization=`Bearer ${d.auth_token}`:d.auth_type==="api-key"&&d.auth_token&&(f["X-API-Key"]=d.auth_token);const g=await(await fetch(d.url,{method:"POST",headers:f,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:p,arguments:h}})})).json();if(g.error)throw new Error(g.error.message);return g.result},[]);return{connections:t,loading:n,loadConnections:i,addConnection:o,deleteConnection:l,discoverTools:c,callTool:u}}function mx(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1),i=m.useCallback(async g=>{if(!e)throw new Error("No project selected — please create or open a project first");const{data:{session:y}}=await G.auth.getSession();if(!y)throw new Error("Not authenticated — please sign in first");let b;try{b=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/auto-db",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y.access_token}`},body:JSON.stringify({...g,projectId:e})})}catch(N){const j=N instanceof Error?N.message:"Unknown network error";throw new Error(`Network error calling Auto DB: ${j}`)}const v=await b.text();let k={};try{k=v?JSON.parse(v):{}}
5656catch{throw new Error(`Auto DB returned invalid response (${b.status}): ${v.slice(0,200)}`)}if(!b.ok){const N=(k==null?void 0:k.error)||(k==null?void 0:k.message)||`Auto DB call failed (HTTP ${b.status})`;throw new Error(N)}return k},[e]),o=m.useCallback(async()=>{if(e){s(!0);try{const g=await i({action:"list_tables"});r(g.tables||[])}catch(g){console.error("Failed to load auto-db tables:",g),W.error(`Failed to load tables: ${(g==null?void 0:g.message)||"Unknown error"}`)}finally{s(!1)}}},[e,i]),l=m.useCallback(async g=>{const y=await i({action:"create_table",tableName:g.tableName,displayName:g.displayName||g.tableName,columns:g.columns});return await o(),y},[i,o]),c=m.useCallback(async g=>{const y=await i({action:"batch_create_tables",tables:g.map(b=>({tableName:b.tableName,displayName:b.displayName||b.tableName,columns:b.columns}))});return await o(),y},[i,o]),u=m.useCallback(async g=>{await i({action:"drop_table",tableName:g}),await o()},[i,o]),d=m.useCallback(async(g,y)=>{await i({action:"add_column",tableName:g,columns:y}),await o()},[i,o]),p=m.useCallback(async(g,y)=>i({action:"insert",tableName:g,record:y}),[i]),h=m.useCallback(async(g,y)=>i({action:"select",tableName:g,...y}),[i]),f=m.useCallback(async(g,y,b)=>i({action:"update",tableName:g,record:y,filters:b}),[i]),x=m.useCallback(async(g,y)=>i({action:"delete",tableName:g,filters:y}),[i]);return{tables:t,loading:n,loadTables:o,createTable:l,batchCreateTables:c,dropTable:u,addColumn:d,insertRow:p,selectRows:h,updateRows:f,deleteRows:x}}const T0=new Set(["the","a","an","and","or","for","of","in","on","at","to","with","from","that","which","who","when","where","why","how","this","these","those","is","are","was","were","be","been","being","will","would","should","could","has","have","had","do","does","did","me","my","i","we","our","us","you","your","they","their","them","it","its"]),QJ=[{name:"build_for",re:/\bbuild\s+(?:me\s+)?(?:a|an)?\s*([\w\s,.'&-]{3,80}?)\s+for\s+([\w\s.,'&-]{2,40})\b/i},{name:"build_that",re:/\bbuild\s+(?:me\s+)?(?:a|an)?\s*([\w\s,.'&-]{3,60}?)\s+that\b/i},{name:"build_plain",re:/\bbuild\s+(?:me\s+)?(?:a|an|the)?\s*([\w\s,.'&-]{3,60}?)(?:[.!?\n]|\s+(?:with|using|so|because|but|and then|then)|$)/i},{name:"make_create",re:/\b(?:make|create|generate|design)\s+(?:me\s+)?(?:a|an|the)?\s*([\w\s,.'&-]{3,60}?)(?:[.!?\n]|\s+(?:with|using|so|because|but|and then|then|that|for)|$)/i},{name:"want_need",re:/\bI\s+(?:want|need|would\s+like)\s+(?:a|an|the)?\s*([\w\s,.'&-]{3,60}?)(?:[.!?\n]|\s+(?:with|using|so|because|but|and then|then|that|for)|$)/i},{name:"noun_anchor",re:/\b(?:a|an|the)\s+([\w\s,.'&-]{3,40}?\s+(?:website|webapp|app|tool|dashboard|landing\s+page|page|portal|platform|deck|presentation|store|marketplace|admin|crm|saas))\b/i}];function eX(e){let t=e.trim().replace(/^['"`]|['"`]$/g,"").replace(/\s+/g," ").replace(/[.,;:]+$/,"");const r=t.split(" ");for(;r.length>1&&T0.has(r[0].toLowerCase());)r.shift();return t=r.join(" "),t.length>56&&(t=t.slice(0,53).replace(/\s+\S*$/,"")+"…"),t=t.split(" ").map((n,s)=>!n||n===n.toUpperCase()?n:s>0&&T0.has(n.toLowerCase())?n.toLowerCase():n[0].toUpperCase()+n.slice(1)).join(" "),t}function XI(e){if(!e)return null;const t=e.trim();if(t.length<6)return null;for(const{re:r}of QJ){const n=t.match(r);if(!n)continue;const s=n[1],i=n[2];if(!s||s.trim().length<3)continue;let o=i?`${s.trim()} for ${i.trim()}`:s.trim();if(o.split(/\s+/).filter(u=>!T0.has(u.toLowerCase())).length<1)continue;const c=eX(o);if(!(c.length<3))return c}return null}const C2={new:{label:"New",tone:"bg-primary/10 text-primary border-primary/30",Icon:Dn},edit:{label:"Edit",tone:"bg-blue-500/10 text-blue-600 border-blue-500/30 dark:text-blue-300",Icon:d6},fix:{label:"Fix",tone:"bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-300",Icon:al},refactor:{label:"Refactor",tone:"bg-violet-500/10 text-violet-700 border-violet-500/30 dark:text-violet-300",Icon:gT},phase:{label:"Phase",tone:"bg-emerald-500/10 text-emerald-700 border-emerald-500/30 dark:text-emerald-300",Icon:Dn},failed:{label:"Failed",tone:"bg-destructive/10 text-destructive border-destructive/30",Icon:is}};function tX(e){if(!e||e<=0)return null;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const r=Math.floor(t/60),n=t%60;return n>0?`${r}m ${n}s`:`${r}m`}function nX({title:e,outcome:t,kind:r="edit",fileCount:n,durationMs:s,onShowDetail
5656s:i,onOpenPreview:o}){const l=C2[r]||C2.edit,c=l.Icon,u=tX(s);return a.jsxs("div",{className:"rounded-xl border bg-background shadow-sm overflow-hidden",children:[a.jsxs("div",{className:"flex items-start gap-3 px-3.5 py-2.5",children:[a.jsx("div",{className:L("flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border",l.tone),children:a.jsx(c,{className:"h-4 w-4"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:L("inline-flex items-center rounded-full border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide",l.tone),children:l.label}),a.jsx("h4",{className:"text-sm font-semibold truncate flex-1 min-w-0",children:e})]}),t&&a.jsx("p",{className:"mt-1 text-xs text-muted-foreground leading-snug line-clamp-2",children:t}),a.jsxs("div",{className:"mt-1.5 flex items-center gap-3 text-[10px] text-muted-foreground/80",children:[typeof n=="number"&&n>0&&a.jsxs("span",{children:[n," file",n===1?"":"s"]}),u&&a.jsx("span",{children:u})]})]})]}),a.jsxs("div",{className:"flex items-stretch border-t divide-x",children:[a.jsxs("button",{type:"button",onClick:i,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",children:[a.jsx(gT,{className:"h-3.5 w-3.5"}),"Show details"]}),o&&a.jsxs("button",{type:"button",onClick:o,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors",children:[a.jsx(ys,{className:"h-3.5 w-3.5"}),"Preview"]})]})]})}function rX(e,t,r){if(r)return"failed";const n=(e||"").toLowerCase();return/\b(fix|repair|broken|error|bug|crash|fails?|fault)\b/.test(n)?"fix":/\b(refactor|reorganiz|restructur|
5656clean\s*up|split|rename|move)\b/.test(n)?"refactor":/\b(phase|next phase|continue|finish|complete|add\s+(?:billing|auth|database|db)|stripe)\b/.test(n)?"phase":/\b(build|create|make|generate|scaffold|new)\b/.test(n)&&t>=4?"new":"edit"}function sX({open:e,onClose:t}){const{planSteps:r,toolCallHistory:n,currentAgent:s,isBuilding:i,messages:o}=gn();m.useEffect(()=>{if(!e)return;function p(h){h.key==="Escape"&&t()}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,t]),m.useEffect(()=>{if(!e)return;const p=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=p}},[e]);const l=r.filter(p=>p.status==="done").length,c=r.filter(p=>p.status==="running").length,u=r.filter(p=>p.status==="error").length,d=[...o].reverse().find(p=>p.role==="user");return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:L("fixed inset-0 z-[70] bg-black/30 backdrop-blur-[1px] transition-opacity duration-200",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),onClick:t,"aria-hidden":!0}),a.jsxs("aside",{className:L("fixed right-0 top-0 bottom-0 z-[71] w-[480px] max-w-[95vw] bg-card border-l shadow-2xl flex flex-col transition-transform duration-200",e?"translate-x-0":"translate-x-full"),role:"dialog","aria-label":"Build details",children:[a.jsxs("header",{className:"flex items-center justify-between px-4 py-3 border-b",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(Dn,{className:"h-4 w-4 text-primary shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"text-sm font-semibold truncate",children:"Details"}),d&&a.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:["Re: ",d.content.slice(0,80),d.content.length>80?"…":""]})]})]}),a.jsx("button",{type:"button",onClick:t,className:"rounded-md p-1.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":"Close details",children:a.jsx(qn,{className:"h-4 w-4"})})]}),a.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b bg-muted/30 text-[11px] text-muted-foreground",children:[a.jsxs("span",{className:"inline-flex items-center gap-1",children:[a.jsx(mn,{className:"h-3 w-3 text-emerald-500"}),l," done"]}),c>0&&a.jsxs("span",{className:"inline-flex items-center gap-1",children:[a.jsx(ze,{className:"h-3 w-3 animate-spin text-primary"}),c," running"]}),u>0&&a.jsxs("span",{className:"inline-flex items-center gap-1 text-destructive",children:[a.jsx(is,{className:"h-3 w-3"}),u," error",u===1?"":"s"]}),s&&a.jsx("span",{className:"ml-auto text-[10px] uppercase tracking-wide opacity-70",children:s})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.length>0&&a.jsxs("section",{className:"px-4 py-3 border-b",children:[a.jsx("h3",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:"Plan steps"}),a.jsx("ol",{className:"space-y-1.5",children:r.map(p=>a.jsxs("li",{className:"flex items-start gap-2 text-xs",children:[p.status==="done"?a.jsx(mn,{className:"h-3.5 w-3.5 text-emerald-500 mt-0.5 shrink-0"}):p.status==="running"?a.jsx(ze,{className:"h-3.5 w-3.5 animate-spin text-primary mt-0.5 shrink-0"}):p.status==="error"?a.jsx(is,{className:"h-3.5 w-3.5 text-destructive mt-0.5 shrink-0"}):a.jsx("div",{className:"h-3.5 w-3.5 rounded-full border border-muted-foreground/30 mt-0.5 shrink-0"}),a.jsxs("span",{className:L("flex-1",p.status==="done"&&"text-muted-foreground line-through opacity-70",p.status==="error"&&"text-destructive"),children:[p.label,p.description&&a.jsx("span",{className:"block text-[10px] text-muted-foreground/80 mt-0.5",children:p.description})]})]},p.id))})]}),n.length>0&&a.jsxs("section",{className:"px-4 py-3 border-b",children:[a.jsxs("h3",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:["Tool activity (",n.length,")"]}),a.jsx("ol",{className:"space-y-1",children:n.map(p=>{const h=/\b(read|inspect|scan)\b/i.test(p.label)?ys:/\b(edit|write|update|patch)\b/i.test(p.label)?Vg:/\b(think|reason|plan)\b/i.test(p.label)?t6:al;return a.jsxs("li",{className:"flex items-start gap-2 text-[11px] font-mono",children:[a.jsx(h,{className:"h-3 w-3 mt-0.5 shrink-0 text-muted-foreground"}),a.jsx("span",{className:L("flex-1 truncate",p.status==="running"&&"text-primary"),children:p.label}),p.agent&&a.jsx("span",{className:"text-[9px] uppercase tracking-wide opacity-50",children:p.agent})]}
5656,p.id)})})]}),r.length===0&&n.length===0&&!i&&a.jsx("div",{className:"px-4 py-12 text-center text-xs text-muted-foreground",children:"No build activity recorded for the current session yet."})]})]})]})}const aX=["fix","bug","issue","error","broken","not working","cannot","can't","cant","unable","fails","failing","stopped","problem","wrong","retry","stuck","not possible","does not work","doesnt work","can not","not clickable"],iX=new Set(["the","and","for","with","that","this","from","into","when","then","than","have","has","had","still","same","need","want","page","screen","system","proper","please","small","issue","error","fix","build","make","again","look","like","does","doesnt","doesn","dont","not","working","work","click","clickable","possible","tab","button","why","how","can","you","also","what"]),oX=[{keywords:["ecommerce","e-commerce","shop","store","marketplace","product catalog"],blueprint:{category:"E-Commerce",pages:["Product Catalog","Product Detail","Shopping Cart","Checkout","Order History"],features:["Product search & filters","Cart management","Payment integration"]}},{keywords:["dashboard","admin","analytics","crm","management system","back office"],blueprint:{category:"Dashboard",pages:["Dashboard Overview","Data Tables","Analytics Charts","Settings"],features:["KPI widgets","Data visualization","User management"]}},{keywords:["social","feed","community","twitter","instagram","network"],blueprint:{category:"Social Platform",pages:["Feed","Profile","Explore","Messages","Notifications"],features:["Post creation","Follow system","Real-time updates"]}},{keywords:["blog","cms","content","magazine","news","publication"],blueprint:{category:"Content Platform",pages:["Article List","Article Detail","Category Browser","Author Page"],features:["Rich text content","Categories & tags","Search"]}},{keywords:["saas","landing","marketing","startup","launch","product page"],blueprint:{category:"SaaS Landing",pages:["Hero & Features","Pricing","About","Contact","Blog"],features:["CTA sections","Pricing tiers","Testimonials"]}},{keywords:["portfolio","resume","personal","freelance","agency"],blueprint:{category:"Portfolio",pages:["Home","Projects Gallery","Project Detail","About","Contact"],features:["Project showcase","Skill visualization","Contact form"]}},{keywords:["booking","appointment","reservation","scheduling","calendar"],blueprint:{category:"Booking System",pages:["Service Catalog","Booking Calendar","Booking Confirmation","My Bookings"],features:["Calendar integration","Availability slots","Confirmation emails"]}},{keywords:["restaurant","food","menu","cafe","dining","delivery"],blueprint:{category:"Restaurant",pages:["Menu","Order","Reservations","About","Contact"],features:["Menu categories","Online ordering","Table reservations"]}},{keywords:["tender","bid","procurement","rfp","proposal","contract"],blueprint:{category:"Tender Management",pages:["Dashboard","Tender Discovery","Bid Workspace","Submissions","Analytics"],features:["Tender tracking","Bid management","Document handling"]}},{keywords:["fitness","gym","workout","health","wellness","exercise"],blueprint:{category:"Fitness App",pages:["Dashboard","Workout Plans","Progress Tracker","Exercise Library","Profile"],features:["Workout logging","Progress charts","Exercise database"]}},{keywords:["real estate","property","listing","housing","rental"],blueprint:{category:"Real Estate",pages:["Property Listings","Property Detail","Map View","Favorites","Contact Agent"],features:["Property search","Map integration","Inquiry forms"]}},{keywords:["education","course","learning","lms","tutorial","school"],blueprint:{category:"Education Platform",pages:["Course Catalog","Course Detail","Lesson Viewer","Progress Dashboard","Profile"],features:["Course enrollment","Video lessons","Progress tracking"]}}];function ZI(e){const t=[],r=e.toLowerCase(),n=r.match(/with\s+([\w\s,]+(?:\s+and\s+[\w\s]+)?)\s+page/i);n&&n[1].replace(/\s+and\s+/g,", ").split(",").forEach(o=>{const l=o.trim();l.length>1&&l.length<40&&t.push(l.replace(/\b\w/g,c=>c.toUpperCase()))});const s=["home","dashboard","settings","profile","about","contact","pricing","features","blog","faq","help","search","login","signup","register","checkout","cart","orders","products","catalog","gallery","portfolio","projects","analytics","reports","notifications","messages","inbox","users","admin","overview","feed","explore","discover","calendar","schedule","booking","reservations","menu","landing","onboarding","wizard","integrations"];for(const i of s)r.includes(i)&&!t.some(o=>o.toLowerCase()===i)&&t.push(i.replace(/\b\w/g,o=>o.toUpperCase()));return t.slice(0,8)}function lX(e){const t=e.toLowerCase();return aX.some(r=>t.includes(r))}function cX(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function uX(e){const t=ZI(e);if(t.length>0)return t.slice(0,2).join(" + ");const r=e.match(/"([^"]+)"|'([^']+)'/),n=(r==null?void 0:r[1])||(r==null?void 0:r[2]);if(n)return n.trim();const s=e.toLowerCase().replace(/[^a-z0-9\s/-]/g," ").split(/\s+/).filter(i=>i.length>2&&!iX.has(i));return s.length===0?"reported area":cX(s.slice(0,4).join(" "))}function dX(e){const t=uX(e);return[{id:"smart-fix-diagnose",title:"Analyze reported issue",description:t==="reported area"?"Understand the failure and expected behavior":t,status:"pending"},{id:"smart-fix-locate",title:`Inspect ${t}`,description:"Read the affected page/component before changing code",status:"pending"}
5656,{id:"smart-fix-apply",title:"Apply targeted fix",description:"Change only the affected file(s) and preserve the rest",status:"pending"},{id:"smart-fix-verify",title:"Explain fix and test steps",description:"Summarize what changed, what page/file was touched, and how to test",status:"pending"}]}function QI(e,t){return t==="issue-fix"?"issue-fix":t&&t!=="issue-fix"?"build":lX(e)?"issue-fix":"build"}function pX(e){const t=[],r=e.toLowerCase(),n={"dark mode":"Dark mode toggle",authentication:"User authentication",auth:"User authentication",login:"User authentication","real-time":"Real-time updates",realtime:"Real-time updates",responsive:"Responsive design",mobile:"Mobile-first layout",animation:"Animations & transitions",search:"Search functionality",filter:"Filtering & sorting",payment:"Payment integration",stripe:"Stripe payments",upload:"File upload",notification:"Notifications system",chart:"Data visualization",graph:"Data visualization",map:"Map integration",email:"Email integration",api:"API integration",webhook:"Webhook handling",export:"Data export",import:"Data import",role:"Role-based access",permission:"Permissions system",i18n:"Internationalization",multilingual:"Multi-language support"};for(const[s,i]of Object.entries(n))r.includes(s)&&!t.includes(i)&&t.push(i);return t.slice(0,5)}function hX(e,t){if(QI(e,t)==="issue-fix")return dX(e);const r=[],n=e.toLowerCase();r.push({id:"smart-design",title:"Set up design system",description:"Colors, typography, and component tokens",status:"pending"});let s=null;for(const{keywords:f,blueprint:x}of oX)if(f.some(g=>n.includes(g))){s=x;break}const i=ZI(e),o=n.includes("sidebar")||n.includes("navigation")||n.includes("navbar");r.push({id:"smart-shell",title:o?"Build app shell with sidebar":"Build app shell & navigation",description:"Layout structure with routing",status:"pending"});const l=i.length>0?i:(s==null?void 0:s.pages)||[],c=l.slice(0,4),u=l.slice(4);for(const f of c)r.push({id:`smart-page-${f.toLowerCase().replace(/\s+/g,"-")}`,title:`Build ${f} page`,description:"",status:"pending"});u.length>0&&r.push({id:"smart-remaining",title:"Build remaining pages",description:`${u.join(", ")}`,status:"pending"});const d=pX(e),p=(s==null?void 0:s.features)||[],h=[...new Set([...d,...p])].slice(0,3);return h.length>0&&r.push({id:"smart-features",title:"Add core features",description:h.join(", "),status:"pending"}),l.length===0&&(r.push({id:"smart-core",title:"Build core pages",description:"Main application views",status:"pending"}),r.push({id:"smart-components",title:"Build UI components",description:"Reusable interface elements",status:"pending"})),r}function eO(e,t,r){const n=t.map(i=>i.toLowerCase()),s=n.length>0;return e.map((i,o)=>{if(i.status==="done"||i.status==="error")return i;if(i.id.startsWith("smart-fix-")){if(i.id==="smart-fix-diagnose")return s?{...i,status:"done"}:o===0&&r?{...i,status:"running"}:i;if(i.id==="smart-fix-locate")return s?{...i,status:"done"}:i;if(i.id==="smart-fix-apply")return!r&&s?{...i,status:"done"}:s&&r?{...i,status:"running"}:i;if(i.id==="smart-fix-verify")return!r&&s?{...i,status:"done"}:s&&r?{...i,status:"pending"}:i}if(i.id==="smart-design")return n.some(c=>c.includes("index.css")||c.includes("theme")||c.includes("tailwind")||c.includes("globals"))?{...i,status:"done"}:s?{...i,status:"done"}:o===0&&r?{...i,status:"running"}:i;if(i.id==="smart-shell")return n.some(c=>c.includes("layout")||c.includes("nav")||c.includes("sidebar")||c.includes("app.")||c.includes("shell"))?{...i,status:"done"}:n.length>=2?{...i,status:"done"}:n.length>=1&&r?{...i,status:"running"}:i;if(i.id.startsWith("smart-page-")){const l=i.id.replace("smart-page-","");return n.some(d=>{const p=d.split("/").pop()||d;return p.includes(l)||p.includes(l.replace(/-/g,""))})?{...i,status:"done"}:e.slice(0,o).every(d=>d.status==="done"||eO([d],t,r)[0].status==="done")&&r?{...i,status:"running"}:i}if(i.id==="smart-remaining"){const l=e.filter(c=>c.id.startsWith("smart-page-")).length;return n.length>l+3?{...i,status:r?"running":"done"}:i}return i.id==="smart-features"?!r&&s?{...i,status:"done"}:n.length>5&&r?{...i,status:"running"}:i:i.id==="smart-core"||i.id==="smart-components"?!r&&s?{...i,status:"done"}:n.length>3&&r?{...i,status:"running"}:i:i})}const fX=[/\b(fix|debug|repair|patch)\b/i,/\b(bug|issue|error|broken|crash)\b/i,/\b(not\s+working|doesn't\s+wor
5656k|doesnt\s+work|can't|cannot)\b/i,/\b(fails|failing|stopped|stuck|wrong)\b/i],mX=[/\b(calculator|converter|timer|stopwatch|counter)\b/i,/\b(generator|formatter|validator|checker|tester)\b/i,/\b(color\s*picker|json\s*viewer|regex\s*tester|markdown\s*editor)\b/i,/\b(unit\s*convert|currency\s*convert|date\s*calc)\b/i,/\b(qr\s*code|barcode|hash|encrypt|decode|encode)\b/i,/\b(password\s*gen|lorem\s*ipsum|uuid\s*gen|random)\b/i,/\b(pomodoro|todo\s*list|note\s*taking|kanban)\b/i,/\b(quiz|flashcard|poll|survey\s*form)\b/i,/\b(single.page\s+tool|utility|widget|mini.app)\b/i,/\bbuild\s+(?:a|an|me)\s+(?:simple\s+)?(calculator|timer|converter|generator|checker|picker)/i],gX=[/\b(api|rest\s*api|graphql|endpoint|webhook)\b.*\b(build|create|make|design)\b/i,/\b(build|create|make|design)\b.*\b(api|rest\s*api|graphql|endpoint|webhook)\b/i,/\b(backend|server|microservice|edge\s*function)\b/i,/\b(crud\s*api|data\s*api|proxy|middleware)\b/i,/\bapi[\s-]*(only|first|service)\b/i],xX=[/\b(login|signup|sign\s*up|auth|register|account)\b/i,/\b(database|db|table|schema|migration|crud)\b/i,/\b(user\s*management|role|permission|admin\s*panel)\b/i,/\b(dashboard|admin|analytics)\b.*\b(with|and)\b.*\b(auth|login|data)\b/i,/\b(saas|platform|system|portal|management)\b/i,/\b(real[\s-]*time|live\s*update|notification|chat\s*app)\b/i,/\b(payment|stripe|billing|subscription)\b/i,/\b(upload|file\s*storage|image\s*upload)\b/i,/\b(full[\s-]*stack|fullstack|backend\s*and\s*frontend)\b/i],yX=[/\b(landing\s*page|homepage|website|web\s*page|site)\b/i,/\b(portfolio|blog|news|magazine|gallery)\b/i,/\b(e[\s-]*commerce|shop|store|marketplace|product)\b/i,/\b(restaurant|menu|booking|reservation)\b/i,/\b(company|business|agency|startup)\s*(website|site|page)?\b/i,/\b(multi[\s-]*page|responsive\s*website|modern\s*website)\b/i];function q1(e){const t=e.match(/USER REQUEST:\s*([\s\S]*)$/i);return((t==null?void 0:t[1])||e).trim()}function Mm(e){if(/^BUILD TYPE:\s*FULL\s*STACK/i.test(e)||/^BUILD TYPE:\s*MOBILE/i.test(e))return!1;const t=q1(e),r=/https?:\/\/[^\s)]+/i.test(t),n=/\b(website|web\s*site|site|landing\s*page|homepage|marketing\
5656s*page|public\s*page)\b/i.test(t),s=/\b(like|similar\s+to|clone|inspired\s+by|reference)\b/i.test(t)&&r;return!/\b(full[\s-]*stack|backend|database|db|schema|auth|login|signup|sign\s*up|account|admin|dashboard|portal|crm|api|endpoint|webhook|stripe|payment|billing|subscription|real[\s-]*time|crud|marketplace|e[\s-]*commerce|analytics|booking|appointments|calendar|polls|social\s+app|saas)\b/i.test(t)&&(n||s)}const P2=8e3;async function bX(e,t=!1){if(!e||e.trim().length===0)return{...ap(e,t),source:"keyword"};try{let r=null;const{data:n,error:s}=await(async()=>{const l=G.functions.invoke("classify-intent",{body:{prompt:e,hasExistingFiles:t}}),c=new Promise((u,d)=>{r=setTimeout(()=>{d(new Error(`classify-intent timed out after ${P2}ms`))},P2)});try{return await Promise.race([l,c])}finally{r&&clearTimeout(r)}})();if(s||!(n!=null&&n.classification))return console.warn("[classify-intent] failed, falling back to keyword classifier:",(s==null?void 0:s.message)??"no classification in response"),{...ap(e,t),source:"keyword"};const i=n.classification;if(i.strategy==="conversational")return{...ap(e,t),source:"keyword"};const o={strategy:i.strategy,confidence:typeof i.confidence=="number"?i.confidence:.8,reason:i.reason||"LLM intent classification",suggestedPages:Array.isArray(i.suggestedPages)?i.suggestedPages:[],suggestedFeatures:Array.isArray(i.suggestedFeatures)?i.suggestedFeatures:[],needsDatabase:!!i.needsDatabase,needsAuth:!!i.needsAuth,needsApi:!!i.needsApi,needsRealtime:!!i.needsRealtime,needsFileStorage:!!i.needsFileStorage,needsBilling:!!i.needsBilling,domain:typeof i.domain=="string"?i.domain:void 0,integrations:Array.isArray(i.integrations)?i.integrations:[],aiSpecialists:Array.isArray(i.aiSpecialists)?i.aiSpecialists:[],aestheticHint:typeof i.aestheticHint=="string"?i.aestheticHint:void 0,targetPlatform:i.targetPlatform==="mobile"||i.targetPlatform==="both"?i.targetPlatform:"web",useTemplate:i.useTemplate==="saas-landing"?"saas-landing":i.useTemplate==="single-tool"?"single-tool":i.useTemplate==="dashboard-app"?"dashboard-app":"none",source:"llm"};return Mm(e)&&o.strategy!=="website"?{...o,strategy:"website",confidence:Math.max(o.confidence,.9),reason:"Website/reference URL request without explicit backend requirements",needsDatabase:!1,needsAuth:!1,needsApi:!1,needsRealtime:!1,needsFileStorage:!1,needsBilling:!1,suggestedPages:o.suggestedPages.length?o.suggestedPages:tO(q1(e)),suggestedFeatures:["Responsive design","Navigation","Reference-inspired search UI","SEO meta tags","Contact form"],useTemplate:o.useTemplate==="dashboard-app"?"none":o.useTemplate}:o}catch(r){return console.warn("[classify-intent] threw, falling back to keyword classifier:",r),{...ap(e,t),source:"keyword"}}}function Bd(e,t){let r=0;for(const n of t)n.test(e)&&r++;return r}function ap(e,t=!1){const r=e.toLowerCase().trim();if(!t&&/^BUILD TYPE:\s*LANDING/i.test(e))return{...Pl("website",.95,"HomePage landing build",r,t),useTemplate:"saas-landing"};if(!t&&/^BUILD TYPE:\s*WEBSITE/i.test(e))return{...Pl("website",.95,"HomePage website build",r,t),useTemplate:"saas-landing"};if(!t&&/^BUILD TYPE:\s*FULL\s*STACK/i.test(e))return{...Pl("fullstack",.95,"HomePage full-stack build",r,t),useTemplate:"dashboard-app"};if(!t&&/^BUILD TYPE:\s*MOBILE/i.test(e))return{...Pl("fullstack",.9,"HomePage mobile PWA build",r,t),targetPlatform:"mobile",useTemplate:"none"};if(Mm(e))return{...Pl("website",.9,"Website/reference URL request without explicit backend requirements",q1(e).toLowerCase(),t),needsDatabase:!1,needsAuth:!1,needsApi:!1,useTemplate:t?"none":"saas-landing"};if(t){const u=Bd(r,fX);if(u>=1)return{strategy:"issue-fix",confidence:Math.min(.5+u*.2,1),reason:"Detected fix/debug keywords with existing project",suggestedPages:[],suggestedFeatures:["Targeted code fix","Preserve existing functionality"],needsDatabase:!1,needsAuth:!1,needsApi:!1}}const n={tool:Bd(r,mX),"api-service":Bd(r,gX),fullstack:Bd(r,xX),website:Bd(r,yX)};n.fullstack>=2&&(n.fullstack+=1),n.tool>=1&&r.length<100&&(n.tool+=1);const s=Object.entries(n).sort((u,d)=>d[1]-u[1]),[i,o]=s[0],[,l]=s[1];if(o===0){const d=r.split(/\s+/).length>20?"fullstack":"website";return Pl(d,.4,"Default — no strong category signals",r,t)}const c=Math.min(.5+(o-l)*.15+o*.1,1);return Pl(i,c,`Matched ${o} ${i} pattern(s)`,r,t)}function Pl(e,t,r,n,s=!1){const i=/\b(log\s*in|login|sign\s*up|signup|sign\s*in|auth|register|registration|account|profile|user\s+table|admin)\b/i.test(n),o=i||/\b(database|db|table|crud|store|save|persist|data|supabase|postgres)\b/i.test(n),l=o||/\b(api|endpoint|backend|server|function)\b/i.test(n),c={website:tO(n),tool:["Tool Page"],fullstack:vX(n),"api-service":["API Documentation"],"issue-fix":[]},u={website:["Responsive design","Navigation","SEO meta tags","Contact form"],tool:["Single-page functionality","Input validation","Real-time output"],fullstack:[...i?["Authentication (login/signup)"]:[],...o?["Database schema & CRUD"]:[],...l?["API endpoints"]:[],"Dashboard UI"],"api-service":["REST endpoints","Edge functions","API documentation","Error handling"],"issue-fix":["Targeted fix","Preserve existing code"]};return{strategy:e,confidence:t,reason:r,suggestedPages:c[e],suggestedFeatures:u[e],needsDatabase:o,needsAuth:i,needsApi:l,useTemplate:s?"none":e==="website"?"saas-landing":e==="tool"?"single-tool":e==="fullstack"?"dashboard-app":"none"}}function tO(e){const t=["Home"];return/\b(about|company|team)\b/i.test(e)&&t.push("About"),/\b(contact|get\s*in\s*touch)\b/i.test(e)&&t.push("Contact"),/\b(blog|article|post|news)\b/i.test(e)&&t.push("Blog"),/\b(pricing|plan|tier)\b/i.test(e)&&t.push("Pricing"),/\b(product|shop|store|catalog)\b/i.test(e)&&t.push("Products","Product Detail","Cart"),/\b(gallery|portfolio|project|work)\b/i.test(e)&&t.push("Gallery"),/\b(service|feature)\b/i.test(e)&&t.push("Services"),/\b(faq|help)\b/i.test(e)&&t.push("FAQ"),/\b(testimonial|review)\b/i.test(e)&&t.push("Testimonials"),t.length<4&&t.push("About","Contact","Services"),[...new Set(t)]}function vX(e){const t=["Dashboard"];return/\b(login|auth|sign\s*in)\b/i.test(e)&&t.push("Login","Signup"),/\b(profile|account|setting)\b/i.test(e)&&t.push("Profile","Settings"),/\b(user|member|team|admin)\b/i.test(e)&&t.push("User Management"),/\b(analytic|report|chart|stat)\b/i.test(e)&&t.push("Analytics"),/\b(product|item|inventory)\b/i.test(e)&&t.push("Products"),/\b(order|transaction|history)\b/i.test(e)&&t.push("Orders"),/\b(message|chat|inbox|notification)\b/i.test(e)&&t.push("Messages"),t.length<4&&t.push("Settings","Profile"),[...new Set(t)]}function wX(){return[{id:"first-design",title:"Setting up design system",description:"Colors, typography, layout tokens",
5656status:"pending"},{id:"first-nav",title:"Building navigation",description:"Responsive navbar + footer",status:"pending"},{id:"first-home",title:"Creating homepage",description:"Hero section + content blocks",status:"pending"},{id:"first-wrap",title:"Wrapping up",description:"Routing, 404 page, final polish",status:"pending"}]}function A2(e){const{strategy:t,suggestedPages:r,suggestedFeatures:n}=e;switch(t){case"tool":return[{id:"smart-tool-design",title:"Design Tool UI",description:"Layout, inputs, and output areas",status:"pending"},{id:"smart-tool-logic",title:"Implement Logic",description:"Core functionality and calculations",status:"pending"},{id:"smart-tool-polish",title:"Polish & Validate",description:"Error handling, responsive design, edge cases",status:"pending"}];case"website":return[{id:"smart-design",title:"Design System",description:"Colors, typography, component tokens",status:"pending"},{id:"smart-nav",title:"Navigation & Layout",description:"Shared navbar, footer, routing",status:"pending"},...r.slice(0,5).map((s,i)=>({id:`smart-page-${i}`,title:`Build ${s}`,description:`Generate ${s} page with full content`,status:"pending"})),{id:"smart-responsive",title:"Responsive & Polish",description:"Mobile layout, transitions, final touches",status:"pending"}];case"fullstack":return[{id:"smart-schema",title:"Database Schema",description:"Tables, relationships, indexes",status:"pending"},...e.needsAuth?[{id:"smart-auth",title:"Authentication",description:"Login, signup, session management",status:"pending"}]:[],{id:"smart-api",title:"API Endpoints",description:`${n.filter(s=>s.includes("endpoint")||s.includes("CRUD")).length||3}+ edge functions`,status:"pending"},...r.slice(0,4).map((s,i)=>({id:`smart-page-${i}`,title:`Build ${s}`,description:`Generate ${s} with real API integration`,status:"pending"})),{id:"smart-deploy",title:"Deploy & Wire Up",description:"Deploy functions, run migrations",status:"pending"}];case"api-service":return[{id:"smart-schema",title:"Database Schema",description:"Tables, RLS policies, indexes",status:"pending"},{id:"smart-endpoints",title:"API Endpoints",description:"Edge functions with CRUD operations",status:"pending"},{id:"smart-auth-api",title:"Auth & Middleware",description:"JWT validation, CORS, rate limiting",status:"pending"},{id:"smart-docs",title:"API Documentation",description:"Interactive docs page with examples",status:"pending"},{id:"smart-deploy-api",title:"Deploy Functions",description:"Deploy to Supabase edge runtime",status:"pending"}];case"issue-fix":return[{id:"smart-fix-analyze",title:"Analyze Issue",description:"Identify root cause and affected files",status:"pending"},{id:"smart-fix-locate",title:"Locate Code",description:"Find the exact code that needs to change",status:"pending"},{id:"smart-fix-apply",title:"Apply Fix",description:"Modify only affected files",status:"pending"},{id:"smart-fix-verify",title:"Verify & Test",description:"Explain fix and provide test steps",status:"pending"}]}}const jX={"package.json":`{
5657  "name": "mobile-pwa-app",
5658  "private": true,
5659  "version": "0.0.0",
5660  "type": "module",
5661  "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" },
5662  "dependencies": {
5663    "react": "^18.3.1",
5664    "react-dom": "^18.3.1",
5665    "react-router-dom": "^6.26.2"
5666  },
5667  "devDependencies": {
5668    "@types/react": "^18.3.5",
5669    "@types/react-dom": "^18.3.0",
5670    "@vitejs/plugin-react": "^4.3.1",
5671    "autoprefixer": "^10.4.20",
5672    "postcss": "^8.4.41",
5673    "tailwindcss": "^3.4.10",
5674    "typescript": "^5.5.3",
5675    "vite": "^5.4.2"
5676  }
5677}
5678`,"vite.config.ts":`import { defineConfig } from 'vite';
5679import react from '@vitejs/plugin-react';
5680export default defineConfig({ plugins: [react()], server: { port: 5173 } });
5681`,"tsconfig.json":`{
5682  "compilerOptions": {
5683    "target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"], "module": "ESNext",
5684    "moduleResolution": "bundler", "jsx": "react-jsx", "strict": true,
5685    "skipLibCheck": true, "noEmit": true, "isolatedModules": true
5686  },
5687  "include": ["src"]
5688}
5689`,"tsconfig.node.json":`{
5690  "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true },
5691  "include": ["vite.config.ts"]
5692}
5693`,"tailwind.config.ts":`import type { Config } from 'tailwindcss';
5694export default { content: ['./index.html', './src/**/*.{ts,tsx}'], theme: { extend: {} }, plugins: [] } satisfies Config;
5695`,"postcss.config.js":`export default { plugins: { tailwindcss: {}, autoprefixer: {} } };
5696`,"index.html":`<!doctype html>
5697<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /><title>Mobile App</title></head>
5698<body><div id="root"></div><script type="module" src="/src/main.tsx"><\/script></body></html>
5699`,"src/vite-env.d.ts":`/// <reference types="vite/client" />
5700`,"src/index.css":`@tailwind base;
5701@tailwind components;
5702@tailwind utilities;
5703html, body, #root { height: 100%; margin: 0; }
5704body { font-family: system-ui, -apple-system, sans-serif; background: #f8fafc; }
5705`,"src/content.types.ts":`export interface TabItem { id: string; label: string; path: string; icon: string; }
5706export interface CardItem { id: string; title: string; subtitle: string; badge?: string; meta?: string; }
5707export interface MobileAppContent {
5708  meta: { title: string; brand: string; accent: string; appKind?: 'shop' | 'booking' | 'social' | 'generic'; };
5709  tabs: TabItem[];
5710  home: { greeting: string; headline: string; cards: CardItem[]; cta: { label: string; }; };
5711  explore: { title: string; items: CardItem[]; };
5712  activity: { title: string; items: { id: string; text: string; time: string; }[]; };
5713  profile: { name: string; email: string; role: string; stats: { label: string; value: string; }[]; };
5714}
5715`,"src/main.tsx":`import { StrictMode } from 'react';
5716import { createRoot } from 'react-dom/client';
5717import { BrowserRouter } from 'react-router-dom';
5718import './index.css';
5719import App from './App';
5720createRoot(document.getElementById('root')!).render(
5721  <StrictMode><BrowserRouter><App /></BrowserRouter></StrictMode>
5722);
5723`,"src/App.tsx":`import { useState } from 'react';
5724import { NavLink, Route, Routes, Navigate, useNavigate } from 'react-router-dom';
5725import content from './content';
5726
5727function Screen({ children, title }: { children: React.ReactNode; title?: string }) {
5728  return (
5729    <div className="flex-1 overflow-y-auto px-4 pt-4 pb-24">
5730      {title && <h1 className="text-xl font-bold text-slate-900 mb-4">{title}</h1>}
5731      {children}
5732    </div>
5733  );
5734}
5735
5736function HomeScreen() {
5737  const navigate = useNavigate();
5738  const { home, meta } = content;
5739  const kind = meta.appKind || 'generic';
5740
5741  if (kind === 'social') {
5742    return (
5743      <Screen>
5744        <p className="text-sm text-violet-600 mb-1">{home.greeting}</p>
5745        <h1 className="text-2xl font-bold text-slate-900 mb-4">{home.headline}</h1>
5746        <div className="space-y-3">
5747          {home.cards.map((card) => (
5748            <div key={card.id} className="rounded-2xl bg-white border border-violet-100 p-4">
5749              <div className="font-semibold text-slate-900">{card.title}</div>
5750              <div className="text-sm text-slate-500 mt-1">{card.subtitle}</div>
5751              <div className="mt-3 h-2 rounded-full bg-violet-100 overflow-hidden">
5752                <div className="h-full rounded-full bg-violet-500" style={{ width: '62%' }} />
5753              </div>
5754              <div className="flex gap-2 mt-3">
5755                <button type="button" className="flex-1 rounded-xl py-2 text-sm font-medium text-white" style={{ background: meta.accent }}>Vote</button>
5756                <button type="button" className="flex-1 rounded-xl py-2 text-sm font-medium border border-violet-200 text-violet-700">Skip</button>
5757              </div>
5758            </div>
5759          ))}
5760        </div>
5761      </Screen>
5762    );
5763  }
5764
5765  if (kind === 'booking') {
5766    return (
5767      <Screen>
5768        <p className="text-sm text-amber-700 mb-1">{home.greeting}</p>
5769        <h1 className="text-2xl font-bold text-slate-900 mb-4">{home.headline}</h1>
5770        <div className="grid grid-cols-3 gap-2 mb-4">
5771          {['10:00', '11:30', '2:00', '3:30', '5:00', '6:30'].map((slot) => (
5772            <button key={slot} type="button" className="rounded-xl border border-amber-200 bg-white py-3 text-sm font-medium text-amber-900">{slot}</button>
5773          ))}
5774        </div>
5775        <button type="button" onClick={() => navigate('/book')} className="w-full rounded-2xl py-4 font-semibold text-white min-h-[48px]" style={{ background: meta.accent }}>{home.cta.label}</button>
5776      </Screen>
5777    );
5778  }
5779
5780  if (kind === 'shop') {
5781    return (
5782      <Screen>
5783        <h1 className="text-2xl font-bold text-slate-900 mb-4">{home.headline}</h1>
5784        <div className="grid grid-cols-2 gap-3">
5785          {home.cards.map((card) => (
5786            <button key={card.id} type="button" onClick={() => navigate('/shop')} className="rounded-2xl bg-white border border-emerald-100 p-3 text-left">
5787              <div className="h-20 rounded-xl bg-emerald-50 mb-2" />
5788              <div className="font-semibold text-sm text-slate-900">{card.title}</div>
5789              <div className="text-xs text-emerald-700 font-medium mt
5789-1">$24.00</div>
5790            </button>
5791          ))}
5792        </div>
5793      </Screen>
5794    );
5795  }
5796
5797  return (
5798    <Screen>
5799      <p className="text-sm text-slate-500 mb-1">{home.greeting}</p>
5800      <h1 className="text-2xl font-bold text-slate-900 mb-4">{home.headline}</h1>
5801      <div className="space-y-3">
5802        {home.cards.map((card) => (
5803          <button key={card.id} type="button" onClick={() => navigate('/explore')}
5804            className="w-full text-left rounded-2xl bg-white border border-slate-200 p-4 shadow-sm active:scale-[0.98] transition min-h-[72px]">
5805            <div className="flex items-start justify-between gap-2">
5806              <div>
5807                <div className="font-semibold text-slate-900">{card.title}</div>
5808                <div className="text-sm text-slate-500 mt-1">{card.subtitle}</div>
5809              </div>
5810              {card.badge && <span className="text-xs font-medium px-2 py-1 rounded-full" style={{ background: meta.accent + '22', color: meta.accent }}>{card.badge}</span>}
5811            </div>
5812            {card.meta && <div className="text-xs text-slate-400 mt-2">{card.meta}</div>}
5813          </button>
5814        ))}
5815      </div>
5816      <button type="button" onClick={() => navigate('/activity')}
5817        className="mt-6 w-full rounded-2xl py-4 font-semibold text-white min-h-[48px]"
5818        style={{ background: meta.accent }}>{home.cta.label}</button>
5819    </Screen>
5820  );
5821}
5822
5823function ExploreScreen() {
5824  return (
5825    <Screen title={content.explore.title}>
5826      <div className="space-y-3">
5827        {content.explore.items.map((item) => (
5828          <div key={item.id} className="rounded-2xl bg-white border border-slate-200 p-4">
5829            <div className="font-semibold text-slate-900">{item.title}</div>
5830            <div className="text-sm text-slate-500 mt-1">{item.subtitle}</div>
5831          </div>
5832        ))}
5833      </div>
5834    </Screen>
5835  );
5836}
5837
5838function ActivityScreen() {
5839  return (
5840    <Screen title={content.activity.title}>
5841      <div className="space-y-3">
5842        {content.activity.items.map((item) => (
5843          <div key={item.id} className="rounded-2xl bg-white border border-slate-200 p-4 flex justify-between gap-3">
5844            <div className="text-sm text-slate-800">{item.text}</div>
5845            <div className="text-xs text-slate-400 shrink-0">{item.time}</div>
5846          </div>
5847        ))}
5848      </div>
5849    </Screen>
5850  );
5851}
5852
5853function ProfileScreen() {
5854  const { profile } = content;
5855  return (
5856    <Screen title="Profile">
5857      <div className="rounded-2xl bg-white border border-slate-200 p-5 mb-4">
5858        <div className="w-14 h-14 rounded-full flex items-center justify-center text-lg font-bold text-white mb-3" style={{ background: content.meta.accent }}>
5859          {profile.name.split(' ').map((n) => n[0]).join('').slice(0, 2)}
5860        </div>
5861        <div className="font-semibold text-slate-900">{profile.name}</div>
5862        <div className="text-sm text-slate-500">{profile.email}</div>
5863        <div className="text-xs text-slate-400 mt-1">{profile.role}</div>
5864      </div>
5865      <div className="grid grid-cols-2 gap-3">
5866        {profile.stats.map((s) => (
5867          <div key={s.label} className="rounded-2xl bg-white border border-slate-200 p-4 text-center">
5868            <div className="text-lg font-bold text-slate-900">{s.value}</div>
5869            <div className="text-xs text-slate-500 mt-1">{s.label}</div>
5870          </div>
5871        ))}
5872      </div>
5873    </Screen>
5874  );
5875}
5876
5877function BottomNav() {
5878  const icons: Record<string, string> = { home: '⌂', explore: '◎', activity: '◔', profile: '☺' };
5879  return (
5880    <nav className="fixed bottom-0 left-0 right-0 mx-auto max-w-[430px] border-t border-slate-200 bg-white/95 backdrop-blur px-2 pb-[env(safe-area-inset-bottom)]">
5881      <div className="flex justify-around">
5882        {content.tabs.map((tab) => (
5883          <NavLink key={tab.id} to={tab.path} end={tab.path === '/'}
5884            className={({ isActive }) => \`flex flex-col items-center justify-center min-w-[64px] min-h-[56px] text-xs \${isActive ? 'font-semibold' : 'text-slate-500'}\`}
5885            style={({ isActive }) => isActive ? { color: content.meta.accent } : undefined}>
5886            <span className="text-lg leading-none mb-1">{icons[tab.icon] || '•'}</span>
5887            {tab.label}
5888          </NavLink>
5889        ))}
5890      </div>
5891    </nav>
5892  );
5893}
5894
5895export default function App() {
5896  const [toast, setToast] = useState<string | null>(null);
5897  document.title = content.meta.title;
5898  return (
5899    <div className="mx-auto max-w-[430px] min-h-full bg-slate-50 flex flex-col relative shadow-xl">
5900      <header className="sticky top-0 z-10 bg-white/95 backdrop-blur border-b border-slate-200 px-4 py-3">
5901        <div className="font-semibold text-slate-900">{content.meta.brand}</div>
5902      </header>
5903      <Routes>
5904        {content.tabs.map((tab) => (
5905          <Route
5906            key={tab.path}
5907            path={tab.path}
5908            element={
5909              tab.id === 'home' || tab.path === '/' ? <HomeScreen />
5910              : tab.id === 'profile' ? <ProfileScreen />
5911              : tab.id === 'activity' || tab.id === 'appointments' ? <ActivityScreen />
5912              : <ExploreScreen />
5913            }
5914          />
5915        ))}
5916        <Route path="*" element={<Navigate to={content.tabs[0]?.path || '/'} replace />} />
5917      </Routes>
5918      <BottomNav />
5919      {toast && (
5920        <div className="fixed bottom-20 left-4 right-4 mx-auto max-w-[400px] rounded-xl bg-slate-900 text-white text-sm px-4 py-3 text-center" onClick={() => setToast(null)}>
5921          {toast}
5922        </div>
5923      )}
5924    </div>
5925  );
5926}
5927`};function NX(e){const t=e.replace(/^(build|create|make|design)\s+(me\s+)?(a|an|the)?\s*/i,"").trim(),r=Zw(t),n=Qw(r,t),s=r==="fitness",i=r==="food",o=r==="social",l=r==="bookclub",c=r==="ecommerce",u=r==="booking",d=s?"#10b981":i?"#f59e0b":o?"#8b5cf6":l?"#b45309":c?"#059669":u?"#d97706":"#3b82f6",p=s?"Crush today's goals":i?"Discover nearby favorites":o?"Vote with your crew":l?"Your club's next read":t.slice(0,60)||"Your app, ready to go",h={meta:{title:`${n} — Mobile`,brand:n,accent:d,appKind:c?"shop":u?"booking":o?"social":"generic"},tabs:c?[{id:"home",label:"Home",path:"/",icon:"home"},{id:"shop",label:"Shop",path:"/shop",icon:"explore"},{id:"cart",label:"Cart",path:"/cart",icon:"activity"},{id:"profile",label:"Profile",path:"/profile",icon:"profile"}]:u?[{id:"home",label:"Home",path:"/",icon:"home"},{id:"book",label:"Book",path:"/book",icon:"explore"},{id:"appointments",label:"Visits",path:"/appointments",icon:"activity"},{id:"profile",label:"Profile",path:"/profile",icon:"profile"}]:[{id:"home",label:"Home",path:"/",icon:"home"},{id:"explore",label:o?"Polls":l?"Books":"Explore",path:"/explore",icon:"explore"},{id:"activity",label:"Activity",path:"/activity",icon:"activity"},{id:"profile",label:"Profile",path:"/profile",icon:"profile"}],home:{greeting:"Good morning",headline:p,cards:[{id:"1",title:s?"Morning run":i?"Trending near you":o?"Weekend poll":l?"March pick":"Quick start",subtitle:s?"5.2 km · 32 min":i?"12 spots open now":o?"Where should we eat?":l?"The Midnight Library · 4.8★":"Tap to continue your flow",badge:"Live",meta:"Updated just now"},{id:"2",title:s?"Strength session":i?"Chef picks":o?"Group chat":l?"Discussion":"Saved items",subtitle:s?"Upper body · 45 min":i?"Seasonal menu highlights":o?"12 new reactions":l?"Chapter 8 notes":"3 items waiting",meta:"Yesterday"},{id:"3",title:s?"Recovery score":i?"Rewards":o?"Circles":l?"Meetup":"Teams",subtitle:s?"Sleep + HRV on track":i?"240 points available":o?"3 active groups":l?"Sat 7pm · Cafe Noir":"2 updates",badge:s?"92%":void 0}],cta:{label:s?"Start workout":i?"Order now":o?"Create poll":l?"Vote on book":"Continue"}},explore:{title:"Explore",items:[{id:"e1",title:s?"HIIT classes":i?"Brunch spots":"Featured",subtitle:"Curated for you today"},{id:"e2",title:s?"Yoga flow":i?"Healthy bowls":"Popular",subtitle:"Trending in your area"},{id:"e3",title:s?"Trail routes":i?"Late night":"New",subtitle:"Fresh this week"}]},activity:{title:"Activity",items:[{id:"a1",text:s?"Completed Morning run":i?"Order confirmed · #2841":"Profile updated",time:"2m ago"},{id:"a2",text:s?"New personal best on steps":i?"Reward points earned":"New message from team",time:"1h ago"},{id:"a3",text:s?"Weekly goal 80% complete":i?"Favorite saved":"Reminder set",time:"Yesterday"}]},profile:{name:"Alex Rivera",email:`alex@${n.toLowerCase()}.app`,role:s?"Member":i?"Foodie":"User",stats:[{label:s?"Streak":"Orders",value:s?"12 days":"28"},{label:s?"Workouts":"Saved",value:s?"47":"14"}]}};return`import type { MobileAppContent } from './content.types'
5928
5929const content: MobileAppContent = ${JSON.stringify(h,null,2)}
5930
5931export default content
5932`}function kX(e){const t=e.match(/USER REQUEST:\s*([\s\S]*)$/i);return((t==null?void 0:t[1])||e).trim()}function nO(e){const t=e.trim();return/^BUILD TYPE:\s*MOBILE/i.test(t)?"mobile-pwa":/^BUILD TYPE:\s*(LANDING|WEBSITE)/i.test(t)?"saas-landing":/^BUILD TYPE:\s*FULL\s*STACK/i.test(t)?"dashboard-app":null}function SX(e){return nO(e)!==null}function CX(e){return e.endsWith(".tsx")||e.endsWith(".jsx")?"tsx":e.endsWith(".ts")?"typescript":e.endsWith(".css")?"css":e.endsWith(".html")?"html":e.endsWith(".json")?"json":"text"}function PX(e){const t=nO(e);
5932if(!t)return[];const r=kX(e);let n,s;switch(t){case"dashboard-app":n=a0,s=o7(r);break;case"mobile-pwa":n=jX,s=NX(r);break;case"saas-landing":n=i0,s=l7(r);break}const i=Object.entries(n).map(([c,u])=>({filename:c,content:u,language:CX(c)})),o=i.findIndex(c=>c.filename==="src/content.ts"),l={filename:"src/content.ts",content:s,language:"typescript"};return o>=0?i[o]=l:i.push(l),i}const AX="sj_oauth_pending_after";function rO(){const[e,t]=m.useState(!1);return{connect:m.useCallback(async n=>{var s;t(!0);try{const o=(s=(await G.auth.getSession()).data.session)==null?void 0:s.access_token;if(!o)return t(!1),{success:!1,error:"Please sign in first."};const l=n||window.location.href,c=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/supabase-oauth-start",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"},body:JSON.stringify({redirect_to:l})});if(!c.ok){const d=await c.json().catch(()=>({}));return t(!1),{success:!1,error:(d==null?void 0:d.error)||`OAuth start failed (HTTP ${c.status})`}}const{authorize_url:u}=await c.json();try{sessionStorage.setItem(AX,l)}catch{}return window.location.href=u,{success:!1,redirecting:!0}}catch(i){return t(!1),{success:!1,error:i.message||"Network error"}}},[]),connecting:e}}function H1(){var i;const e=il();m.useCallback(o=>{var y;const l=(o||((y=e==null?void 0:e.project)==null?void 0:y.name)||"Studio Jungle").trim()||"Studio Jungle",c=l.split(/\s+/).filter(Boolean).slice(0,2).map(b=>{var v;return((v=b[0])==null?void 0:v.toUpperCase())||""}).join("")||"SJ";let u=0;for(let b=0;b<l.length;b++)u=(u<<5)-u+l.charCodeAt(b)|0;const d=[["#114c34","#86c7a8","#f2fbf6"],["#3a225f","#c7a4f7","#fbf7ff"],["#21476b","#8ec5ff","#f4f9ff"],["#6b3a21","#f2b879","#fff8f0"],["#19464f","#88d6cf","#f3fffd"]],[p,h,f]=d[Math.abs(u)%d.length],x=l.replace(/[&<>"']/g,b=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"})[b]||b),g=`<svg xmlns="http://www.w3.org/2000/svg" width="768" height="480" viewBox="0 0 768 480">
5933      <defs>
5934        <linearGradient id="bg" x1="0" x2="1" y1="0" y2="1">
5935          <stop offset="0" stop-color="${f}"/>
5936          <stop offset="1" stop-color="#ffffff"/>
5937        </linearGradient>
5938        <filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
5939          <feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="${p}" flood-opacity="0.16"/>
5940        </filter>
5941      </defs>
5942      <rect width="768" height="480" fill="url(#bg)"/>
5943      <rect x="54" y="48" width="660" height="384" rx="28" fill="#ffffff" stroke="${p}" stroke-opacity="0.12" filter="url(#shadow)"/>
5944      <rect x="54" y="48" width="660" height="58" rx="28" fill="${p}" fill-opacity="0.06"/>
5945      <circle cx="89" cy="77" r="7" fill="#ef6461"/>
5946      <circle cx="113" cy="77" r="7" fill="#f4b860"/>
5947      <circle cx="137" cy="77" r="7" fill="#57b894"/>
5948      <rect x="176" y="66" width="260" height="20" rx="10" fill="${p}" fill-opacity="0.10"/>
5949      <rect x="96" y="150" width="150" height="150" rx="32" fill="${p}"/>
5950      <text x="171" y="242" text-anchor="middle" font-family="Inter, Arial, sans-serif" font-size="54" font-weight="800" fill="${h}">${c}</text>
5951      <rect x="286" y="154" width="330" height="24" rx="12" fill="${p}" fill-opacity="0.18"/>
5952      <rect x="286" y="196" width="260" height="18" rx="9" fill="${p}" fill-opacity="0.10"/>
5953      <rect x="286" y="230" width="300" height="18" rx="9" fill="${p}" fill-opacity="0.10"/>
5954      <rect x="286" y="286" width="132" height="42" rx="21" fill="${p}"/>
5955      <rect x="436" y="286" width="112" height="42" rx="21" fill="${h}" fill-opacity="0.35"/>
5956      <text x="96" y="371" font-family="Inter, Arial, sans-serif" font-size="22" font-weight="700" fill="${p}">${x.slice(0,42)}</text>
5957      <text x="96" y="398" font-family="Inter, Arial, sans-serif" font-size="14" fill="${p}" fill-opacity="0.55">Project preview</text>
5958    </svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(g)}`},[(i=e==null?void 0:e.project)==null?void 0:i.name]);const t=m.useCallback(async(o,l)=>
5958{if(!(!o||!l)){if(e!=null&&e.saveThumbnail){await e.saveThumbnail(o,l);return}await G.from("projects").update({thumbnail_url:l}).eq("id",o)}},[e]),r=m.useCallback(async o=>{if(!o)return null;const l=document.createElement("iframe");l.dataset.thumbnailTmp="1",l.style.cssText="position:fixed;top:-9999px;left:-9999px;width:1280px;height:800px;border:none;opacity:0;pointer-events:none;",l.sandbox.add("allow-scripts"),document.body.appendChild(l),l.srcdoc=o,await new Promise(c=>{l.onload=()=>setTimeout(c,2500),setTimeout(c,6e3)});try{const c=l.contentDocument;if(!(c!=null&&c.body))return null;const u=1280,d=800,p=document.createElement("canvas"),h=.3;p.width=Math.round(u*h),p.height=Math.round(d*h);const f=p.getContext("2d");if(!f)return null;f.fillStyle="#ffffff",f.fillRect(0,0,p.width,p.height);const g=new XMLSerializer().serializeToString(c.documentElement),y=`<svg xmlns="http://www.w3.org/2000/svg" width="${u}" height="${d}">
5959        <foreignObject width="100%" height="100%">
5960          ${g}
5961        </foreignObject>
5962      </svg>`,b=new Blob([y],{type:"image/svg+xml;charset=utf-8"}),v=URL.createObjectURL(b),k=new Image;await new Promise((j,w)=>{k.onload=()=>{try{f.drawImage(k,0,0,p.width,p.height)}catch{}URL.revokeObjectURL(v),j()},k.onerror=()=>{URL.revokeObjectURL(v),w(new Error("Failed to render thumbnail"))},k.src=v});const N=p.toDataURL("image/jpeg",.65);return N.length>4e3?N:null}finally{if(l.parentNode)try{l.parentNode.removeChild(l)}catch{}}},[]),n=m.useCallback(async(o,l,c)=>{if(!o||!l)return null;try{const u=await r(l);if(u)return await t(o,u),u}catch(u){console.warn("Thumbnail backfill failed (non-critical):",u)}return null},[r,t]);return{capturePreviewThumbnail:m.useCallback(async o=>{var d;if(!((d=e==null?void 0:e.project)!=null&&d.id))return;const l=(()=>{try{return document.querySelector('iframe[src*="e2b.app"], iframe[title*="preview" i], iframe[data-webcontainer]')}catch{return null}})();if(l!=null&&l.contentWindow){const p=await new Promise(h=>{const f="thumb-"+Math.random().toString(36).slice(2),x=window.setTimeout(()=>{window.removeEventListener("message",g),h(null)},12e3);function g(y){const b=(y==null?void 0:y.data)??null;!b||typeof b!="object"||b.type!=="sj-thumbnail-ready"||b.requestId!==f||(window.clearTimeout(x),window.removeEventListener("message",g),h(typeof b.dataUrl=="string"&&b.dataUrl.length>4e3?b.dataUrl:null))}window.addEventListener("message",g);try{l.contentWindow.postMessage({type:"sj-capture-thumbnail",requestId:f},"*")}catch{window.clearTimeout(x),window.removeEventListener("message",g),h(null)}});if(p){await t(e.project.id,p);return}}let c=null,u=!1;try{c=document.querySelector('iframe[title*="preview" i], iframe[data-webcontainer], iframe[srcdoc]:not([data-thumbnail-tmp])')}catch{}if(!c){if(!o)return;c=document.createElement("iframe"),c.dataset.thumbnailTmp="1",c.style.cssText="position:fixed;top:-9999px;left:-9999px;width:1280px;height:800px;border:none;opacity:0;pointer-events:none;",c.sandbox.add("allow-scripts"),document.body.appendChild(c),c.srcdoc=o,u=!0,await new Promise(p=>{c.onload=()=>setTimeout(p,2500),setTimeout(p,6e3)})}try{const p=c==null?void 0:c.contentDocument;if(!(p!=null&&p.body)){u&&c&&document.body.removeChild(c);return}const h=c.getBoundingClientRect(),f=u?1280:Math.max(640,Math.round(h.width||1280)),x=u?800:Math.max(400,Math.round(h.height||800)),g=document.createElement("canvas"),y=.3;g.width=Math.round(f*y),g.height=Math.round(x*y);const b=g.getContext("2d");if(!b){u&&c&&document.body.removeChild(c);return}b.fillStyle="#ffffff",b.fillRect(0,0,g.width,g.height);const k=new XMLSerializer().serializeToString(p.documentElement),N=`<svg xmlns="http://www.w3.org/2000/svg" width="${f}" height="${x}">
5963        <foreignObject width="100%" height="100%">
5964          ${k}
5965        </foreignObject>
5966      </svg>`,j=new Blob([N],{type:"image/svg+xml;charset=utf-8"}),w=URL.createObjectURL(j),S=new Image;await new Promise((C,A)=>{S.onload=()=>{try{b.drawImage(S,0,0,g.width,g.height)}catch{}URL.revokeObjectURL(w),C()},S.onerror=()=>{URL.revokeObjectURL(w),A(new Error("Failed to render thumbnail"))},S.src=w});const T=g.toDataURL("image/jpeg",.65);u&&c&&document.body.removeChild(c),T.length>4e3&&await t(e.project.id,T)}catch(p){if(u&&(c!=null&&c.parentNode))try{c.parentNode.removeChild(c)}catch{}console.warn("Thumbnail capture failed (non-critical):",p)}},[t,e]),captureHtmlThumbnail:n}}function W1(e){const{user:t}=Us(),[r,n]=m.useState([]),[s,i]=m.useState([]),[o,l]=m.useState(!0),c=m.useCallback(async()=>
5966{if(!e||!t){n([]),l(!1);return}const{data:y}=await G.from("project_edge_functions").select("*").eq("project_id",e).order("created_at",{ascending:!0});n(y||[]),l(!1)},[e,t]),u=m.useCallback(async()=>{if(!e||!t){i([]);return}const{data:y}=await G.from("project_secrets").select("*").eq("project_id",e).order("created_at",{ascending:!0});i(y||[])},[e,t]);m.useEffect(()=>{c(),u()},[c,u]);const d=m.useCallback(async y=>{if(!e||!t)return null;const{data:b,error:v}=await G.from("project_edge_functions").upsert({project_id:e,user_id:t.id,function_name:y.function_name,display_name:y.display_name,description:y.description||null,methods:y.methods||["POST"],path:y.path,verify_jwt:y.verify_jwt??!0,source_code:y.source_code||null,auto_generated:y.auto_generated??!1,feature_category:y.feature_category||null,config:y.config||{}},{onConflict:"project_id,function_name"}).select().single();return b?(await c(),b):null},[e,t,c]),p=m.useCallback(async y=>{await G.from("project_edge_functions").delete().eq("id",y),await c()},[c]),h=m.useCallback(async(y,b)=>{await G.from("project_edge_functions").update({status:b}).eq("id",y),await c()},[c]),f=m.useCallback(async(y,b=!1)=>{!e||!t||(await G.from("project_secrets").upsert({project_id:e,user_id:t.id,secret_name:y,is_configured:b},{onConflict:"project_id,secret_name"}),await u())},[e,t,u]),x=m.useCallback(async y=>{var N;if(!e)return;const b=s.find(j=>j.id===y);if(!b)return;const{data:v,error:k}=await G.functions.invoke("store-secret",{body:{action:"delete",projectId:e,names:[b.secret_name]}});if(k)throw new Error(k.message);if(v!=null&&v.error)throw new Error(v.error);if(((N=v==null?void 0:v.failed)==null?void 0:N.length)>0)throw new Error(v.failed[0].error||"Secret delete failed");await G.from("project_secrets").delete().eq("id",y),await u()},[u,e,s]),g=m.useCallback(async y=>{if(!e||!t)return;const b=new Set,v=N=>{const j=[/Deno\.env\.get\(["'](\w+)["']\)/g,/process\.env\.(\w+)/g,/import\.meta\.env\.(\w+)/g,/\benv\.(\w+)/g,/\[\[SECRET:(\w+)\]\]/g];for(const w of j){let S;for(;(S=w.exec(N))!==null;)b.add(S[1])}};for(const N of y)v(N.content);for(const N of y){const j=N.filename.match(/(?:supabase\/)?functions\/([^/]+)\//);if(j&&(N.content.includes("serve(")||N.content.includes("Deno.serve("))){const w=j[1],S=[];(N.content.includes("req.method")||N.content.includes("request.method"))&&((N.content.includes('"GET"')||N.content.includes("'GET'"))&&S.push("GET"),(N.content.includes('"POST"')||N.content.includes("'POST'"))&&S.push("POST"),(N.content.includes('"PUT"')||N.content.includes("'PUT'"))&&S.push("PUT"),(N.content.includes('"DELETE"')||N.content.includes("'DELETE'"))&&S.push("DELETE"),(N.content.includes('"PATCH"')||N.content.includes("'PATCH'"))&&S.push("PATCH")),S.length===0&&S.push("POST");let T="general";N.content.includes("auth")||N.content.includes("signUp")||N.content.includes("signIn")?T="auth":N.content.includes(".from(")&&(N.content.includes(".insert")||N.content.includes(".select"))?T="crud":N.content.includes("openai")||N.content.includes("anthropic")||N.content.includes("gemini")?T="ai":N.content.includes("webhook")||N.content.includes("stripe")?T="webhook":(N.content.includes("storage")||N.content.includes("upload"))&&(T="storage");const C=N.content.includes("getClaims")||N.content.includes("getUser")||N.content.includes("Authorization");await d({function_name:w,display_name:w.replace(/-/g," ").replace(/\b\w/g,E=>E.toUpperCase()),description:`Auto-generated ${T} function`,methods:S,path:`/functions/v1/${w}`,verify_jwt:C,source_code:N.content,auto_generated:!0,feature_category:T});const A=/Deno\.env\.get\(["'](\w+)["']\)/g;let P;for(;(P=A.exec(N.content))!==null;){const E=P[1];b.add(E),["SUPABASE_URL","SUPABASE_ANON_KEY"].includes(E)||await f(E)}continue}if(N.filename.includes("api/")&&(N.content.includes("router.get")||N.content.includes("router.post"))){const w=/router\.(get|post|put|delete|patch)\s*\(\s*['"`]([^'"`]+)['"`]/gi,S=[],T=[];let C;for(;(C=w.exec(N.content))!==null;){const P=C[1].toUpperCase();S.includes(P)||S.push(P),T.includes(C[2])||T.push(C[2])}if(T.length===0)continue;const A=new Set;for(const P of T){const E=P.match(/\/api\/([^/:]+)/);E&&A.add(E[1])}for(const P of A){const E=T.filter(I=>I.includes(`/api/${P}`)).map(I=>{const D=N.content.match(new RegExp(`router\\.(get|post|put|delete|patch)\\s*\\(\\s*['"\`][^'"\`]*\\/api\\/${P}`,"i"));return D?D[1].toUpperCase():"GET"}),_=[...new Set(E)];await d({function_name:`api-${P}`,display_name:`${P.charAt(0).toUpperCase()+P.slice(1)} API`,description:`REST API for ${P} (${_.join(", ")})`,methods:_.length>0?_:S,path:`/api/${P}`,verify_jwt:N.content.includes("auth")||N.content.includes("protect"),source_code:N.content,auto_generated:!0,feature_category:"crud"})}}if(N.filename.includes("schema.sql")&&N.content.includes("CREATE TABLE")){const w=(N.content.match(/CREATE TABLE/gi)||[]).length;await d({function_name:"database-schema",display_name:"Database Schema",description:`${w} table(s) defined`,methods:["SQL"],path:"/schema",verify_jwt:!1,source_code:N.content,auto_generated:!0,feature_category:"crud"})}}const{data:k}=await G.from("project_secrets").select("id, secret_name").eq("project_id",e);for(const N of k||[])if(!["SUPABASE_URL","SUPABASE_ANON_KEY","SUPABASE_SERVICE_ROLE_KEY"].includes(N.secret_name)&&!b.has(N.secret_name))try{await x(N.id)}catch(j){console.warn("[secrets] prune failed for",N.secret_name,j)}},[e,t,d,f,x]);return{functions:r,secrets:s,loading:o,addFunction:d,removeFunction:p,updateFunctionStatus:h,addSecret:f,removeSecret:x,autoDetectFunctions:g,refresh:()=>{c(),u()}}}const _2=[{label:"Pages",emoji:"📄",match:e=>/\/pages\//i.test(e)||/^src\/pages\//.test(e)||e.endsWith("Page.tsx")},{label:"Components",emoji:"🧩",match:e=>/\/components\//.test(e)},{label:"Hooks",emoji:"🪝",match:e=>/\/hooks\//.test(e)||/^src\/hooks\//.test(e)},{label:"Library / utilities",emoji:"🛠️",match:e=>/\/lib\//.test(e)||/\/utils\//.test(e)},{label:"Database",emoji:"🗄️",match:e=>e.endsWith(".sql")||/\/migrations\//.test(e)||/supabase\/functions\//.test(e)},{label:"Styles",emoji:"🎨",match:e=>e.endsWith(".css")||e.endsWith(".scss")||e==="tailwind.config.ts"||e==="tailwind.config.js"},{label:"Configuration",emoji:"⚙️",match:e=>/^(package\.json|tsconfig.*\.json|vite\.config\..*|\.env.*|\.gitignore)$/.test(e)},{label:"Deploy artifacts",emoji:"🚀",match:e=>/^(vercel\.json|netlify\.toml|Dockerfile|\.github\/workflows\/.+\.ya?ml)$/.test(e)}],T2={label:"Other",emoji:"📦",match:()=>!0};function _X({projectName:e,files:t,commitSha:r,branch:n,designMode:s}){if(t.length===0)return`Auto-generated update from StudioJungle for **${e}**.
5967
5968No files in this push.`;const i=new Map;for(const d of t){const p=_2.find(h=>h.match(d.path))||T2;i.has(p.label)||i.set(p.label,[]),i.get(p.label).push(d)}const o=t.reduce((d,p)=>d+p.content.split(`
5969`).length,0),l=["## 🤖 StudioJungle update","",`Auto-generated for **${e}** on branch \`${n}\`.`,"",`- **Files:** ${t.length}
5969`,`- **Lines of code:** ~${o.toLocaleString()}`,r?`- **Commit:** \`${r.slice(0,7)}\``:null,s&&s!=="auto"?`- **Design mode:** ${s}`:null].filter(Boolean).join(`
5970`),c=[];for(const d of[..._2,T2]){const p=i.get(d.label);!p||p.length===0||c.push(`<details>
5971<summary>${d.emoji} <strong>${d.label}</strong> (${p.length})</summary>
5972
5973${p.map(h=>`- \`${h.path}\``).join(`
5974`)}
5975
5976</details>`)}const u=["---","<sub>Generated by [StudioJungle](https://studiojungle.ai). Review the diff carefully — AI-generated code can introduce subtle issues. Don't merge without testing.</sub>"].join(`
5977`);return[l,"","## Files changed","",c.join(`
5978
5979`),"",u].join(`
5980`)}function gx(e){return{token:`github-token::${e}`,login:`github-user-login::${e}`,name:`github-user-name::${e}`,avatar:`github-user-avatar::${e}`}}function Dh(e){if(!e||typeof window>"u")return{token:"",user:null};const t=gx(e),r=localStorage.getItem(t.token)||"",n=localStorage.getItem(t.login)||"";return{token:r,user:n?{login:n,name:localStorage.getItem(t.name)||n,avatar_url:localStorage.getItem(t.avatar)||""}:null}}function TX(e,t){!e||typeof window>"u"||localStorage.setItem(gx(e).token,t)}function EX(e,t){if(!e||typeof window>"u")return;const r=gx(e);localStorage.setItem(r.login,t.login),localStorage.setItem(r.name,t.name||t.login),localStorage.setItem(r.avatar,t.avatar_url||"")}function IX(e){if(!e||typeof window>"u")return;const t=gx(e);[t.token,t.login,t.name,t.avatar].forEach(r=>localStorage.removeItem(r))}function sO(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="folder"&&n.children?r.push(...sO(n.children,s)):n.type==="file"&&n.content&&r.push({path:s,content:n.content})}return r}async function OX(e){try{const{data:n,error:s}=await G.from("projects").select("github_owner, github_repo, github_branch, github_auto_push, github_auto_pr").eq("id",e).single();if(!s&&(n!=null&&n.github_owner)&&(n!=null&&n.github_repo))return{owner:n.github_owner,repo:n.github_repo,branch:n.github_branch||"main",autoPush:!!n.github_auto_push,autoPr:!!n.github_auto_pr}}catch{}const t=localStorage.getItem(`github-owner::${e}`),r=localStorage.getItem(`github-repo::${e}`);return t&&r?{owner:t,repo:r,branch:localStorage.getItem(`github-branch::${e}`)||"main",autoPush:localStorage.getItem(`github-auto-push::${e}`)==="true",autoPr:localStorage.getItem(`github-auto-pr::${e}`)==="true"}:null}function RX(){const{user:e}=Us();return{triggerAutoPush:m.useCallback(async(r,n,s)=>{const i=Dh(e==null?void 0:e.id).token;if(!i)return{ok:!1,error:"github not configured"};if(!s)return{ok:!1,error:"no project id"};const o=await OX(s);if(!o)return{ok:!1,error:"github not configured"};if(!o.autoPush)return{ok:!1,error:"auto-push disabled"};const{owner:l,repo:c,branch:u,autoPr:d}=o,p=sO(r);if(p.length===0)return{ok:!1,error:"no files to push"};let h;const{data:{user:f}}=await G.auth.getUser();if(f){const{data:x}=await G.from("project_deployments").insert({project_id:s,user_id:f.id,target:"github",status:"pending",branch:u,metadata:{owner:l,repo:c,file_count:p.length}}).select("id").single();h=x==null?void 0:x.id}try{const{data:x,error:g}=await G.functions.invoke("github-push",{body:{action:"push",token:i,owner:l,repo:c,files:p,commitMessage:`Auto-push from StudioJungle — ${n||"project"} — ${new Date().toISOString()}`,branch:u,committer:{name:"StudioJungle Bot",email:"[email protected]"}}});if(g)throw new Error(g.message);if(x!=null&&x.error)throw new Error(x.error);const y=x==null?void 0:x.commit_sha,b=x==null?void 0:x.html_url;let v,k;if(d&&u!=="main"&&u!=="master"){const N=localStorage.getItem("studio-design-mode")||void 0,j=_X({projectName:n||"this project",files:p,commitSha:y,branch:u,designMode:N||void 0}),{data:w,error:S}=await G.functions.invoke("github-push",{body:{action:"create-pull-request",token:i,owner:l,repo:c,head:u,base:"main",title:`StudioJungle: ${n||"update"}`,body:j}});!S&&!(w!=null&&w.error)&&(v=w==null?void 0:w.number,k=w==null?void 0:w.html_url)}return h&&await G.from("project_deployments").update({status:"success",commit_sha:y,pr_number:v,pr_url:k,deploy_url:b}).eq("id",h),W.success("Pushed to GitHub",{description:k?`${l}/${c} — PR #${v} opened`:`${l}/${c}`}),{ok:!0,commit_sha:y,commit_url:b,pr_number:v,pr_url:k}}catch(x){const g=x instanceof Error?x.message:"Unknown error";return h&&await G.from("project_deployments").update({status:"failed",error_message:g}).eq("id",h),W.error("Auto-push failed",{description:g}),{ok:!1,error:g}}},[e==null?void 0:e.id])}}function aO(){const[e,t]=m.useState(!1),r=async()=>{var d;return{"Content-Type":"application/json",Authorization:`Bearer ${((d=(await G.auth.getSession()).data.session)==null?void 0:d.access_token)||""}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"}},n=m.useCallback(async()=>{const{data:c}=await G.from("user_supabase_tokens").select("user_id").limit(1).maybeSingle();return!!c},[]),s=m.useCallback(async(c,u,d)=>{try{const p=await r(),{data:h}=await G.from("project_cloud_config").select("env_vars").eq("project_id",c).maybeSingle(),f=(h==null?void 0:h.env_vars)||{};if(f.SUPABASE_URL&&f.SUPABASE_ANON_KEY)return{success:!0};const{data:x}=await G.from("project_cloud_config").select("region").eq("project_id",c).maybeSingle(),g=d||(x==null?void 0:x.region)||"us-east-1";d&&d!==(x==null?void 0:x.region)&&await G.from("project_cloud_config").update({region:d}).eq("project_id",c);const y=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/provision-supabase",{method:"POST",headers:p,body:JSON.stringify({projectId:c,projectName:u||c,region:g})}),b=await y.json();
5980return y.ok?{success:!0,info:{supabase_url:b.supabase_url,region:b.region,supabase_project_id:b.supabase_project_id}}:y.status===412&&(b==null?void 0:b.error)==="supabase_not_connected"?{success:!1,needs_connect:!0,error:b.message||"Connect Supabase first."}:{success:!1,error:b.error||"Provisioning failed"}}catch(p){return{success:!1,error:p.message}}},[]),i=m.useCallback(async(c,u)=>{if(!c||u.length===0)return{success:!0,results:[]};t(!0);try{const d=await r(),p=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/deploy-to-project",{method:"POST",headers:d,body:JSON.stringify({projectId:c,functions:u})}),h=await p.json();return p.ok?{success:h.success,results:h.results||[],error:h.success?void 0:"Some functions failed to deploy"}:{success:!1,results:[],error:h.error||"Deploy failed"}}catch(d){return{success:!1,results:[],error:d.message}}finally{t(!1)}},[]),o=m.useCallback(async(c,u)=>{if(!c)return{success:!1,error:"No project ID"};try{const d=await r(),p=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/project-db-migrate",{method:"POST",headers:d,body:JSON.stringify({projectId:c,...u})}),h=await p.json();if(!p.ok||(h==null?void 0:h.success)===!1){const f=[];return h.error&&f.push(h.error),h.failed_statement&&f.push(`at: ${h.failed_statement}`),typeof h.executed=="number"&&typeof h.skipped=="number"&&f.push(`${h.executed} executed, ${h.skipped} skipped before failure`),{success:!1,error:f.join(" — ")||"Migration failed"}}return{success:!0}}catch(d){return{success:!1,error:d.message}}},[]),l=m.useCallback(async(c,u,d)=>{var y,b,v,k;const p=[];for(const N of u){const j=N.filename.match(/^supabase\/functions\/([^/]+)\/index\.ts$/);j&&p.push({slug:j[1],code:N.content,verifyJwt:!1})}const f=u.filter(N=>N.filename.endsWith(".sql")&&/CREATE\s+TABLE/i.test(N.content)).map(N=>N.content).join(`
5981`),x={functions:{deployed:0,failed:0,pending:0,results:[]},schema:{success:!1},autoProvisioned:!1,pendingConnect:!1};if((p.length>0||f.length>0)&&(d!=null&&d.onNeedsConnect)&&!await n()&&!await d.onNeedsConnect())return x.pendingConnect=!0,x.functions.pending=p.length,x.schema=f?{success:!1,pending:!0,error:"Supabase not connected. Schema staged until you connect Supabase."}:{success:!0},x;if(p.length>0){const N=await i(c,p);x.functions={deployed:N.results.filter(j=>j.success).length,failed:N.results.filter(j=>!j.success).length,pending:0,results:N.results}}if(f){let N=await o(c,{sql:f});const j=((y=N.error)==null?void 0:y.includes("not provisioned"))||((b=N.error)==null?void 0:b.includes("not_provisioned"));if(!N.success&&j){(v=d==null?void 0:d.onProvisionStart)==null||v.call(d);let w;if(d!=null&&d.onNeedRegion){const T=await d.onNeedRegion();if(T===null)return{...x,schema:{success:!1,error:"Region selection cancelled."}};w=T}let S=await s(c,d==null?void 0:d.projectName,w);if(S.needs_connect&&(d!=null&&d.onNeedsConnect)){try{sessionStorage.setItem("sj_pending_cloud_provision",JSON.stringify({projectId:c,projectName:(d==null?void 0:d.projectName)||c,region:w||"us-east-1"}))}catch{}if(await d.onNeedsConnect())S=await s(c,d==null?void 0:d.projectName,w);else return{...x,pendingConnect:!0,functions:{...x.functions,pending:p.length-x.functions.deployed},schema:{success:!1,pending:!0,error:"Supabase not connected. Schema staged until you connect Supabase."}}}(k=d==null?void 0:d.onProvisionDone)==null||k.call(d,S.success,S.info),S.success?(x.autoProvisioned=!0,await new Promise(T=>setTimeout(T,3e3)),N=await o(c,{sql:f})):N={success:!1,error:`Auto-provision failed: ${S.error}`}}x.schema=N}return x},[i,o,s,n]);return{deployFunctions:i,migrateSchema:o,deployBuildArtifacts:l,deploying:e,autoProvision:s,isSupabaseConnected:n}}var xx="Checkbox",[DX,Tve]=sl(xx),[MX,V1]=DX(xx);function LX(e){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:s,disabled:i,form:o,name:l,onCheckedChange:c,required:u,value:d="on",internal_do_not_use_render:p}=e,[h,f]=ac({prop:r,defaultProp:s??!1,onChange:c,caller:xx}),[x,g]=m.useState(null),[y,b]=m.useState(null),v=m.useRef(!1),k=x?!!o||!!x.closest("form"):!0,N={checked:h,disabled:i,setChecked:f,control:x,setControl:g,name:l,form:o,value:d,hasConsumerStoppedPropagationRef:v,required:u,defaultChecked:Xo(s)?!1:s,isFormControl:k,bubbleInput:y,setBubbleInput:b};return a.jsx(MX,{scope:t,...N,children:$X(p)?p(N):n})}var iO="CheckboxTrigger",oO=m.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:r,...n},s)=>{const{control:i,value:o,disabled:l,checked:c,required:u,setControl:d,setChecked:p,hasConsumerStoppedPropagationRef:h,isFormControl:f,bubbleInput:x}=V1(iO,e),g=Tr(s,d),y=m.useRef(c);return m.useEffect(()=>{const b=i==null?void 0:i.form;if(b){const v=()=>p(y.current);return b.addEventListener("reset",v),()=>b.removeEventListener("reset",v)}},[i,p]),a.jsx(En.button,{type:"button",role:"checkbox","aria-checked":Xo(c)?"mixed":c,"aria-required":u,"data-state":pO(c),"data-disabled":l?"":void 0,disabled:l,value:o,...n,ref:g,onKeyDown:vn(t,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:vn(r,b=>{p(v=>Xo(v)?!0:!v),x&&f&&(h.current=b.isPropagationStopped(),h.current||b.stopPropagation())})})});oO.displayName=iO;var G1=m.forwardRef((e,t)=>
5981{const{__scopeCheckbox:r,name:n,checked:s,defaultChecked:i,required:o,disabled:l,value:c,onCheckedChange:u,form:d,...p}=e;return a.jsx(LX,{__scopeCheckbox:r,checked:s,defaultChecked:i,disabled:l,required:o,onCheckedChange:u,name:n,form:d,value:c,internal_do_not_use_render:({isFormControl:h})=>a.jsxs(a.Fragment,{children:[a.jsx(oO,{...p,ref:t,__scopeCheckbox:r}),h&&a.jsx(dO,{__scopeCheckbox:r})]})})});G1.displayName=xx;var lO="CheckboxIndicator",cO=m.forwardRef((e,t)=>{const{__scopeCheckbox:r,forceMount:n,...s}=e,i=V1(lO,r);return a.jsx(Fa,{present:n||Xo(i.checked)||i.checked===!0,children:a.jsx(En.span,{"data-state":pO(i.checked),"data-disabled":i.disabled?"":void 0,...s,ref:t,style:{pointerEvents:"none",...e.style}})})});cO.displayName=lO;var uO="CheckboxBubbleInput",dO=m.forwardRef(({__scopeCheckbox:e,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:s,checked:i,defaultChecked:o,required:l,disabled:c,name:u,value:d,form:p,bubbleInput:h,setBubbleInput:f}=V1(uO,e),x=Tr(r,f),g=q_(i),y=ML(n);m.useEffect(()=>{const v=h;if(!v)return;const k=window.HTMLInputElement.prototype,j=Object.getOwnPropertyDescriptor(k,"checked").set,w=!s.current;if(g!==i&&j){const S=new Event("click",{bubbles:w});v.indeterminate=Xo(i),j.call(v,Xo(i)?!1:i),v.dispatchEvent(S)}},[h,g,i,s]);const b=m.useRef(Xo(i)?!1:i);return a.jsx(En.input,{type:"checkbox","aria-hidden":!0,defaultChecked:o??b.current,required:l,disabled:c,name:u,value:d,form:p,...t,tabIndex:-1,ref:x,style:{...t.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});dO.displayName=uO;function $X(e){return typeof e=="function"}function Xo(e){return e==="indeterminate"}function pO(e){return Xo(e)?"indeterminate":e?"checked":"unchecked"}const hO=m.forwardRef(({className:e,...t},r)=>a.jsx(G1,{ref:r,className:L("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:a.jsx(cO,{className:L("flex items-center justify-center text-current"),children:a.jsx(Wn,{className:"h-4 w-4"})})}));hO.displayName=G1.displayName;const fO=[{value:"eu-central-1",label:"Europe (Frankfurt)",flag:"🇩🇪",tzPrefixes:["Europe/Berlin","Europe/Vienna","Europe/Zurich","Europe/Stockholm","Europe/Helsinki","Europe/Warsaw","Europe/Prague","Europe/Oslo","Europe/Copenhagen","Europe","Africa"]},{value:"eu-west-1",label:"Europe (Ireland)",flag:"🇮🇪",tzPrefixes:["Europe/Dublin","Europe/London","Europe/Lisbon"]},{value:"us-east-1",label:"US East (N. Virginia)",flag:"🇺🇸",tzPrefixes:["America"]},{value:"ap-southeast-1",label:"Asia Pacific (Singapore)",flag:"🇸🇬",tzPrefixes:["Asia","Indian"]},{value:"ap-northeast-1",label:"Japan (Tokyo)",flag:"🇯🇵",tzPrefixes:["Asia/Tokyo","Asia/Seoul"]}];function eb(){try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone||"";for(const t of fO)for(const r of t.tzPrefixes)if(e===r||e.startsWith(r+"/")||e.startsWith(r))return t.value}catch{}return"eu-central-1"}function FX({open:e,onAllow:t,onSkip:r,intent:n}){const[s,i]=m.useState(()=>eb()),[o,l]=m.useState(!1);if(m.useEffect(()=>{e&&i(eb())},[e]),!e)return null;const c=[];n!=null&&n.needsAuth&&c.push("login"),n!=null&&n.needsDatabase&&c.push("a database"),n!=null&&n.needsAI&&c.push("AI features"),n!=null&&n.needsRealtime&&c.push("realtime updates"),n!=null&&n.needsFileStorage&&c.push("file storage"),n!=null&&n.needsBilling&&c.push("billing");const u=c.length===0?null:c.length===1?c[0]:c.length===2?`${c[0]} and ${c[1]}`:`${c.slice(0,-1).join(", ")}, and ${c[c.length-1]}`,d=[{icon:Hn,title:"Cloud — database, storage, auth",desc:"Postgres + RLS for per-user data, file storage with signed URLs, email + password auth out of the box.",emphasis:!0}];return(!n||n.needsAI===void 0||n.needsAI===!0)&&d.push({icon:sT,title:"Studio Jungle AI — chat, vision, generation",desc:"Studio Jungle routes each request through the right AI lane. Your app calls our proxy — no API keys to manage. Billed in AI credits, included in your plan.",emphasis:!0}),n!=null&&n.needsRealtime&&d.push({icon:hr,title:"Realtime channels",desc:"Live updates for messaging, presence, collaborative editing."}),n!=null&&n.needsFileStorage&&d.push({icon:ad,title:"File storage",desc:"Secure uploads with per-user folders and signed URL downloads."}),a.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",children:a.jsxs("div",{className:"bg-card border rounded-2xl shadow-2xl max-w-lg w-full mx-4 animate-in fade-in zoom-in-95 duration-200 overflow-hidden",children:[a.jsxs("div",{className:"px-6 pt-5 pb-3 flex items-start justify-between gap-4 border-b",children:[a.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[a.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx(Dn,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Enable Cloud for this project"}),a.jsx("p",{className:"text-[12.5px] text-muted-foreground leading-snug mt-0.5",children:u?a.jsxs(a.Fragment,{children:["To build ",u,", this project needs hosted infrastru
5981cture. One time setup."]}):a.jsx(a.Fragment,{children:"This is a one-time setup that turns on backend infrastructure and Studio Jungle AI for this project."})})]})]}),a.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-foreground transition-colors shrink-0 -mt-0.5","aria-label":"Close",children:a.jsx(qn,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"px-6 py-5 space-y-4",children:[a.jsx("ul",{className:"space-y-3",children:d.map(h=>a.jsxs("li",{className:L("flex items-start gap-3 p-3 rounded-xl",h.emphasis?"bg-secondary/40 border":""),children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0 mt-0.5",children:a.jsx(h.icon,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-[13px] font-semibold text-foreground",children:h.title}),a.jsx("p",{className:"text-[11.5px] text-muted-foreground leading-relaxed mt-0.5",children:h.desc})]})]},h.title))}),a.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-xl border",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-muted flex items-center justify-center shrink-0 mt-0.5",children:a.jsx(Br,{className:"w-4 h-4 text-foreground"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[13px] font-semibold text-foreground",children:"Hosting region"}),a.jsxs("p",{className:"text-[11.5px] text-muted-foreground leading-relaxed mt-0.5",children:["Where this project's data lives. ",a.jsx("span",{className:"text-foreground/80",children:"Region can't be changed later."})]}),a.jsxs(Ns,{value:s,onValueChange:i,children:[a.jsx(hs,{className:"w-full sm:w-56 h-9 text-[12.5px] mt-2",children:a.jsx(ks,{})}),a.jsx(fs,{className:"z-[110]",children:fO.map(h=>a.jsxs(Dt,{value:h.value,className:"text-[12.5px]",children:[h.flag,"  ",h.label,h.value===eb()&&a.jsx("span",{className:"ml-2 text-[10px] text-muted-foreground",children:"recommended"})]},h.value))})]})]})]}),a.jsxs("div",{className:"flex items-start gap-2 px-1",children:[a.jsx(el,{className:"w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0 mt-0.5"}),a.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:[a.jsx("span",{className:"text-foreground font-medium",children:"Included in your plan."})," Cloud + AI usage have free monthly allotments. Top up only if you scale beyond them. ",a.jsx("a",{href:"/pricing",target:"_blank",rel:"noreferrer",className:"text-primary hover:underline",children:"See limits →"})]})]})]}),a.jsxs("div",{className:"px-6 py-3 bg-secondary/30 border-t flex items-center justify-between gap-4 flex-wrap",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none text-[12px] text-muted-foreground hover:text-foreground transition-colors",children:[a.jsx(hO,{checked:o,onCheckedChange:h=>l(h===!0)}),"Always allow for new projects"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Q,{variant:"ghost",size:"sm",onClick:r,children:"Skip for now"}),a.jsxs(Q,{size:"sm",onClick:()=>t(s,o),className:"gap-1.5",children:[a.jsx(Dn,{className:"w-3.5 h-3.5"}),"Enable"]})]})]})]})})}const E2={auth:!0,storage:!0,edgeFunctions:!0,realtime:!0,database:!0};function mO(e){const[t,r]=m.useState(null),[n,s]=m.useState(!0),i=m.useCallback(async()=>{if(!e){r(null),s(!1);return}s(!0);const{data:d}=await G.from("project_cloud_config").select("*").eq("project_id",e).maybeSingle();if(d)r({...d,features:d.features||E2,env_vars:d.env_vars||{}});else{const{data:p}=await G.from("project_cloud_config").insert({project_id:e}).select().single();p&&r({...p,features:E2,env_vars:{}})}s(!1)},[e]);m.useEffect(()=>{i()},[i]);const o=m.useCallback(async d=>{if(!e||!t)return;const{data:p}=await G.from("project_cloud_config").update(d).eq("project_id",e).select().single();p&&r(h=>h?{...h,...p,features:p.features||h.features,env_vars:p.env_vars||h.env_vars}:null)},[e,t]),l=m.useCallback(async(d,p)=>{if(!t)return;const h={...t.features,[d]:p};await o({features:h})},[t,o]),c=m.useCallback(async(d,p)=>{if(!t)return;const h={...t.env_vars,[d]:p};await o({env_vars:h})},[t,o]),u=m.useCallback(async d=>{if(!t)return;const p={...t.env_vars};delete p[d],await o({env_vars:p})},[t,o]);return{config:t,loading:n,updateConfig:o,updateFeature:l,setEnvVar:c,removeEnvVar:u,refresh:i}}function BX(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1);m.useEffect(()=>{if(!e){r([]),s(!0);return}let c=!1;return(async()=>{const{data:d}=await G.from("project_memory").select("*").eq("project_id",e).order("created_at",{ascending:!1}).limit(30);!c&&d&&r(d.map(p=>({id:p.id,memory_type:p.memory_type,content:p.content,metadata:p.metadata||{},created_at:p.created_at}))),c||s(!0)})(),()=>{c=!0}},[e]);const i=m.useCallback(async(c,u,d)=>{var g;if(!e)return;const{data:p}=await G.auth.getUser(),h=(g=p==null?void 0:p.user)==null?void 0:g.id;if(!h)return;const f={project_id:e,user_id:h,memory_type:c,content:u,metadata:d||{}},{data:x}=await G.from("project_memory").insert(f).select().single();if(x){const y={id:x.id,memory_type:c,content:u,metadata:d||{},created_at:x.created_at};r(b=>[y,...b].slice(0,30))}},[e]),o=m.useCallback(()=>t.length===0?"":`
5982
5983--- PROJECT MEMORY (what was previously built) ---
5984${t.slice(0,10).map((d,p)=>{var f;const h=(f=d.metadata)!=null&&f.files_changed?` (files: ${d.metadata.files_changed.join(", ")})`:"";return`${p+1}. [${d.memory_type}] ${d.content}${h}`}).join(`
5985`)}
5986--- END MEMORY ---
5987Use this context to understand what already exists. Do NOT rebuild things that are already done. Build on top of previous work.`,[t]),l=m.useCallback(async(c,u,d)=>{const p=u.slice(0,10).join(", "),f=`Built: "${c.length>120?c.slice(0,120)+"…":c}" → Generated/updated ${u.length} file(s): ${p}`;await i("build_summary",f,{prompt:c.slice(0,500),files_changed:u.slice(0,20),model:d||"unknown",file_count:u.length})},[i]);return{memories:t,loaded:n,addMemory:i,getMemoryContext:o,saveBuildMemory:l}}const K1=[{id:"stripe",name:"Stripe",icon:"💳",category:"payments",description:"Payment processing, subscriptions, invoicing",docsUrl:"https://stripe.com/docs/api",secrets:[{key:"STRIPE_SECRET_KEY",label:"Secret Key",description:"Starts with sk_test_ or sk_live_",placeholder:"sk_test_...",docsUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",label:"Publishable Key",description:"Starts with pk_test_ or pk_live_",placeholder:"pk_test_...",required:!1}],endpoints:[{method:"POST",path:"/create-checkout",description:"Create Stripe Checkout session"},{method:"POST",path:"/create-payment-intent",description:"Create Payment Intent"},{method:"GET",path:"/products",description:"List Stripe products"}
5987,{method:"POST",path:"/webhook",description:"Handle Stripe webhooks"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
5988import Stripe from "https://esm.sh/[email protected]?target=deno";
5989
5990const corsHeaders = {
5991  "Access-Control-Allow-Origin": "*",
5992  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
5993};
5994
5995serve(async (req) => {
5996  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
5997
5998  const stripeKey = Deno.env.get("STRIPE_SECRET_KEY");
5999  if (!stripeKey) {
6000    return new Response(JSON.stringify({ error: "STRIPE_SECRET_KEY not configured" }), {
6001      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6002    });
6003  }
6004
6005  const stripe = new Stripe(stripeKey, { apiVersion: "2023-10-16" });
6006  const url = new URL(req.url);
6007  const action = url.searchParams.get("action") || "checkout";
6008
6009  try {
6010    if (action === "checkout") {
6011      const { items, success_url, cancel_url } = await req.json();
6012      const session = await stripe.checkout.sessions.create({
6013        payment_method_types: ["card"],
6014        line_items: items.map((item: any) => ({
6015          price_data: {
6016            currency: "usd",
6017            product_data: { name: item.name },
6018            unit_amount: Math.round(item.price * 100),
6019          },
6020          quantity: item.quantity || 1,
6021        })),
6022        mode: "payment",
6023        success_url: success_url || req.headers.get("origin") + "/success",
6024        cancel_url: cancel_url || req.headers.get("origin") + "/cart",
6025      });
6026      return new Response(JSON.stringify({ url: session.url, id: session.id }), {
6027        headers: { ...corsHeaders, "Content-Type": "application/json" },
6028      });
6029    }
6030
6031    if (action === "products") {
6032      const products = await stripe.products.list({ limit: 50, active: true });
6033      const prices = await stripe.prices.list({ limit: 50, active: true });
6034      return new Response(JSON.stringify({ products: products.data, prices: prices.data }), {
6035        headers: { ...corsHeaders, "Content-Type": "application/json" },
6036      });
6037    }
6038
6039    return new Response(JSON.stringify({ error: "Unknown action" }), {
6040      status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" },
6041    });
6042  } catch (err) {
6043    return new Response(JSON.stringify({ error: err.message }), {
6044      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6045    });
6046  }
6047});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6048
6049export async function createCheckout(items: { name: string; price: number; quantity: number }[]) {
6050  const { data, error } = await supabase.functions.invoke('stripe-connector', {
6051    body: { items, success_url: window.location.origin + '/success', cancel_url: window.location.origin + '/cart' },
6052  });
6053  if (error) throw error;
6054  if (data?.url) window.location.href = data.url;
6055  return data;
6056}`,mockData:{checkout:{url:"https://checkout.stripe.com/mock",id:"cs_test_mock"},products:[{id:"prod_1",name:"Pro Plan",description:"Full access",default_price:{unit_amount:2999,currency:"usd"}}]},setupSteps:["Go to https://dashboard.stripe.com/apikeys","Copy your Secret key (starts with sk_test_)","Paste it below"]},{id:"twilio",name:"Twilio",icon:"📱",category:"communication",description:"SMS, WhatsApp, voice calls",docsUrl:"https://www.twilio.com/docs",secrets:[{key:"TWILIO_ACCOUNT_SID",label:"Account SID",description:"Found on Twilio Console dashboard",placeholder:"AC..."},{key:"TWILIO_AUTH_TOKEN",label:"Auth Token",description:"Found on Twilio Console dashboard",placeholder:"your auth token"},{key:"TWILIO_PHONE_NUMBER",label:"Phone Number",description:"Your Twilio phone number",placeholder:"+1234567890"}],endpoints:[{method:"POST",path:"/send-sms",description:"Send SMS message"},{method:"POST",path:"/send-whatsapp",description:"Send WhatsApp message"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6057
6058const corsHeaders = {
6059  "Access-Control-Allow-Origin": "*",
6060  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6061};
6062
6063serve(async (req) => {
6064  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6065
6066  const accountSid = Deno.env.get("TWILIO_ACCOUNT_SID");
6067  const authToken = Deno.env.get("TWILIO_AUTH_TOKEN");
6068  const fromNumber = Deno.env.get("TWILIO_PHONE_NUMBER");
6069
6070  if (!accountSid || !authToken || !fromNumber) {
6071    return new Response(JSON.stringify({ error: "Twilio credentials not configured" }), {
6072      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6073    });
6074  }
6075
6076  try {
6077    const { to, body, channel } = await req.json();
6078    const isWhatsApp = channel === "whatsapp";
6079    const from = isWhatsApp ? "whatsapp:" + fromNumber : fromNumber;
6080    const toNum = isWhatsApp ? "whatsapp:" + to : to;
6081
6082    const twilioUrl = \`https://api.twilio.com/2010-04-01/Accounts/\${accountSid}/Messages.json\`;
6083    const params = new URLSearchParams({ To: toNum, From: from, Body: body });
6084
6085    const resp = await fetch(twilioUrl, {
6086      method: "POST",
6087      headers: {
6088        "Content-Type": "application/x-www-form-urlencoded",
6089        Authorization: "Basic " + btoa(accountSid + ":" + authToken),
6090      },
6091      body: params.toString(),
6092    });
6093
6094    const data = await resp.json();
6095    if (!resp.ok) throw new Error(data.message || "Twilio API error");
6096
6097    return new Response(JSON.stringify({ success: true, sid: data.sid }), {
6098      headers: { ...corsHeaders, "Content-Type": "application/json" },
6099    });
6100  } catch (err) {
6101    return new Response(JSON.stringify({ error: err.message }), {
6102      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6103    });
6104  }
6105});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6106
6107export async function sendSMS(to: string, body: string) {
6108  const { data, error } = await supabase.functions.invoke('twilio-connector', {
6109    body: { to, body, channel: 'sms' },
6110  });
6111  if (error) throw error;
6112  return data;
6113}
6114
6115export async function sendWhatsApp(to: string, body: string) {
6116  const { data, error } = await supabase.functions.invoke('twilio-connector', {
6117    body: { to, body, channel: 'whatsapp' },
6118  });
6119  if (error) throw error;
6120  return data;
6121}`,mockData:{sms:{success:!0,sid:"SM_mock_123"}},setupSteps:["Go to https://console.twilio.com","Copy Account SID and Auth Token from the dashboard","Get a phone number from Phone Numbers → Manage → Buy a number"]},{id:"sendgrid",name:"SendGrid",icon:"📧",category:"communication",description:"Transactional and marketing emails",docsUrl:"https://docs.sendgrid.com",secrets:[{key:"SENDGRID_API_KEY",label:"API Key",description:"Create at Settings → API Keys",placeholder:"SG.xxxxx",docsUrl:"https://app.sendgrid.com/settings/api_keys"},{key:"SENDGRID_FROM_EMAIL",label:"From Email",description:"Verified sender email",placeholder:"[email protected]",required:!1}],endpoints:[{method:"POST",path:"/send",description:"Send email"},{method:"POST",path:"/send-template",description:"Send templated email"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6122
6123const corsHeaders = {
6124  "Access-Control-Allow-Origin": "*",
6125  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6126};
6127
6128serve(async (req) => {
6129  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6130
6131  const apiKey = Deno.env.get("SENDGRID_API_KEY");
6132  const fromEmail = Deno.env.get("SENDGRID_FROM_EMAIL") || "[email protected]";
6133
6134  if (!apiKey) {
6135    return new Response(JSON.stringify({ error: "SENDGRID_API_KEY not configured" }), {
6136      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6137    });
6138  }
6139
6140  try {
6141    const { to, subject, html, text } = await req.json();
6142
6143    const resp = await fetch("https://api.sendgrid.com/v3/mail/send", {
6144      method: "POST",
6145      headers: {
6146        Authorization: "Bearer " + apiKey,
6147        "Content-Type": "application/json",
6148      },
6149      body: JSON.stringify({
6150        personalizations: [{ to: [{ email: to }] }],
6151        from: { email: fromEmail },
6152        subject,
6153        content: [
6154          ...(text ? [{ type: "text/plain", value: text }] : []),
6155          ...(html ? [{ type: "text/html", value: html }] : []),
6156        ],
6157      }),
6158    });
6159
6160    if (!resp.ok) {
6161      const err = await resp.text();
6162      throw new Error("SendGrid error: " + err);
6163    }
6164
6165    return new Response(JSON.stringify({ success: true }), {
6166      headers: { ...corsHeaders, "Content-Type": "application/json" },
6167    });
6168  } catch (err) {
6169    return new Response(JSON.stringify({ error: err.message }), {
6170      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6171    });
6172  }
6173});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6174
6175export async function sendEmail(to: string, subject: string, html: string) {
6176  const { data, error } = await supabase.functions.invoke('sendgrid-connector', {
6177    body: { to, subject, html },
6178  });
6179  if (error) throw error;
6180  return data;
6181}`,mockData:{send:{success:!0,messageId:"mock_msg_123"}},setupSteps:["Go to https://app.sendgrid.com/settings/api_keys",'Click "Create API Key" with Full Access',"Copy the key (starts with SG.)"]},{id:"telegram",name:"Telegram",icon:"✈️",category:"communication",description:"Bot messaging and notifications",docsUrl:"https://core.telegram.org/bots/api",secrets:[{key:"TELEGRAM_BOT_TOKEN",label:"Bot Token",description:"Get from @BotFather on Telegram",placeholder:"123456:ABC-DEF..."}],endpoints:[{method:"POST",path:"/send-message",description:"Send message to chat"}
6181,{method:"POST",path:"/set-webhook",description:"Set webhook URL"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6182
6183const corsHeaders = {
6184  "Access-Control-Allow-Origin": "*",
6185  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6186};
6187
6188serve(async (req) => {
6189  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6190
6191  const botToken = Deno.env.get("TELEGRAM_BOT_TOKEN");
6192  if (!botToken) {
6193    return new Response(JSON.stringify({ error: "TELEGRAM_BOT_TOKEN not configured" }), {
6194      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6195    });
6196  }
6197
6198  try {
6199    const { chat_id, text, parse_mode } = await req.json();
6200    const resp = await fetch(\`https://api.telegram.org/bot\${botToken}/sendMessage\`, {
6201      method: "POST",
6202      headers: { "Content-Type": "application/json" },
6203      body: JSON.stringify({ chat_id, text, parse_mode: parse_mode || "HTML" }),
6204    });
6205
6206    const data = await resp.json();
6207    if (!data.ok) throw new Error(data.description || "Telegram API error");
6208
6209    return new Response(JSON.stringify({ success: true, message_id: data.result.message_id }), {
6210      headers: { ...corsHeaders, "Content-Type": "application/json" },
6211    });
6212  } catch (err) {
6213    return new Response(JSON.stringify({ error: err.message }), {
6214      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6215    });
6216  }
6217});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6218
6219export async function sendTelegramMessage(chatId: string, text: string) {
6220  const { data, error } = await supabase.functions.invoke('telegram-connector', {
6221    body: { chat_id: chatId, text },
6222  });
6223  if (error) throw error;
6224  return data;
6225}`,mockData:{send:{success:!0,message_id:12345}},setupSteps:["Open Telegram and search for @BotFather","Send /newbot and follow prompts","Copy the bot token"]}
6225,{id:"slack",name:"Slack",icon:"💬",category:"communication",description:"Send messages and notifications to Slack channels",docsUrl:"https://api.slack.com/methods",secrets:[{key:"SLACK_BOT_TOKEN",label:"Bot Token",description:"OAuth token starting with xoxb-",placeholder:"xoxb-...",docsUrl:"https://api.slack.com/apps"}],endpoints:[{method:"POST",path:"/send-message",description:"Post message to channel"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6226
6227const corsHeaders = {
6228  "Access-Control-Allow-Origin": "*",
6229  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6230};
6231
6232serve(async (req) => {
6233  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6234
6235  const token = Deno.env.get("SLACK_BOT_TOKEN");
6236  if (!token) {
6237    return new Response(JSON.stringify({ error: "SLACK_BOT_TOKEN not configured" }), {
6238      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6239    });
6240  }
6241
6242  try {
6243    const { channel, text, blocks } = await req.json();
6244    const resp = await fetch("https://slack.com/api/chat.postMessage", {
6245      method: "POST",
6246      headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" },
6247      body: JSON.stringify({ channel, text, blocks }),
6248    });
6249
6250    const data = await resp.json();
6251    if (!data.ok) throw new Error(data.error || "Slack API error");
6252
6253    return new Response(JSON.stringify({ success: true, ts: data.ts }), {
6254      headers: { ...corsHeaders, "Content-Type": "application/json" },
6255    });
6256  } catch (err) {
6257    return new Response(JSON.stringify({ error: err.message }), {
6258      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6259    });
6260  }
6261});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6262
6263export async function sendSlackMessage(channel: string, text: string) {
6264  const { data, error } = await supabase.functions.invoke('slack-connector', {
6265    body: { channel, text },
6266  });
6267  if (error) throw error;
6268  return data;
6269}`,mockData:{send:{success:!0,ts:"1234567890.123456"}},setupSteps:["Go to https://api.slack.com/apps → Create New App","Add Bot Token Scopes: chat:write, channels:read","Install to workspace and copy the Bot User OAuth Token"]},{id:"resend",name:"Resend",icon:"✉️",category:"communication",description:"Modern email API for developers",docsUrl:"https://resend.com/docs",secrets:[{key:"RESEND_API_KEY",label:"API Key",description:"Get from Resend dashboard",placeholder:"re_xxxxx",docsUrl:"https://resend.com/api-keys"}],endpoints:[{method:"POST",path:"/send",description:"Send email via Resend"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6270
6271const corsHeaders = {
6272  "Access-Control-Allow-Origin": "*",
6273  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6274};
6275
6276serve(async (req) => {
6277  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6278
6279  const apiKey = Deno.env.get("RESEND_API_KEY");
6280  if (!apiKey) {
6281    return new Response(JSON.stringify({ error: "RESEND_API_KEY not configured" }), {
6282      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6283    });
6284  }
6285
6286  try {
6287    const { from, to, subject, html } = await req.json();
6288    const resp = await fetch("https://api.resend.com/emails", {
6289      method: "POST",
6290      headers: { Authorization: "Bearer " + apiKey, "Content-Type": "application/json" },
6291      body: JSON.stringify({ from: from || "[email protected]", to, subject, html }),
6292    });
6293
6294    const data = await resp.json();
6295    if (!resp.ok) throw new Error(JSON.stringify(data));
6296
6297    return new Response(JSON.stringify({ success: true, id: data.id }), {
6298      headers: { ...corsHeaders, "Content-Type": "application/json" },
6299    });
6300  } catch (err) {
6301    return new Response(JSON.stringify({ error: err.message }), {
6302      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6303    });
6304  }
6305});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6306
6307export async function sendEmail(to: string, subject: string, html: string) {
6308  const { data, error } = await supabase.functions.invoke('resend-connector', {
6309    body: { to, subject, html },
6310  });
6311  if (error) throw error;
6312  return data;
6313}`,mockData:{send:{success:!0,id:"mock_email_id"}},setupSteps:["Go to https://resend.com/api-keys","Create a new API key","Copy the key (starts with re_)"]},{id:"openai",name:"OpenAI",icon:"🤖",category:"ai",description:"GPT models for chat, completion, embeddings",docsUrl:"https://platform.openai.com/docs",secrets:[{key:"OPENAI_API_KEY",label:"API Key",description:"Get from platform.openai.com",placeholder:"sk-...",docsUrl:"https://platform.openai.com/api-keys"}],endpoints:[{method:"POST",path:"/chat",description:"Chat completion"},{method:"POST",path:"/embeddings",description:"Generate embeddings"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6314
6315const corsHeaders = {
6316  "Access-Control-Allow-Origin": "*",
6317  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6318};
6319
6320serve(async (req) => {
6321  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6322
6323  const apiKey = Deno.env.get("OPENAI_API_KEY");
6324  if (!apiKey) {
6325    return new Response(JSON.stringify({ error: "OPENAI_API_KEY not configured" }), {
6326      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6327    });
6328  }
6329
6330  try {
6331    const { messages, model, temperature } = await req.json();
6332    const resp = await fetch("https://api.openai.com/v1/chat/completions", {
6333      method: "POST",
6334      headers: { Authorization: "Bearer " + apiKey, "Content-Type": "application/json" },
6335      body: JSON.stringify({
6336        model: model || "gpt-4o-mini",
6337        messages,
6338        temperature: temperature ?? 0.7,
6339      }),
6340    });
6341
6342    const data = await resp.json();
6343    if (!resp.ok) throw new Error(data.error?.message || "OpenAI API error");
6344
6345    return new Response(JSON.stringify({ response: data.choices[0].message.content, usage: data.usage }), {
6346      headers: { ...corsHeaders, "Content-Type": "application/json" },
6347    });
6348  } catch (err) {
6349    return new Response(JSON.stringify({ error: err.message }), {
6350      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6351    });
6352  }
6353});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6354
6355export async function chatWithAI(messages: { role: string; content: string }[]) {
6356  const { data, error } = await supabase.functions.invoke('openai-connector', {
6357    body: { messages },
6358  });
6359  if (error) throw error;
6360  return data.response;
6361}`,mockData:{chat:{response:"This is a mock AI response.",usage:{total_tokens:50}}},setupSteps:["Go to https://platform.openai.com/api-keys","Create a new secret key","Copy and paste it below"]},{id:"google-maps",name:"Google Maps",icon:"🗺️",category:"data",description:"Maps, geocoding, places, directions",docsUrl:"https://developers.google.com/maps",secrets:[{key:"GOOGLE_MAPS_API_KEY",label:"API Key",description:"From Google Cloud Console",placeholder:"AIza...",docsUrl:"https://console.cloud.google.com/apis/credentials"}],endpoints:[{method:"GET",path:"/geocode",description:"Geocode address"},{method:"GET",path:"/places",description:"Search nearby places"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6362
6363const corsHeaders = {
6364  "Access-Control-Allow-Origin": "*",
6365  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6366};
6367
6368serve(async (req) => {
6369  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6370
6371  const apiKey = Deno.env.get("GOOGLE_MAPS_API_KEY");
6372  if (!apiKey) {
6373    return new Response(JSON.stringify({ error: "GOOGLE_MAPS_API_KEY not configured" }), {
6374      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6375    });
6376  }
6377
6378  try {
6379    const url = new URL(req.url);
6380    const action = url.searchParams.get("action") || "geocode";
6381    const address = url.searchParams.get("address") || "";
6382
6383    if (action === "geocode") {
6384      const resp = await fetch(\`https://maps.googleapis.com/maps/api/geocode/json?address=\${encodeURIComponent(address)}&key=\${apiKey}\`);
6385      const data = await resp.json();
6386      return new Response(JSON.stringify(data), {
6387        headers: { ...corsHeaders, "Content-Type": "application/json" },
6388      });
6389    }
6390
6391    return new Response(JSON.stringify({ error: "Unknown action" }), {
6392      status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" },
6393    });
6394  } catch (err) {
6395    return new Response(JSON.stringify({ error: err.message }), {
6396      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6397    });
6398  }
6399});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6400
6401export async function geocodeAddress(address: string) {
6402  const { data, error } = await supabase.functions.invoke('google-maps-connector?action=geocode&address=' + encodeURIComponent(address));
6403  if (error) throw error;
6404  return data;
6405}`,mockData:{geocode:{results:[{formatted_address:"1600 Amphitheatre Parkway",geometry:{location:{lat:37.42,lng:-122.08}}}]}},setupSteps:["Go to https://console.cloud.google.com/apis/credentials","Create an API key","Enable Maps JavaScript API, Geocoding API, Places API"]},{id:"webhooks",name:"Custom Webhook",icon:"🔗",category:"automation",description:"Send/receive data to any HTTP endpoint",docsUrl:"https://en.wikipedia.org/wiki/Webhook",secrets:[{key:"WEBHOOK_URL",label:"Webhook URL",description:"The endpoint to send data to",placeholder:"https://your-api.com/webhook"},{key:"WEBHOOK_SECRET",label:"Secret (optional)",description:"For HMAC signature verification",placeholder:"whsec_...",required:!1}],endpoints:[{method:"POST",path:"/send",description:"Send webhook payload"},{method:"POST",path:"/receive",description:"Receive incoming webhook"}],edgeFunctionTemplate:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
6406
6407const corsHeaders = {
6408  "Access-Control-Allow-Origin": "*",
6409  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
6410};
6411
6412serve(async (req) => {
6413  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
6414
6415  try {
6416    const { url, method, headers, body } = await req.json();
6417    const targetUrl = url || Deno.env.get("WEBHOOK_URL");
6418
6419    if (!targetUrl) {
6420      return new Response(JSON.stringify({ error: "No webhook URL provided" }), {
6421        status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" },
6422      });
6423    }
6424
6425    const resp = await fetch(targetUrl, {
6426      method: method || "POST",
6427      headers: { "Content-Type": "application/json", ...(headers || {}) },
6428      body: body ? JSON.stringify(body) : undefined,
6429    });
6430
6431    const data = await resp.text();
6432    return new Response(JSON.stringify({ status: resp.status, response: data }), {
6433      headers: { ...corsHeaders, "Content-Type": "application/json" },
6434    });
6435  } catch (err) {
6436    return new Response(JSON.stringify({ error: err.message }), {
6437      status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" },
6438    });
6439  }
6440});`,serviceTemplate:`import { supabase } from '@/integrations/supabase/client';
6441
6442export async function sendWebhook(url: string, payload: Record<string, unknown>) {
6443  const { data, error } = await supabase.functions.invoke('webhook-connector', {
6444    body: { url, body: payload },
6445  });
6446  if (error) throw error;
6447  return data;
6448}`,mockData:{send:{status:200,response:'{"ok":true}'}},setupSteps:["Enter your webhook endpoint URL","Optionally add a secret for signature verification"]}],Pf="[__substrate_deepen__]";async function Lo(){try{const{data:{session:e}}=await G.auth.getSession();return(e==null?void 0:e.access_token)||"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"}catch{return"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"}}async function UX(){var e;try{const{data:{session:t}}=await G.auth.getSession();return((e=t==null?void 0:t.user)==null?void 0:e.id)||null}catch{return null}}function I2(e){return!!(e.needsDatabase||e.needsAuth||e.needsApi||e.needsRealtime||e.needsFileStorage||e.needsBilling||e.strategy==="fullstack"||e.strategy==="api-service")}function zX(e){return/\b(curl|api|endpoint|webhook|fetch|axios|x-api-key|authorization:|bearer\s+|header|headers|post\s+|get\s+|put\s+|delete\s+|sendemail|send email)\b/i.test(e)}const qX=[{command:"/repair",title:"Repair current error",description:"Patch the failing file only, then validate.",icon:al,prompt:"Repair the current build/runtime error only. Inspect the failing file, imports, routes, and the exact error message. Make the smallest patch needed, do not redesign, do not rebuild unrelated files, then run validation."},{command:"/find",title:"Find in project",description:"Locate a feature, route, component, or bug source.",icon:ja,prompt:"Find where this is implemented: [describe what to find]. Inspect only the relevant files and reply with the exact file paths, current behavior, and the smallest recommended change before editing."},{command:"/explain",title:"Explain project",description:"Summarize routes, files, data flow, and risks.",icon:kh,prompt:"Explain the current project structure. Cover the main routes, important files, data/API/auth flow, what is wired, what is missing, and the safest next fixes. Do not edit files."},{command:"/test",title:"Test the app",description:"Run focused validation for the current surface.",icon:P6,prompt:"Test the current app surface. Run the fastest relevant checks first, inspect build/runtime errors, verify the active route, and summarize pass/fail with exact fixes needed. Only edit if a small repair is required."},{command:"/deploy",title:"Deploy check",description:"Inspect publish readiness and deployment blockers.",icon:Es,prompt:"Check deployment readiness. Inspect build config, env requirements, publish settings, route handling, and the latest deploy/build error. Fix only blockers that prevent publishing."},{command:"/security",title:"Security scan",description:"Look for exposed keys, unsafe APIs, auth gaps, CORS.",icon:os,prompt:"Run a focused security scan of this project. Check exposed secrets, unsafe frontend API keys, missing auth checks, weak RLS/API assumptions, CORS/preflight issues, and risky dependencies. Report issues first, then fix only high-confidence safe changes."},{command:"/review",title:"Code review",description:"Review recent changes for bugs and broken wiring.",icon:_$,prompt:"Review the current project like a senior engineer. Prioritize bugs, broken routes, missing imports, unhandled states, and build/deploy risks. Give file-specific findings first, then make the smallest safe fixes if the issue is clear."}];function HX(e){return(e||"mcp").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32)||"mcp"}function WX(e){if(!e.is_active||!e.url)return null;const t={};return e.auth_type==="bearer"&&e.auth_token?t.Authorization=`Bearer ${e.auth_token}`:e.auth_type==="api-key"&&e.auth_token&&(t["X-API-Key"]=e.auth_token),{name:HX(e.name),url:e.url,headers:Object.keys(t).length?t:void 0}}function VX(e,t){const r=e.toLowerCase(),n=new Set((t||[]).map(s=>s.toLowerCase()));return K1.filter(s=>{const i=s.id.toLowerCase(),o=s.name.toLowerCase(),l=i.replace(/-/g," ");return n.has(i)||n.has(o)||r.includes(o)||r.includes(l)})}function GX(e){const t=VX(e.text,e.classifierIntegrations).slice(0,3),r=/\bmcp\b|model context protocol/i.test(e.text);if(t.length===0&&e.mcpServers.length===0&&!r)return null;const n=[];if(t.length>0){const s=t.map(i=>i.name).join(", ");n.push(`🔌 Using ${s} (credentials stay server-side).`)}if(e.mcpServers.length>0){const s=e.mcpServers.map(i=>i.name).join(", ");n.push(`🧩 MCP tools active: ${s}.`)}else r&&n.push("🧩 MCP supported — add a server in the MCP tab.");return n.join(`
6449
6450`)}function O2(e){const t=e.trim().toLowerCase().replace(/[?!.,]+$/g,"");return!t||![/^(is it|is|it'?s|its|is this|are we|we are|you are)\s+(done|finished|complete|completed|ready)$/,/^(done|finished|complete|completed|ready|status)$/,/^(is|did)\s+(the\s+)?(build|deploy|deployment|publish|preview)\s+(done|finished|complete|working|ready|pass|passed)$/,/^(is|are|did|does)\s+(the\s+)?(email|emails|mail|contact\s+form|sales\s+form|form)\s+(work|working|send|sending|delivered|ready)$/,/^(email|emails|mail|contact\s+form|sales\s+form|form)\s+(is\s+)?(work|working|sending|ready)$/,/^(can|should)\s+i\s+(test|publish|deploy|try)(\s+now)?$/,/^(what'?s|what is)\s+(the\s+)?(status|state|issue|error)$/,/^why\s+(is|did)\s+(it|build|deploy|deployment|preview|publish)\s+(fail|failed|failing|stuck|not working)$/].some(n=>n.test(t))?!1:!/\b(add|create|make|fix|repair|change|update|wire|connect|integrate|implement|remove|redesign|style|deploy to|publish to|generate)\b/i.test(t)}function KX(e){const t=e.trim();return t?/^(BUILD TYPE:|USER REQUEST:|IMPLEMENT THIS NOW|PHASE CONTINUATION)/i.test(t)?!0:/\b(build|create|make|design|generate|add|implement|wire|connect|integrate|fix|repair|change|update|remove|redesign|style|deploy|publish|scaffold|clone)\b/i.test(t):!1}function YX(e){const t=e.lastBuildErrors.find(Boolean);if(e.isBuilding){const r=e.planSteps.filter(s=>s.status==="running").pop();return`Not done yet — a build is still running.${r?` Current step: **${r.title}**.`:""}
6451
6452You can keep viewing the last preview, but wait for the build to pass before publishing.`}return t?`Not fully done yet — the last build has an error.
6453
6454**Blocking issue:** \`${t.replace(/\s+/g," ").slice(0,220)}\`
6455
6456Use **Fix build** or ask me to “fix the build” and I’ll repair that exact file instead of rebuilding everything.`:e.filesCount>0?`No build is running right now. The project has **${e.filesCount} files** loaded.
6457
6458You can test the instant preview now. Before publish, export, or Git push, run **Build check** so Studio Jungle catches compile errors and offers a focused repair if needed.`:"Nothing is building right now, and I don’t see generated project files yet. Send what you want to create and I’ll start with a short plan before editing."}function JX(e){return/\b(design|style|ui|layout|responsive|mobile|desktop|polish|color|font|spacing|animation|navbar|hero|card|button|look|feel)\b/i.test(e)}function tb(e,t){return t==="api"?[{id:"smart-api-classify",title:"Classify API request",description:"Treat pasted URL/curl as functionality, not a design reference",status:"running"},{id:"smart-api-inspect",title:"Check existing form",description:"Find the page, submit handler, and existing edge functions",status:"pending"},{id:"smart-api-secure",title:"Secure server call",description:"Keep API keys out of frontend code",status:"pending"},{id:"smart-api-wire",title:"Wire UI states",description:"Add loading, success, and error behavior",status:"pending"}]:t==="design"?[{id:"smart-design-inspect",title:"Inspect current page",description:"Read the active page and shared design tokens",
6458status:"running"},{id:"smart-design-scope",title:"Scope visual changes",description:"Avoid duplicate pages and unrelated rewrites",status:"pending"},{id:"smart-design-apply",title:"Apply design update",description:"Patch the affected components only",status:"pending"},{id:"smart-design-check",title:"Check responsive fit",description:"Verify text, spacing, and route wiring",status:"pending"}]:[{id:"smart-edit-inspect",title:"Inspect relevant files",description:"Read only the files needed for this request",status:"running"},{id:"smart-edit-plan",title:"Choose smallest change",description:"Preserve existing pages and project structure",status:"pending"},{id:"smart-edit-apply",title:"Apply update",description:"Edit the requested area",status:"pending"},{id:"smart-edit-verify",title:"Verify result",description:"Run the right build or preview check",status:"pending"}]}const Ud={landing:[{label:"Add contact form",prompt:"Add a working contact form with name, email, and message fields that validates input and shows success feedback."},{label:"Add testimonials",prompt:"Add a testimonials section with customer quotes, star ratings, and profile photos."},{label:"Add blog section",prompt:"Add a blog listing page with articles, categories, and a featured post section."},{label:"Improve SEO",prompt:"Add proper meta tags, Open Graph, structured data, and semantic HTML for better SEO."}],ecommerce:[{label:"Add cart & checkout",prompt:"Add a shopping cart with add/remove items, quantity controls, and a checkout page with order summary."},{label:"Add product filters",prompt:"Add category filters, price range slider, and sort options to the product listing."},{label:"Add wishlist",prompt:"Add a wishlist feature where users can save products and view them later."},{label:"Add payment flow",prompt:"Add a Stripe-style payment form with card input, validation, and order confirmation."}],dashboard:[{label:"Add data export",prompt:"Add CSV and PDF export buttons for dashboard data and charts."},{label:"Add notifications",prompt:"Add a notification bell with real-time alerts, unread count, and a notification dropdown."},{label:"Add user settings",prompt:"Add a settings page with profile editing, password change, and notification preferences."},{label:"Add search & filters",prompt:"Add a global search bar and table filters with column sorting."}],auth:[{label:"Add social login",prompt:"Add Google and GitHub OAuth login buttons alongside email/password auth."},{label:"Add user roles",prompt:"Add role-based access control with admin and user roles and different dashboard views."},{label:"Add profile page",prompt:"Add a user profile page with avatar upload, bio editing, and account settings."},{label:"Add onboarding flow",prompt:"Add a multi-step onboarding wizard after signup to collect user preferences."}],portfolio:[{label:"Add project details",prompt:"Add individual project detail pages with image gallery, tech stack, and live demo links."},{label:"Add resume download",prompt:"Add a downloadable PDF resume button and an interactive timeline of experience."},{label:"Add client testimonials",prompt:"Add client testimonials with ratings and company logos."},{label:"Add blog",prompt:"Add a blog section with Markdown support, categories, and reading time estimates."}],hospitality:[{label:"Add booking flow",prompt:"Add a multi-step room booking flow with date picker, room selection, guest details, and confirmation with mock availability."},{label:"Add photo gallery",prompt:"Add a photo gallery page with lightbox viewer for rooms, dining, spa, and property grounds."},{label:"Add dining menu",prompt:"Add a dining/menu page with categorized dishes, prices, dietary tags, and reservation CTA."},{label:"Add scroll polish",prompt:"Add Framer Motion fade-in animations, parallax hero, and smoother hover transitions across sections."}],social:[{label:"Add messaging",prompt:"Add a real-time direct messaging system with conversation list and chat view."},{label:"Add stories",prompt:"Add a stories feature with image/video upload and auto-expire after 24 hours."},{label:"Add notifications",prompt:"Add push-style notifications for likes, follows, and comments with a bell icon."},{label:"Add explore page",prompt:"Add an explore/discover page with trending posts, suggested users, and hashtags."}],general:[{label:"Add dark mode",prompt:"Add a dark mode toggle with persistent theme switching."},{label:"Make responsive",prompt:"Make the entire app fully responsive for mobile, tablet, and desktop."},{label:"Add animations",prompt:"Add smooth page transitions and micro-interactions throughout the app."},{label:"Add loading states",prompt:"Add skeleton loaders, spinners, and smooth loading transitions for all data-driven sections."}]};function XX(e,t){var A,P;const r=e.filter(E=>E.role==="user").map(E=>E.content.toLowerCase()).join(" "),n=e.filter(E=>E.role==="ai").map(E=>E.content.toLowerCase()).join(" "),s=r+" "+n,o=(t||[]).flatMap(function E(_){const I=[_.name.toLowerCase()];return _.children&&I.push(..._.children.flatMap(E)),I}).join(" "),l=s.includes("login")||s.includes("signup")||o.includes("login")||o.includes("auth"),c=s.includes("dark mode")||o.includes("theme"),u=s.includes("cart")||s.includes("checkout")||o.includes("cart"),d=s.includes("profile page")||o.includes("profile"),p=s.includes("notification")||o.includes("notification"),h=s.includes("search bar")||s.includes("global search"),f=s.includes("responsive")||s.includes("mobile friendly"),x=s.includes("social login")||s.includes("google login")||s.includes("oauth"),g=s.includes("user roles")||s.includes("role-based"),y=s.includes("animation")||s.includes("framer"),b=s.includes("blog")||o.includes("blog"),v=s.includes("export")||s.includes("csv"),k=[{pool:"landing",score:["landing","hero","features","pricing","cta","homepage","website"].filter(E=>s.includes(E)).length},{pool:"ecommerce",score:["shop","store","product","cart","e-commerce","ecommerce","buy","price","catalog","order"].filter(E=>s.includes(E)).length},{pool:"dashboard",score:["dashboard","analytics","chart","kpi","metrics","admin panel","reports","data table"].filter(E=>s.includes(E)).length},{pool:"auth",score:["login","signup","sign up","auth","register","password","account"].filter(E=>s.includes(E)).length},{pool:"portfolio",score:["portfolio","personal site","resume","cv","projects showcase","about me","freelance"].filter(E=>s.includes(E)).length}
6458,{pool:"hospitality",score:["hotel","hospitality","restaurant","resort","boutique","dining","room","rooms","suite","booking","reservation","menu","chef","spa","stay","lodging","inn","bistro","cafe","olivewood"].filter(E=>s.includes(E)).length},{pool:"social",score:["social network","social app","feed","post","follow","like","comment","twitter","instagram"].filter(E=>s.includes(E)).length}];k.sort((E,_)=>_.score-E.score);const N=((A=k[0])==null?void 0:A.score)>0?k[0].pool:"general",j=[...Ud[N]],w=((P=k[1])==null?void 0:P.score)>0?k[1].pool:"general";if(w!==N&&w!=="general"){const E=Ud[w][Math.floor(Math.random()*Ud[w].length)];j.push(E)}if(N!=="general"){const E=Ud.general[Math.floor(Math.random()*Ud.general.length)];j.push(E)}const S=j.filter(E=>{const _=E.label.toLowerCase();return!(c&&_.includes("dark mode")||f&&_.includes("responsive")||y&&_.includes("animation")||l&&(_.includes("social login")||_.includes("onboarding"))&&x&&_.includes("social login")||x&&_.includes("social login")||g&&_.includes("user roles")||d&&_.includes("profile")||p&&_.includes("notification")||u&&(_.includes("cart")||_.includes("checkout"))||h&&_.includes("search")||b&&_.includes("blog")||v&&_.includes("export")||!l&&(_.includes("user roles")||_.includes("profile page")||_.includes("social login")))}),T=new Set;return S.filter(E=>T.has(E.label)?!1:(T.add(E.label),!0)).slice(0,4)}const ZX=[/^(?:make|change|set|update|edit|swap|replace|tweak|adjust|move|shift|shrink|grow|expand|enlarge|reduce|increase|decrease|bump|hide|show|remove|delete|drop|kill|cut|trim|polish|tidy|clean(?:\s*up)?|smaller|bigger|wider|taller|shorter|longer|lighter|darker|bolder|thinner|sharper|rounder|softer|brighter|dimmer|center(?:ed)?|left[-\s]?align|right[-\s]?align)\b/i,/^(?:fix|repair|debug|resolve|patch|address|solve)\b/i,/^(?:add|insert|append|include|create|put|place)\s+(?:a|an|the|some|one|two|three|four|five|more|another)?\s*(?:button|link|section|card|field|input|label|icon|image|logo|footer|header|nav(?:bar)?|menu|hero|heading|title|subtitle|paragraph|text|color|gradient|border|margin|padding|spacing|gap|row|column|grid|list|item|line|divider|badge|tag|chip|tooltip|popover|modal|dialog|alert|toast|notification|stat|metric|cta|emoji|animation|hover|shadow)/i,/\b(typo|spelling|spacing|alignment|font[-\s]*size|font[-\s]*weight|color|colour|hex|rgb|hsla?|padding|margin|gap|width|height)\b/i,/\b(slightly|a\s+bit|a\s+little|a\s+touch|just|only|simply|tiny|small)\b/i];function QX(e){const t=e.trim();return t.length>140?!1:ZX.some(r=>r.test(t))}function eZ(e,t){const r=e.trim();return r.length===0||/https?:\/\//i.test(r)||/PHASE CONTINUATION on an existing project|\*\*Next Phase:\*\*/i.test(r)?!1:!t&&/^BUILD TYPE:/i.test(r)||!t&&r.length<=400?!0:t?!!(QX(r)||r.length<=220):!1}function tZ(e){return e.shouldOrchestrate||e.isAutoFix||e.buildIncomplete||!e.isIncremental?!1:e.prompt.trim().length>500?!0:e.generatedFileCount>=12}const iu="/studio/billing",nZ=25;function rZ(e,t){return t?nZ:e==="claude-haiku-4-5"?1:e==="claude-fable-5"?60:e==="claude-opus-4-8"||e==="claude-opus-4-7"||e==="claude-opus-4-6"?30:5}function Af(e){if(e.noPlan)return`💳 **Credits required**
6459
6460You need at least **${Ts} credits** to start AI builds. I refreshed your balance before checking, but Studio Jungle still could not see enough available credits for this account.
6461
6462👉 [Top up credits](${iu})`;const t=Math.max(0,e.requiredCredits-e.balance);return`💳 **More credits needed**
6463
6464This build needs **${e.requiredCredits} credits**, but you have **${e.balance}**. Add **${t} more** or upgrade your plan, then run it again.
6465
6466👉 [Top up credits](${iu})`}function sZ(e){return!e||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(e>=10*1024*1024?0:1)} MB`}function aZ(e){var s,i,o,l;const t=e.join(`
6467`),r=(i=(s=t.match(/ROUTE_SCOPE:\s*([^\n]+)/))==null?void 0:s[1])==null?void 0:i.trim(),n=(l=(o=t.match(/LIKELY_PAGE_FILE:\s*([^\n]+)/))==null?void 0:o[1])==null?void 0:l.trim();return!r&&!n?null:{route:r,file:n}}const nb=1500;function iZ(e){const r=/PHASE\s*\d\s*[—–-]/i.test(e),n=e.length>nb;if(!r&&!n)return{hasPipeline:!1,isLong:!1,summary:e,full:e};if(r){const l=e.match(/((?:#{1,3}\s*)?(?:COMPLETION SUMMARY|✅\s*Build Complete)[\s\S]*$)/i);if(l)return{hasPipeline:!0,isLong:!0,summary:l[1].trim(),full:e}}const s=e.lastIndexOf(`
6468
6469`,nb),i=s>600?s:nb,o=e.slice(0,i).trimEnd();return{hasPipeline:r,isLong:!0,summary:o+`
6470
6471*...response truncated...*`,full:e}}
6471const oZ=[/^analyzing request$/i,/^understanding requirements(?: and planning)?$/i,/^(?:reading|opening|inspecting|reviewing|checking)\s+[`'"]?(?:[\w./-]+\.[a-z0-9]+|[\w./-]+\/[\w./-]+)[`'"]?$/i],lZ=[/\bfile inventory\b/i,/\bread_file\b/i,/\blist_files\b/i,/\bsandbox quirk\b/i,/\bvisible system prompt\b/i,/\bi have enough context\b/i,/\bproceed surgically\b/i,/\bexported hook shape\b/i];function cm(e){return e?e.split(/(```[\s\S]*?```)/g).map(n=>n.startsWith("```")?n:n.split(/\n\s*\n/).map(o=>{const u=o.split(`
6472`).filter(d=>{const p=d.trim();return p?!oZ.some(h=>h.test(p)):!0}).join(`
6473`).trim();return!u||lZ.some(d=>d.test(u))?"":u}).filter(Boolean).join(`
6474
6475`)).join("").replace(/[ \t]+\n/g,`
6476`).replace(/\n{3,}/g,`
6477
6478`).trim():""}const cZ=L("max-w-none text-[13px] leading-[1.6] text-secondary-foreground","[&>*:first-child]:mt-0 [&>*:last-child]:mb-0","[&_p]:my-2 [&_p]:text-[13px] [&_p]:leading-[1.6]","[&_h1]:mt-3 [&_h1]:mb-2 [&_h1]:text-[16px] [&_h1]:font-semibold [&_h1]:tracking-normal [&_h1]:text-foreground","[&_h2]:mt-3.5 [&_h2]:mb-2 [&_h2]:text-[14px] [&_h2]:font-semibold [&_h2]:tracking-normal [&_h2]:text-foreground","[&_h3]:mt-3 [&_h3]:mb-1.5 [&_h3]:text-[13px] [&_h3]:font-semibold [&_h3]:text-foreground","[&_ul]:my-2 [&_ul]:space-y-1.5 [&_ul]:pl-0 [&_ol]:my-2 [&_ol]:space-y-1.5 [&_ol]:pl-0","[&_li]:relative [&_li]:ml-4 [&_li]:pl-1.5 [&_li]:text-[13px] [&_li]:leading-[1.55]","[&_ul>li]:list-disc [&_ol>li]:list-decimal","[&_strong]:font-semibold [&_strong]:text-foreground","[&_em]:text-muted-foreground","[&_a]:font-medium [&_a]:text-primary [&_a]:no-underline hover:[&_a]:underline","[&_hr]:my-3 [&_hr]:border-border/60","[&_blockquote]:my-3 [&_blockquote]:rounded-r-lg [&_blockquote]:border-l-2 [&_blockquote]:border-l-primary/50 [&_blockquote]:bg-primary/[0.04] [&_blockquote]:px-3 [&_blockquote]:py-2 [&_blockquote]:text-muted-foreground","[&_pre]:my-3 [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_pre]:rounded-lg [&_pre]:border [&_pre]:border-border/60 [&_pre]:bg-background/80 [&_pre]:p-3 [&_pre]:text-[12px] [&_pre]:leading-[1.55] [&_pre]:shadow-sm","[&_code]:rounded-md [&_code]:bg-background/80 [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[11.5px] [&_code]:text-foreground [&_code]:ring-1 [&_code]:ring-border/50","[&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-[12px] [&_pre_code]:ring-0","[&_table]:my-3 [&_table]:block [&_table]:w-full [&_table]:overflow-x-auto [&_table]:rounded-lg [&_table]:border [&_table]:border-border/60 [&_table]:text-[12px]","[&_thead]:bg-background/70 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_th]:font-semibold [&_th]:text-foreground","[&_td]:border-t [&_td]:border-border/50 [&_td]:px-3 [&_td]:py-2");function uZ(e,t){const r=e.trim();if(!r||!t||r.length<=700)return r;const n=r.split(`
6479`).map(o=>o.trim()).filter(Boolean).filter(o=>!/^#{1,6}\s*what'?s next/i.test(o)).filter(o=>!/^next phase$/i.test(o)),s=n.find(o=>!/^[-*]\s/.test(o))||n[0]||"";if(!s)return"";const i=s.replace(/^#{1,6}\s*/,"").replace(/^✅\s*/,"").trim();return i.length>260?`${i.slice(0,257).trim()}...`:i}function dZ({content:e,onQuestionSubmit:t,onSchemaApprove:r,onSchemaReject:n,schemaStatuses:s,isLastAiMessage:i,onSecretsSaved:o,projectId:l,onContinueBuild:c,onRetry:u}){var ne,oe;const d=zE(e),p=d?G9(e):e,h=cm(p),{cleaned:f,files:x}=nF(h),g=kK(h),y=DK(h),b=$K(h),v=BK(h),k=y?MK(f):f,N=b?FK(k):k,j=v?UK(N):N,A=uZ(g?SK(j):j,g).replace(/<\/?(?:div|section|header|footer|nav|main|aside|article|span|p|h[1-6]|ul|ol|li|a|img|button|form|input|textarea|select|option|table|tr|td|th|thead|tbody|label|html|head|body|meta|link|script|style|svg|path|circle|rect|noscript)\b[^>]*>/gi,"").replace(/(?:^|\n)\s*(?:[\w.#\-\[\]:,\s>+~]+\{[^}]*\}\s*)+/g,`
6480`).replace(/^((?:const|let|var|export)\s+\w+\s*=\s*\{[\s\S]*?\};?\s*)$/gm,"\n```javascript\n$1\n```\n").replace(new RegExp("(?<=\\n|^)(\\w+:\\s*\\{[^}]*(?:'(?:GET|POST|PUT|DELETE|PATCH)\\s+\\/[^']*'[^}]*)+\\}[,;]?\\s*)+","g"),"\n```javascript\n$&\n```\n").replace(/\[\[SECRET:([A-Z0-9_]+)\]\]/g,"`🔒 $1`").replace(/\[\[__SJ_REFUND:\d+:[a-z_]+__\]\]/g,""),[P,E]=m.useState(!1),[_,I
6480]=m.useState(!1),{hasPipeline:D,isLong:M,summary:B,full:$}=iZ(A),K=D||M,R=K?_?$:B:A,Y=he=>{E(!0),t==null||t(he)},Z=((oe=(ne=y==null?void 0:y.tables)==null?void 0:ne[0])==null?void 0:oe.tableName)||"",O=(s==null?void 0:s.get(Z))||"pending";return a.jsxs("div",{className:L(d&&"pl-3 border-l-2 border-l-destructive/50 -ml-1"),children:[R&&a.jsx("div",{className:cZ,children:a.jsx(oV,{remarkPlugins:[vK],children:R})}),d&&i&&u&&a.jsxs("div",{className:"mt-2.5 flex items-center gap-2",children:[a.jsxs("button",{onClick:u,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11.5px] font-medium bg-destructive/10 text-destructive border border-destructive/20 hover:bg-destructive/15 transition-colors",children:[a.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),a.jsx("path",{d:"M3 3v5h5"})]}),"Retry"]}),a.jsx("span",{className:"text-[10.5px] text-muted-foreground",children:"Reformulates + escalates to a stronger model"})]}),K&&a.jsx("button",{onClick:()=>I(!_),className:"mt-2 flex items-center gap-1.5 text-[11px] font-medium text-primary hover:text-primary/80 transition-colors",children:_?a.jsxs(a.Fragment,{children:[a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m18 15-6-6-6 6"})}),D?"Show Summary":"Show Less"]}):a.jsxs(a.Fragment,{children:[a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m6 9 6 6 6-6"})}),D?"Show Full Response":"Show More"]})}),y&&i&&a.jsx("div",{className:"mt-3",children:a.jsx(kJ,{proposal:y,onApprove:()=>r==null?void 0:r(y),onReject:()=>n==null?void 0:n(y),status:O})}),b&&i&&a.jsx(SJ,{request:b,projectId:l||null,onComplete:he=>o==null?void 0:o(he)}),g&&i&&a.jsx("div",{className:"mt-3",children:a.jsx(_K,{data:g,onSubmit:Y,isSubmitted:P})}),v&&i&&a.jsx("div",{className:"mt-3 rounded-xl border border-primary/30 bg-primary/5 p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/15 text-primary",children:"⏸"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("div",{className:"text-sm font-semibold text-foreground",children:"Build paused at checkpoint"}),a.jsx("div",{className:"mt-1 text-xs text-muted-foreground whitespace-pre-wrap",children:v.message}),v.completed.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsxs("div",{className:"text-[11px] font-medium text-green-700 dark:text-green-400",children:["✓ Completed (",v.completed.length,")"]}),a.jsx("ul",{className:"mt-1 list-inside list-disc text-[11px] text-muted-foreground",children:v.completed.slice(0,8).map((he,ae)=>a.jsx("li",{children:he},ae))})]}),v.remaining.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsxs("div",{className:"text-[11px] font-medium text-amber-700 dark:text-amber-400",children:["⏳ Remaining (",v.remaining.length,")"]}),a.jsx("ul",{className:"mt-1 list-inside list-disc text-[11px] text-muted-foreground",children:v.remaining.slice(0,8).map((he,ae)=>a.jsx("li",{children:he},ae))})]}),a.jsxs("div",{className:"mt-3 flex gap-2",children:[a.jsx("button",{onClick:()=>c==null?void 0:c(v),className:"rounded-lg bg-primary px-4 py-2 text-xs font-semibold text-primary-foreground shadow-sm hover:bg-primary/90 transition",children:"▶ Continue building"}),a.jsx("button",{onClick:()=>{},className:"rounded-lg border border-border px-4 py-2 text-xs font-medium text-foreground hover:bg-muted transition",children:"Stop here"})]})]})]})})]})}function pZ({planSteps:e}){const[t,r]=m.useState(!1),[n,s]=m.useState(()=>Date.now()),{liveStatus:i,toolCallHistory:o,isMultiAgentRun:l,currentAgent:c,messages:u}=gn(),d=m.useMemo(()=>{for(let P=u.length-1;P>=0;P--){const E=u[P];if(E.role==="user"&&E.content)return XI(E.content)}return null},[u]),p=e.filter(P=>P.status==="running").pop(),h=e.filter(P=>P.status==="done");e.filter(P=>P.status==="error"),e.filter(P=>P.status==="pending");const f=e.some(P=>P.id.startsWith("smart-")),x=e.some(P=>P.id.startsWith("smart-fix-")),g=e.some(P=>P.id.startsWith("db-")),y=(p==null?void 0:p.id)==="analyze",b=(p==null?void 0:p.id)==="db-followup"||e.some(P=>P.id.startsWith("gen-")),v=o[o.length-1],k=(v==null?void 0:v.startedAt)||Number(String((v==null?void 0:v.id)||"").split("-")[0])||n,N=(v==null?void 0:v.status)==="running"?n-k:0,j=!!v&&v.status==="running"&&N>12e3&&/^(Reading|Inspecting|Scanning|Updating)\b/i.test(v.label);m.useEffect(()=>{if(!v||v.status!=="running")return;const P=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(P)},[v==null?void 0:v.id,v==null?void 0:v.status]);let S=d?`Building ${d}`:"Building application",T="Building your changes";x?(S="Fixing issue",T="Applying a targeted fix"):f?(S="Editing",T=j?"Working on your changes":i||"Updating your app"):y?(S="Building",T="Preparing your app"):g&&!b?(S="Setting up database",T="Configuring your backend"):b&&(S=d?`Building ${d}`:"Building your app",T=`${h.filter(P=>P.id.startsWith("gen-")).length} files ready`);const C=m.useMemo(()=>{var B;const P=[];if(o.length>0){const $=o.slice(-6);for(const K of $){const R=K.startedAt||Number(String(K.id||"").split("-")[0])||n,Y=K.status==="running"&&n-R>12e3&&/^(Reading|Inspecting|Scanning|Updating)\b/i.test(K.label);P.push({label:K.label,status:Y?"done":K.status})}return P.some(K=>
6480K.status==="running")||P.push({label:"Thinking through the next edit",status:"running"}),P}if(f){for(const $ of e)P.push({label:$.title,status:$.status});return P}const E=e.filter($=>$.id.startsWith("db-create-")),_=e.find($=>$.id==="db-seed"),I=e.find($=>$.id==="db-approve"),D=e.filter($=>$.id.startsWith("gen-")),M=e.filter($=>$.id.startsWith("phase-"));if(M.length>0)for(const $ of M)P.push({label:$.title,status:$.status});else{if(y||e.find($=>$.id==="analyze")){const $=e.find(K=>K.id==="analyze");P.push({label:"Analyze requirements",status:($==null?void 0:$.status)||"pending"})}if((I||E.length>0)&&P.push({label:"Create database schema",status:E.length>0?E.every($=>$.status==="done")?"done":E.some($=>$.status==="error")?"error":"running":"pending"}),_&&P.push({label:"Seed sample data",status:_.status}),D.length>0||e.find($=>$.id==="db-followup")){const $=D.length>0&&D.every(R=>R.status==="done"),K=D.some(R=>R.status==="running")||((B=e.find(R=>R.id==="db-followup"))==null?void 0:B.status)==="running";P.push({label:"Generate UI components",status:$?"done":K?"running":"pending"})}e.some($=>$.title.toLowerCase().includes("auth"))&&P.push({label:"Add authentication flow",status:"pending"}),D.length>0&&E.length>0&&(P.push({label:"Connect UI to database",status:D.every($=>$.status==="done")?"done":"pending"}),P.push({label:"Add CRUD operations",status:D.every($=>$.status==="done")?"done":"pending"}))}return P.length===0&&P.push({label:"Processing request",status:"running"}),P},[e,y,f,o,n]),A=m.useMemo(()=>{if(!l)return null;const P={planner:[],architect:[],builder:[],reviewer:[],tester:[]};for(const E of o){const _=(E.agent||"").toLowerCase();_&&P[_]&&P[_].push(E)}return P},[l,o]);return a.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[a.jsxs("button",{onClick:()=>r(!t),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-muted/30 transition-colors text-left",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:S}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:T})]}),a.jsx(ia,{className:L("w-4 h-4 text-muted-foreground transition-transform",t&&"rotate-90")})]}),A&&a.jsx("div",{className:"border-t bg-muted/10 grid grid-cols-3 gap-px",children:["planner","builder","reviewer"].map(P=>{const E=A[P],_=P==="planner"?A.architect:P==="reviewer"?A.tester:[],I=[...E,..._],D=(c||"").toLowerCase()===P||P==="planner"&&c==="architect"||P==="reviewer"&&c==="tester",M={planner:"Planner",builder:"Builder",reviewer:"Reviewer"};return a.jsxs("div",{className:L("px-3 py-2 bg-card",D&&"bg-primary/5"),children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[a.jsx("div",{className:L("w-1.5 h-1.5 rounded-full",D?"bg-primary animate-pulse":I.length>0?"bg-emerald-500":"bg-muted-foreground/30")}),a.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-wider text-muted-foreground",children:M[P]})]}),a.jsx("div",{className:"space-y-1",children:I.length===0?a.jsx("div",{className:"text-[10.5px] text-muted-foreground/60 italic",children:D?"starting…":"pending"}):I.slice(-5).map(B=>a.jsxs("div",{className:L("text-[10.5px] truncate flex items-center gap-1",B.status==="running"?"text-foreground font-medium":"text-muted-foreground"),title:B.label,children:[B.status==="running"?a.jsx(ze,{className:"w-2.5 h-2.5 animate-spin shrink-0"}):a.jsx(mn,{className:"w-2.5 h-2.5 text-emerald-500 shrink-0"}),a.jsx("span",{className:"truncate",children:B.label})]},B.id))})]},P)})}),a.jsx("div",{className:L("border-t px-4 py-3 space-y-2.5",!t&&"block"),children:C.map((P,E)=>a.jsxs("div",{className:"flex items-center gap-2.5",children:[P.status==="running"?a.jsx(ze,{className:"w-4 h-4 text-muted-foreground animate-spin shrink-0"}):P.status==="done"?a.jsx(mn,{className:"w-4 h-4 text-primary shrink-0"}):P.status==="error"?a.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-destructive shrink-0 flex items-center justify-center",children:a.jsx(qn,{className:"w-2.5 h-2.5 text-destructive"})}):a.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-muted-foreground
6480/30 shrink-0"}),a.jsx("span",{className:L("text-sm",P.status==="done"?"text-foreground":P.status==="running"?"text-foreground font-medium":"text-muted-foreground"),children:P.label})]},E))})]})}function hZ({message:e}){const[t,r]=m.useState(!1),n=e.durationMs,s=(()=>{if(!n||n<0)return null;if(n<1e3)return`${n} ms`;const o=Math.round(n/1e3);if(o<60)return`${o} s`;const l=Math.floor(o/60),c=o%60;return c===0?`${l} min`:`${l}m ${c}s`})(),i=e.createdAt?new Date(e.createdAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;return a.jsxs("div",{className:"relative inline-block",children:[a.jsx("button",{type:"button",onClick:()=>r(o=>!o),className:"p-1 rounded text-muted-foreground/60 hover:text-foreground hover:bg-secondary transition-colors",title:"Message actions","aria-label":"Message actions",children:a.jsx(Cw,{className:"w-3.5 h-3.5"})}),t&&a.jsxs("div",{className:"absolute z-50 mt-1 right-0 min-w-[220px] rounded-lg border bg-card shadow-lg p-1 text-xs",onMouseLeave:()=>r(!1),children:[a.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(e.content||""),W.success("Copied to clipboard"),r(!1)},className:"w-full flex items-center gap-2 px-2.5 py-1.5 rounded hover:bg-secondary transition-colors",children:[a.jsx(gs,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-foreground",children:"Copy message"})]}),a.jsx("div",{className:"my-1 border-t"}),s&&a.jsxs("div",{className:"px-2.5 py-1.5 flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-muted-foreground",children:"Worked for"}),a.jsx("span",{className:"font-mono text-foreground",children:s})]}),i&&a.jsxs("div",{className:"px-2.5 py-1.5 flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-muted-foreground",children:"Sent at"}),a.jsx("span",{className:"font-mono text-foreground",children:i})]}),typeof e.creditsUsed=="number"&&a.jsxs("div",{className:"px-2.5 py-1.5 flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-muted-foreground",children:"Credits used"}),a.jsx("span",{className:"font-mono text-foreground",children:e.creditsUsed.toFixed(2)})]})]})]})}function fZ({tools:e}){const[t,r]=m.useState(!1),n=t?e:e.slice(0,4);return a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex flex-wrap gap-1",children:[n.map(s=>a.jsxs("span",{className:L("inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md border text-[9px] font-medium",s.color),title:s.description,children:[a.jsx("span",{children:s.icon}),s.name]},s.id)),!t&&e.length>4&&a.jsxs("button",{onClick:()=>r(!0),className:"text-[9px] px-1.5 py-0.5 rounded-md bg-secondary border text-muted-foreground hover:text-foreground transition-colors",children:["+",e.length-4," more"]})]}),t&&e.length>4&&a.jsx("button",{onClick:()=>r(!1),className:"text-[9px] text-muted-foreground hover:text-foreground",children:"Show less"})]})}async function mZ(e,t,r,n,s){var l,c,u,d;const i="ai-test";if(t.some(p=>p.id===i))return{triggeredRepair:!1};const o=e.filter(p=>p.content&&p.name).slice(0,15).map(p=>`### ${p.name}
6481\`\`\`
6482${(p.content||"").slice(0,400)}
6483\`\`\``).join(`
6484
6485`);if(!o)return{triggeredRepair:!1};n(p=>[...p,{id:i,title:"AI Testing",description:"Running automated code review…",status:"running",logs:["Sending code to AI reviewer…"]}]);try{const p=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},body:JSON.stringify({messages:[{role:"system",content:`You are a senior code reviewer. Review the generated code for:
64861. Syntax errors or broken imports
64872. Missing event handlers or broken links (href="#")
64883. Hardcoded credentials or security issues
64894. UI elements that won't render (missing closing tags, wrong component names)
64905. Functions called but never defined
6491
6492Respond with ONLY a short JSON object (no markdown):
6493{"pass":true/false,"issues":["issue 1","issue 2"],"summary":"one-line verdict"}
6494If everything looks good, return {"pass":true,"issues":[],"summary":"All files look clean — no issues detected."}
6495Max 5 issues. Be concise.`},{role:"user",content:`Review these generated files:
6496
6497${o}`}],mode:"app-builder",provider:"gemini-2.5-flash",model:"gemini-2.5-flash"})});if(!p.ok)return n(b=>b.map(v=>v.id===i?{...v,status:"done",description:"Skipped — reviewer unavailable",logs:["AI reviewer returned an error, skipping test."]}:v)),{triggeredRepair:!1};const h=(l=p.body)==null?void 0:l.getReader();if(!h)return{triggeredRepair:!1};const f=new TextDecoder;let x="";for(;;){const{done:b,value:v}=await h.read();if(b)break;const k=f.decode(v,{stream:!0});for(const N of k.split(`
6498`)){if(!N.startsWith("data: "))continue;const j=N.slice(6).trim();if(j!=="[DONE]")try{const S=(d=(u=(c=JSON.parse(j).choices)==null?void 0:c[0])==null?void 0:u.delta)==null?void 0:d.content;S&&(x+=S)}catch{}}}let g={pass:!0,issues:[],summary:"Review complete."};try{const b=x.replace(/```json\s*/g,"").replace(/```/g,"").trim();g=JSON.parse(b)}catch{g={pass:!0,issues:[],summary:x.slice(0,200)||"Review complete."}}const y=g.issues.length>0?g.issues.map((b,v)=>`⚠️ ${v+1}. ${b}`):["✅ No issues found"];if(n(b=>b.map(v=>v.id===i?{...v,status:g.pass?"done":"error",description:g.summary,logs:y}:v)),!g.pass&&g.issues.length>0){const b=g.issues.map((v,k)=>`${k+1}. ${v}`).join(`
6499`);return r("ai",`🧪 **AI Test Results**
6500
6501${g.summary}
6502
6503**Issues found:**
6504${b}
6505
6506🔧 Running a focused repair pass for the issues above…`),s==null||s(g.issues),{triggeredRepair:!0}}return{triggeredRepair:!1}}catch(p){return console.warn("AI post-build test failed (non-critical):",p),n(h=>h.map(f=>f.id===i?{...f,status:"done",description:"Skipped — network error",logs:[`Could not reach reviewer: ${p.message}`]}:f)),{triggeredRepair:!1}}}function gO(e){var s;if(!e)return!0;
6506if(e.length<50){const i=e.trim();return!(i.length>0&&!i.endsWith("{")&&!i.endsWith("("))}const t=e.trimEnd();if(t.endsWith("[... trimmed for context limit ...]")||t.endsWith("// ...")||t.endsWith("/* ... */")||(t.includes("<!DOCTYPE")||t.includes("<html"))&&!t.includes("</html>")&&!t.includes("</body>"))return!0;const r=((s=t.split(`
6507`).pop())==null?void 0:s.trim())||"";return!!(t.split(`
6508`).length>10&&(r.endsWith("{")||r.endsWith("(")))}function R2(e,t){var n;const r=((n=e.split(".").pop())==null?void 0:n.toLowerCase())||"";if(!["tsx","ts","jsx","js"].includes(r))return!0;if(gO(t))return!1;try{return RI(t,{sourceType:"module",plugins:["jsx","typescript"],errorRecovery:!1}),!0}catch{return!1}}function $l(e,t){const r=new Map;for(const o of e)r.set(o.name,o);const n=t.map(o=>{if(o.type==="file"&&o.content){const l=r.get(o.name);if((l==null?void 0:l.type)==="file"&&l.content&&gO(o.content)&&o.content.length<l.content.length*.5)return console.warn(`[merge] Skipping truncated file: ${o.name} (${o.content.length} chars vs ${l.content.length} old)`),l}return o}),s=[...n],i=new Map(n.map(o=>[o.name,o]));for(const o of e){const l=i.get(o.name);if(!l){s.push(o);continue}if(o.type==="folder"&&l.type==="folder"){const c=s.indexOf(l);s[c]={...l,children:$l(o.children||[],l.children||[])}}}return s.sort((o,l)=>o.type!==l.type?o.type==="folder"?-1:1:o.name.localeCompare(l.name))}function Y1(e){return e.length===0?null:[...e].sort((r,n)=>{const s=i=>{let o=0;const l=(i.id||"").toLowerCase(),c=(i.filename||"").toLowerCase(),u=(i.name||"").toLowerCase(),d=(i.html||"").toLowerCase();return l==="/"&&(o+=100),(/home|landing/.test(c)||/home|landing/.test(u))&&(o+=60),(c.includes("app.tsx")||c.includes("homepage")||c.includes("landing"))&&(o+=40),d.includes("<body")&&(o+=10),(d.includes("react root")||d.includes('id="root"')||d.includes("id='root'"))&&(o-=80),o};return s(n)-s(r)})[0]||null}function gZ(e,t){const r=e.toLowerCase(),n=Zr(t).map(s=>s.path.toLowerCase()).join(`
6509`);return!!(/billing/.test(r)&&/billing/.test(n)||/dashboard/.test(r)&&/dashboard/.test(n)||/habit/.test(r)&&/habit/.test(n)||/(login|sign.?up|auth)/.test(r)&&/(login|signup|auth)/.test(n))}function Zr(e,t=""){return e.flatMap(r=>{var s;const n=t?`${t}/${r.name}`:r.name;if(r.type==="file"&&r.content){const i=n.includes(".")&&((s=n.split(".").pop())==null?void 0:s.toLowerCase())||"text",o=i==="htm"?"html":i;return[{path:n,content:r.content,language:o}]}return r.type==="folder"&&r.children?Zr(r.children,n):[]})}function $o(e){return e.map(t=>t.type==="folder"?{...t,children:$o(t.children||[])}:{...t})}function Lm(e){return e.replace(/^\/+/,"").replace(/\\/g,"/").trim()}function Bp(e,t,r=""){const n=Lm(t);for(const s of e){const i=r?`${r}/${s.name}`:s.name;if(s.type==="file"&&i===n)return s.content??"";if(s.type==="folder"&&s.children){const o=Bp(s.children,n,i);if(o!==null)return o}}return null}function E0(e,t,r){var o;const n=Lm(t);if(!n)return e;const s=n.includes(".")&&((o=n.split(".").pop())==null?void 0:o.toLowerCase())||"text";return $l(e,Mo([{filename:n,language:s==="htm"?"html":s,content:r}]))}function xZ(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function tu(e){const t=Bp(e,"src/main.tsx"),r=Bp(e,"src/App.tsx");if(!t||r!==null||!/from\s+['"]\.\/App['"]/i.test(t))return e;const s=Zr(e).map(u=>({filename:u.path,language:u.language,content:u.content})),i=id(s),o=i.length>0?Y1(i)||i[0]:null,l=o==null?void 0:o.html,c=l?`const previewHtml = String.raw\`${xZ(l)}\`;
6510
6511export default function App() {
6512  return (
6513    <iframe
6514      title="Studio Jungle generated preview"
6515      srcDoc={previewHtml}
6516      className="min-h-screen w-full border-0 bg-white"
6517    />
6518  );
6519}
6520`:`export default function App() {
6521  return (
6522    <main className="min-h-screen bg-slate-50 p-8 text-slate-950">
6523      <h1 className="text-3xl font-bold">Generated app</h1>
6524      <p className="mt-2 text-slate-600">Studio Jungle is finishing this app shell.</p>
6525    </main>
6526  );
6527}
6528`;return E0(e,"src/App.tsx",c)}function _f(e){const t=tu(e),r=Zr(t),n=r.map(o=>({filename:o.path,language:o.language,content:o.content})),s=id(n),i=s.length>0?Y1(s)||s[0]:null;return{flatFiles:r,parsedBlocks:n,pages:s,preferredPage:i,apis:tp(n),schema:np(n)}}function nu(e,t){return e.length>t?`${e.slice(0,t)}
6529... [truncated]`:e}function yZ(e,t){var r;return((r=Zr(e).find(n=>n.path===t))==null?void 0:r.content)||""}function bZ(e){const r=Zr(e.existingFiles).filter(s=>Ul(s.path)).map(s=>s.path),n=r.filter(s=>{const i=`${e.userText} ${s}`.toLowerCase();return/app\.tsx|router|route|nav|home|index|page|component|style|css|auth|login|signup|pricing|billing|stripe|supabase|github|deploy|cloud/.test(i)}).slice(0,12);return`# Current plan
6530
6531Updated: ${new Date().toISOString()}
6532
6533## User request
6534${e.userText}
6535
6536## Detected intent
6537- Strategy: ${e.strategy}
6538- Domain: ${e.classification.domain||"unknown"}
6539- Source: ${e.classification.source||"unknown"}
6540- Backend: ${e.classification.needsDatabase||e.classification.needsAuth||e.classification.needsApi?"possible/yes":"not detected"}
6541
6542## Read before editing
6543- .sj/blueprint.md
6544- .sj/rules.md
6545- .sj/mistakes.md
6546- Current error / active file if present
6547
6548## Likely files to inspect
6549${(n.length?n:r.slice(0,8)).map(s=>`- ${s}`).join(`
6550`)||"- No substantive files yet"}
6551
6552## Constraints
6553- Make the smallest relevant edit.
6554- Do not duplicate pages or routes.
6555- Do not change schema/auth/cloud/billing unless requested.
6556- Verify with build/preview when possible.
6557
6558${e.previousErrors.length?`## Current errors
6559${e.previousErrors.slice(0,6).map(s=>`- ${s}`).join(`
6560`)}
6561`:""}
6562`}function vZ(e,t){const r=(e==null?void 0:e.trim())||"# Build notes",n=t.fileNames.slice(0,16).map(s=>`  - ${s}`).join(`
6563`)||"  - No substantive files changed";return`${r}
6564
6565## ${new Date().toISOString()}
6566- Request: ${t.userText.slice(0,240)}
6567- Status: ${t.status}
6568- Model: ${t.model||"unknown"}
6569- Files:
6570${n}
6571${t.error?`- Error: ${t.error}`:"- Validation: Build log recorded; run preview/build checks for touched surfaces."}
6572`}function wZ(e,t){const r=Zr(t).find(i=>i.path==="src/lib/attached-assets.ts"),n=w$(r==null?void 0:r.content),s=j$(n,e);return s.length===0?[]:[{filename:"src/lib/attached-assets.ts",language:"ts",content:N$(s)}]}function jZ(e,t,r){const n=Zr(e);if(n.length===0)return"";const s=n.filter(y=>Ul(y.path)&&!fp(y.path,y.content)),i=n.find(y=>y.path===Vb),o=n.find(y=>y.path===Gb),l=n.find(y=>y.path===Kb),c=n.find(y=>y.path===Rp),u=n.find(y=>y.path===Dp),d=s.length>0?s:n,p=d.slice(0,120).map(y=>`- ${y.path}`);d.length>120&&p.push(`- ... ${d.length-120} more file(s)`);const f=QI(t,r)==="issue-fix"?"MANDATORY FIX WORKFLOW: inspect only the named surface, its route/layout file, and any direct dependencies needed to make the fix. Avoid unrelated pages or broad scans. The
6572n emit one or more write_file tool calls. No prose preamble, no broad rewrite, no plan list.":"Choose the minimum relevant files, read only what you need, then begin with targeted write_file tool calls instead of broad rewrites.",g=[`
6573
6574--- EXISTING PROJECT FILES ---`,`Project mode: ${s.length>0?`EDIT MODE — ${s.length} substantive project file(s) already exist.`:"FIRST BUILD MODE — only project meta/config exists so you should scaffold the requested app while preserving project memory files."}`,`Relevant file inventory:
6575${p.join(`
6576`)||"- (none yet)"}`];return i&&g.push(`Project rules (${Vb}):
6577\`\`\`md
6578${nu(i.content,2200)}
6579\`\`\``),o&&g.push(`Project blueprint (${Gb}):
6580\`\`\`md
6581${nu(o.content,2200)}
6582\`\`\``),l&&g.push(`Known mistakes (${Kb}):
6583\`\`\`md
6584${nu(l.content,1800)}
6585\`\`\``),c&&g.push(`Current plan (${Rp}):
6586\`\`\`md
6587${nu(c.content,1400)}
6588\`\`\``),u&&g.push(`Recent build notes (${Dp}):
6589\`\`\`md
6590${nu(u.content,1800)}
6591\`\`\``),g.push(`WORKFLOW: Use the inventory above to decide the minimum file set. Read only the files needed for this task. Do not edit unrelated files. Never create a second home/landing page or duplicate an existing route unless the prompt explicitly asks for that surface. ${f}`),g.join(`
6592
6593`)}async function NZ(e){try{const{data:t,error:r}=await G.functions.invoke("sync-supabase-auth-url",{body:{projectId:e}});if(r||t!=null&&t.error)return;t!=null&&t.site_url&&W.success("Auth URL synced",{description:String(t.site_url),duration:5e3})}catch{}}function kZ({chatCollapsed:e=!1,onToggleChat:t}={}){var NN;const{messages:r,addMessage:n,updateLastAiMessage:s,saveLastAiMessage:i,setLastAiMessageMeta:o,isBuilding:l,setIsBuilding:c,setLiveStatus:u,pushToolCall:d,setIsMultiAgentRun:p,setCurrentAgent:h,isMultiAgentRun:f,toolCallHistory:x,setCurrentAgentRunId:g,mode:y,activeModel:b,setActiveModel:v,files:k,setFiles:N,planSteps:j,setPlanSteps:w,previewHtml:S,setPreviewHtml:T,setActiveWorkspaceTab:C,setGeneratedBlockCount:A,generatedPages:P,setGeneratedPages:E,activePageId:_,setActivePageId:I,setBuildProgress:D,setApis:M,setSchema:B,buildMode:$,architecture:K,setArchitecture:R,capabilities:Y,aiBehavior:Z,lifecycleStage:O,focusArea:ne,target:oe,setTarget:he,saveProjectFiles:ae,saveProjectApis:ve,saveProjectSchema:re,triggerBuildRef:se,project:le,projects:te,switchProject:We,setCopilotData:Me,setCopilotSql:Te,setCopilotError:Ee,setCopilotLoading:st,setCurrentWorkflow:xt,addToolUsage:on,orchestration:Yt,setOrchestration:mt,lastBuildErrors:ln,clearBuildErrors:at,appendBuildError:gt,addPendingChange:$t,useApplyOnAccept:ue,setUseApplyOnAccept:je,setBuildHalted:ct,firstBuildDone:it,previewReady:q,enqueuePrompt:Nt}=gn(),U=(le==null?void 0:le.id)||null,Ne=ld(),{user:Ft,emailVerified:Zt}=Us(),{canEdit:Ke}=Ih(),{connections:ie,loadConnections:we,runQuery:Je}=Rh(U),{connections:ot}=z1(U),{createTable:V,batchCreateTables:ye,insertRow:me}=mx(U),{createLog:_e,completeLog:dt,saveSnapshot:kt,loadLogs:wn,loadSnapshot:kn}=Yw(U),{connect:Ae}=rO(),{capturePreviewThumbnail:rt}=H1(),{activeGuideline:fe,toPromptContext:lt}=NE(U,le==null?void 0:le.ownerUserId),{functions:yt,secrets:zt,autoDetectFunctions:Fe}=W1(U),{deployBuildArtifacts:qt,autoProvision:fr,isSupabaseConnected:Jt}=aO(),{triggerAutoPush:_t}=RX(),{getMemoryContext:z,saveBuildMemory:ee}=BX(U),de=m.useMemo(()=>ot.map(WX).filter(Boolean),[ot]),[ge,Se]=m.useState(""),Ie=m.useRef(null),[De,Ce]=m.useState(0),xn=ge.startsWith("/")&&!ge.includes(`
6594`)?ge.slice(1).trim().toLowerCase():null,et=m.useMemo(()=>xn===null?[]:qX.filter(F=>`${F.command} ${F.title} ${F.description}`.toLowerCase().includes(xn)),[xn]),wt=Ke&&!l&&xn!==null&&et.length>0,At=m.useCallback(F=>{Se(F.prompt),Ce(0),requestAnimationFrame(()=>{var X;return(X=Ie.current)==null?void 0:X.focus()})},[]);m.useEffect(()=>{Ce(0)},[xn]);const[Fn,mr]=m.useState(()=>{try{return localStorage.getItem("sj_useOrchestration")==="1"}catch{return!1}});m.useEffect(()=>{try{localStorage.setItem("sj_useOrchestration",Fn?"1":"0")}catch{}},[Fn]);const[ts,zi]=m.useState(()=>{try{return localStorage.getItem("sj_composerMode")||"apply"}catch{return"apply"}}),[Tc,Qs]=m.useState(!1);m.useEffect(()=>{try{localStorage.setItem("sj_composerMode",ts)}catch{}},[ts]),m.useEffect(()=>{const F=X=>
6594{X.altKey&&(X.key==="p"||X.key==="P")&&!X.metaKey&&!X.ctrlKey&&(X.preventDefault(),zi(pe=>pe==="apply"?"draft":"apply"),Qs(!1))};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[]),m.useEffect(()=>{function F(X){var He,bt,jr;const pe=X.detail;if(!pe)return;if(pe.mode==="ai"){if(!((He=pe.instruction)!=null&&He.trim()))return;const In=["Visual editor — Ask AI request. The user clicked an element in the live preview and typed an instruction.","","Element context:",[pe.tagName?`- tag: <${pe.tagName}>`:"",pe.className?`- class: "${pe.className}"`:"",pe.elementText?`- current text: "${pe.elementText.slice(0,200)}"`:"",pe.imgSrc?`- current image src: ${pe.imgSrc}`:""].filter(Boolean).join(`
6595`),"","User instruction:",pe.instruction.trim(),"","Constraints:","- Use str_replace / write_file / edit_file tools as needed to fulfill the request.","- Make the smallest set of edits that satisfies the instruction. Do not refactor unrelated code.","- Prefer editing the page/component currently in the active preview.","- Do NOT rearrange the whole layout (sidebar left↔right, grid restructure, nav rewrite) unless the user explicitly asked for a layout change.","- For image instructions: only change the targeted image src/alt (or the element the user clicked). Do not redesign unrelated sections.",'- If the user says "use this image here", update only that image slot — keep surrounding structure identical.',"- Do NOT call ask_next_phase — this is a one-off visual tweak.","- After edits, reply with one short sentence confirming what changed."].join(`
6596`);(bt=Xn.current)==null||bt.call(Xn,In);return}if(!pe.oldText||pe.newText==null||pe.oldText.trim()===pe.newText.trim())return;const Pe=[`Visual edit from the preview${pe.tagName?` (originally inside <${pe.tagName}>)`:""}. Use the str_replace tool to change the text below in whichever file contains it.`,"","— OLD (find this exactly, including surrounding whitespace if needed):",pe.oldText,"","— NEW (replace with):",pe.newText,"","Constraints:","- Make the smallest possible str_replace edit. Do not touch unrelated lines.","- If the text appears in multiple files, prefer the page/component that is currently in the active preview.","- Do NOT call ask_next_phase — this is a one-off visual tweak, not a phase transition.","- Reply briefly afterwards: one line confirming what changed."].join(`
6597`);(jr=Xn.current)==null||jr.call(Xn,Pe)}return window.addEventListener("sj:visual-edit-submit",F),()=>window.removeEventListener("sj:visual-edit-submit",F)},[]),m.useEffect(()=>{function F(X){var Pe;const xe=(Pe=X.detail)==null?void 0:Pe.prompt;typeof xe=="string"&&xe.length>0&&Se(xe)}return window.addEventListener("sj:chat-prefill",F),()=>window.removeEventListener("sj:chat-prefill",F)},[]),m.useEffect(()=>{function F(X){var bt,jr;const pe=X.detail;if(!pe||!((bt=pe.instruction)!=null&&bt.trim())||!pe.selectedText||!pe.filePath)return;const xe=pe.selectedText,Pe=pe.instruction.trim(),He=[`Cmd+K edit. The user selected a region in \`${pe.filePath}\` and wrote an instruction.`,"","— Selected code (find this exactly):","```",xe,"```","","— Instruction:",Pe,"","Constraints:","- Use the str_replace tool against `"+pe.filePath+"`. The `old_str` MUST be the exact selected code above (whitespace + indentation included).","- The `new_str` is your rewrite that fulfills the instruction.","- Do NOT modify anything outside the selection. No reformatting unrelated lines.","- Preserve indentation level of the selection.","- Do NOT call ask_next_phase — this is a one-off edit.","- After the edit, reply with one short sentence describing what changed."].join(`
6598`);(jr=Xn.current)==null||jr.call(Xn,He)}return window.addEventListener("sj:cmd-k-edit",F),()=>window.removeEventListener("sj:cmd-k-edit",F)},[]);const[qr,xd]=m.useState(()=>{const F=sessionStorage.getItem("sj_pending_model"),X=F?af(F):"claude-opus-4-8";return F&&sessionStorage.removeItem("sj_pending_model"),X}),[vs,fi]=m.useState(()=>PJ());m.useEffect(()=>{AJ(vs)},[vs]);const[gl,mi]=m.useState(()=>MI());m.useEffect(()=>{LI(gl)},[gl]);const xl=m.useRef(k);xl.current=k,m.useEffect(()=>{if(!l||!U)return;let F=!1;const X=async()=>{try{const xe=Zr(xl.current).filter(Pe=>Ul(Pe.path)).length;await G.from("build_jobs").update({files_count:xe,updated_at:new Date().toISOString()}).eq("project_id",U).eq("status","running")}catch{}},pe=window.setInterval(()=>{F||X()},12e3);return X(),()=>{F=!0,window.clearInterval(pe)}},[l,U]);const[Er,Ec]=m.useState(()=>{try{const F=localStorage.getItem("sj_designMode");if(F&&["auto","linear","vercel","stripe","apple","editorial","brutalist","glassmorphic","playful"].includes(F))return F}catch{}return"auto"});m.useEffect(()=>{try{localStorage.setItem("sj_designMode",Er)}catch{}},[Er]);const[Hs,yl]=m.useState(""),[Ic,Ue]=m.useState(""),[Bt,ut]=m.useState(!1),[cn,Qn]=m.useState(!1),[Ye,pt]=m.useState(""),Xe=m.useCallback(async F=>{const X=F.trim();if(!X)return;const pe=/^https?:\/\//i.test(X)?X:`https://${X}`;ut(!0);try{const{data:xe,error:Pe}=await G.functions.invoke("fetch-website",{body:{url:pe}});if(Pe||!xe){W.error(`Couldn't import reference: ${(Pe==null?void 0:Pe.message)??"no response"}`);return}const He=[];xe.title&&He.push(`Title: ${xe.title}`),xe.description&&He.push(`Description: ${xe.description}`),Array.isArray(xe.headings)&&xe.headings.length>0&&He.push(`Section headings: ${xe.headings.slice(0,8).join(" / ")}`),Array.isArray(xe.fonts)&&xe.fonts.length>0&&He.push(`Fonts in use: ${xe.fonts.join(", ")}`),Array.isArray(xe.colors)&&xe.colors.length>0&&He.push(`Color palette: ${xe.colors.slice(0,12).join(", ")}`),xe.ogImage&&He.push(`Hero image style: ${xe.ogImage}`);const bt=He.join(`
6599`);yl(pe),Ue(bt),Qn(!1),W.success(`Imported reference: ${new URL(pe).hostname}`)}catch(xe){W.error(`Reference import failed: ${(xe==null?void 0:xe.message)??"unknown error"}`)}finally{ut(!1)}},[]),St=m.useCallback(()=>{yl(""),Ue(""),pt("")},[]),[Mn,Ir]=m.useState(()=>{try{const F=sessionStorage.getItem("sj_pending_attachments");if(!F)return[];sessionStorage.removeItem("sj_pending_attachments");const X=JSON.parse(F);return Array.isArray(X)?X:[]}catch{return[]}}),[gr,vr]=m.useState(""),[ws,Ps]=m.useState(()=>{try{return localStorage.getItem("sj_build_notifications_dismissed")==="1"}catch{return!1}}),[ca,Jr]=m.useState(()=>typeof Notification>"u"?"denied":Notification.permission),[cr,qa]=m.useState(new Map),Oc=m.useRef(null),qh=m.useRef(null),wr=m.useRef(!1),ly=m.useRef({text:"",at:0}),yd=m.useRef(new Set),Zj=m.useRef(new Set),Qj=m.useRef(!1),Hh=m.useRef(!1),bd=m.useRef(!1),Wh=m.useRef(!1),cy=m.useRef(!1),eN=m.useRef(""),tN=m.useRef(null),er=m.useRef({}),vd=m.useRef(null),[nN,uy]=m.useState(!1),[dy,Rc]=m.useState([]),[KM,rN]=m.useState(!1),qi=m.useRef([]),[py,sN]=m.useState([]),[YM,hy]=m.useState(!1),Hi=m.useRef(null),aN=m.useCallback(()=>new Promise(F=>{Hi.current=F,hy(!0)}),[]),JM=m.useCallback(F=>{var X;hy(!1),(X=Hi.current)==null||X.call(Hi,F),Hi.current=null},[]),XM=m.useCallback(()=>{var F;hy(!1),(F=Hi.current)==null||F.call(Hi,null),Hi.current=null},[]),Vh=m.useRef(new Map),fy=m.useCallback(async(F,X,pe)=>{var Pe,He;if(l)return W.info("Build in progress — open Cloud → Provision after the build finishes."),!1;W.info("Provisioning your database…",{description:`Region: ${pe}`});let xe=await fr(F,X,pe);if(xe.needs_connect){W.info("Redirecting to Supabase to authorize…");const bt=await Ae();if(bt.redirecting){try{sessionStorage.setItem("sj_pending_cloud_provision",JSON.stringify({projectId:F,projectName:X,region:pe}))}catch{}return!1}if(!bt.success)return W.error(bt.error||"Could not connect Supabase"),
6599!1;W.success("Supabase connected — provisioning your database…"),xe=await fr(F,X,pe)}if(xe.success){const bt=(Pe=xe.info)!=null&&Pe.supabase_url?xe.info.supabase_url.replace(/^https?:\/\//,"").split("/")[0]:void 0;return W.success("Database ready",{description:bt?`${bt} · ${((He=xe.info)==null?void 0:He.region)||pe}`:void 0}),window.dispatchEvent(new CustomEvent("sj:infra-changed",{detail:{projectId:F}})),NZ(F),!0}return console.warn("[chat] Auto-provision failed:",xe.error),W.error("Database provisioning failed",{description:xe.error}),!1},[fr,Ae,l]);m.useCallback(async()=>{if(!U||!(le!=null&&le.name)||l)return;let F=null;try{F=sessionStorage.getItem("sj_pending_cloud_provision")}catch{return}if(!F)return;let X;try{X=JSON.parse(F)}catch{try{sessionStorage.removeItem("sj_pending_cloud_provision")}catch{}return}if(X.projectId!==U||!X.region)return;const pe=Vh.current.get(U);if(pe){await pe;return}const xe=(async()=>{try{sessionStorage.removeItem("sj_pending_cloud_provision");const{data:Pe}=await G.from("project_cloud_config").select("env_vars").eq("project_id",U).maybeSingle(),He=(Pe==null?void 0:Pe.env_vars)||{};return He.SUPABASE_URL&&He.SUPABASE_ANON_KEY?!0:(W.success("Supabase connected — finishing database setup…"),await fy(U,le.name,X.region))}catch(Pe){return console.warn("[chat] Resume cloud provision error:",Pe),!1}})();Vh.current.set(U,xe);try{await xe}finally{Vh.current.get(U)===xe&&Vh.current.delete(U)}},[U,le==null?void 0:le.name,fy,l]);const iN=m.useCallback(async F=>{const{data:X}=await G.from("project_cloud_config").select("env_vars, region").eq("project_id",F).maybeSingle(),pe=(X==null?void 0:X.env_vars)||{};return pe.SUPABASE_URL&&pe.SUPABASE_ANON_KEY?(X==null?void 0:X.region)||"us-east-1":aN()},[aN]);m.useEffect(()=>{let F=!1;try{F=sessionStorage.getItem("sj_oauth_just_completed")==="1"}catch{}if(!F)try{sessionStorage.removeItem("sj_pending_cloud_provision")}catch{}},[U]),m.useEffect(()=>{U&&we()},[U,we]);const oN=m.useRef(r.length);m.useEffect(()=>{if(r.length>oN.current&&Oc.current){const F=Oc.current,X=F.scrollHeight-F.clientHeight-F.scrollTop;F.scrollTo({top:F.scrollHeight,behavior:X>600?"auto":"smooth"})}oN.current=r.length},[r]);const ZM=m.useCallback(()=>{D(0);let F=0;qh.current=window.setInterval(()=>{F+=(95-F)*.03,D(Math.min(F,95))},300)},[D]),No=m.useCallback(()=>{qh.current&&(clearInterval(qh.current),qh.current=null),D(100)},[D]),gi=m.useRef([]),ko=m.useRef(null),ua=m.useRef(!1),Dc=m.useRef(0),Gh=m.useRef(""),Kh=m.useRef(!1),lN=m.useCallback(F=>{if(Kh.current)return;Kh.current=!0;const X=PX(F);if(X.length>0){const dn=tu(Mo(X)),{flatFiles:$e,pages:Qt,preferredPage:ns,apis:ur,schema:tr}=_f(dn);gi.current=$o(dn),N(dn),A($e.length),E(Qt),M(ur),B(tr),ns&&(T(ns.html),I(ns.id),C("preview")),w([{id:"stage-planning",title:"Planning",description:"Domain substrate fallback after stall",status:"done"},{id:"stage-generating",title:"Generating Files",description:`Applied ${$e.length} domain-specific substrate files`,status:"done"},{id:"stage-saving",title:"Saving Files",description:"Persisting substrate to project storage",status:"running"},{id:"stage-syncing",title:"Syncing Sandbox",description:"Updating preview runtime with substrate files",status:"pending"},{id:"stage-preview",title:"Starting Preview",description:"Launching domain preview",status:"pending"},{id:"stage-ready",title:"Preview Ready",description:"Preview opened — background deepen continues",status:"pending"}]),No(),c(!1),wr.current=!1;const Na=$e.map(Kn=>({name:Kn.path.split("/").pop()||Kn.path,path:Kn.path,content:Kn.content,language:Kn.language}));ae(Na).then(()=>{w(Kn=>Kn.map(Bn=>Bn.id==="stage-saving"?{...Bn,status:"done"}:Bn.id==="stage-syncing"?{...Bn,status:"running"}:Bn))}).catch(Kn=>{w(Bn=>Bn.map(ka=>ka.id==="stage-saving"?{...ka,status:"error",description:`Save failed: ${Kn.message}`}:ka))}),U&&Pr({action:"restart",projectId:U,files:$e.map(Kn=>({path:Kn.path,content:Kn.content}))}).then(()=>{w(Kn=>Kn.map(Bn=>Bn.id==="stage-syncing"?{...Bn,status:"done"}:Bn.id==="stage-preview"?{...Bn,status:"done"}:Bn.id==="stage-ready"?{...Bn,status:"done"}:Bn))}).catch(Kn=>
6599{w(Bn=>Bn.map(ka=>ka.id==="stage-syncing"||ka.id==="stage-preview"?{...ka,status:"error",description:`Preview recovery failed: ${Kn.message}`}:ka))}),n("ai","I applied the **domain-specific preview substrate** so your app opens immediately with the correct layout shell. Background generation will continue enriching it."),W.warning("Build stalled — applied domain preview substrate.",{duration:5e3});return}const xe=(F.replace(/BUILD TYPE:[\s\S]*?USER REQUEST:\s*/i,"").replace(/\s+/g," ").trim()||"Modern Business Landing Page").slice(0,80),Pe=[{filename:"src/index.css",language:"css",content:`:root { color-scheme: light; }
6600* { box-sizing: border-box; }
6601body { margin: 0; font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #f7f7f7; color: #111827; }
6602a { color: inherit; text-decoration: none; }
6603.container { max-width: 1120px; margin: 0 auto; padding: 0 1.25rem; }
6604.btn { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 999px; padding: 0.8rem 1.2rem; font-weight: 600; cursor: pointer; }
6605.btn-primary { background: #111827; color: #fff; }
6606.btn-secondary { background: #fff; color: #111827; border: 1px solid #d1d5db; }
6607`},{filename:"src/components/Navbar.tsx",language:"tsx",content:`import { Link } from 'react-router-dom';
6608
6609export default function Navbar() {
6610  return (
6611    <header style={{ borderBottom: '1px solid #e5e7eb', background: '#ffffffcc', backdropFilter: 'blur(8px)' }}>
6612      <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 64 }}>
6613        <strong>{'${xe.replace(/'/g,"\\'")}'}</strong>
6614        <nav style={{ display: 'flex', gap: 16 }}>
6615          <a href="#services">Services</a>
6616          <a href="#about">About</a>
6617          <a href="#contact">Contact</a>
6618          <Link to="/">Home</Link>
6619        </nav>
6620      </div>
6621    </header>
6622  );
6623}
6624`},{filename:"src/components/Footer.tsx",language:"tsx",content:`export default function Footer() {
6625  return (
6626    <footer style={{ borderTop: '1px solid #e5e7eb', marginTop: 48, background: '#fff' }}>
6627      <div className="container" style={{ padding: '20px 0', display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
6628        <span>Built with Studio Jungle</span>
6629        <span>[email protected]</span>
6630      </div>
6631    </footer>
6632  );
6633}
6634`},{filename:"src/pages/Home.tsx",language:"tsx",content:`export default function Home() {
6635  return (
6636    <main>
6637      <section className="container" style={{ padding: '80px 0 48px' }}>
6638        <p style={{ color: '#6b7280', marginBottom: 8 }}>Fast preview scaffold</p>
6639        <h1 style={{ fontSize: 'clamp(2rem, 5vw, 3.25rem)', lineHeight: 1.05, margin: 0 }}>`+xe+`</h1>
6640        <p style={{ marginTop: 16, maxWidth: 700, color: '#4b5563', fontSize: 18 }}>Your preview is ready. Studio Jungle will continue generating detailed sections in the background.</p>
6641        <div style={{ display: 'flex', gap: 12, marginTop: 24, flexWrap: 'wrap' }}>
6642          <button className="btn btn-primary">Book Appointment</button>
6643          <button className="btn btn-secondary">View Services</button>
6644        </div>
6645      </section>
6646      <section id="services" className="container" style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', paddingBottom: 40 }}>
6647        {['Consultation', 'Premium Care', 'Follow-up'].map((item) => (
6648          <article key={item} style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 16, padding: 18 }}>
6649            <h3 style={{ marginTop: 0 }}>{item}</h3>
6650            <p style={{ marginBottom: 0, color: '#6b7280' }}>Detailed content is being generated.</p>
6651          </article>
6652        ))}
6653      </section>
6654    </main>
6655  );
6656}
6657`},{filename:"src/pages/NotFound.tsx",language:"tsx",content:`import { Link } from 'react-router-dom';
6658
6659export default function NotFound() {
6660  return (
6661    <main className="container" style={{ padding: '96px 0' }}>
6662      <h1 style={{ marginBottom: 8 }}>Page not found</h1>
6663      <p style={{ color: '#6b7280' }}>The page you are looking for does not exist.</p>
6664      <Link to="/" style={{ color: '#111827', fontWeight: 600 }}>Go back home</Link>
6665    </main>
6666  );
6667}
6668`},{filename:"src/App.tsx",language:"tsx",content:`import { Route, Routes } from 'react-router-dom';
6669import Navbar from './components/Navbar';
6670import Footer from './components/Footer';
6671import Home from './pages/Home';
6672import NotFound from './pages/NotFound';
6673
6674export default function App() {
6675  return (
6676    <>
6677      <Navbar />
6678      <Routes>
6679        <Route path="/" element={<Home />} />
6680        <Route path="*" element={<NotFound />} />
6681      </Routes>
6682      <Footer />
6683    </>
6684  );
6685}
6686`}],He=tu(Mo(Pe)),{flatFiles:bt,pages:jr,preferredPage:un,apis:In,schema:Xr}=_f(He);gi.current=$o(He),N(He),A(bt.length),E(jr),M(In),B(Xr),un&&(T(un.html),I(un.id),C("preview")),w([{id:"stage-planning",title:"Planning",description:"Fallback triggered after stall",status:"done"},{id:"stage-generating",title:"Generating Files",description:`Generated ${bt.length} fallback files`,status:"done"},{id:"stage-saving",title:"Saving Files",description:"Persisting scaffold to project storage",status:"running"},{id:"stage-syncing",title:"Syncing Sandbox",description:"Updating preview runtime with fallback files",status:"pending"},{id:"stage-preview",title:"Starting Preview",description:"Launching preview from fallback scaffold",status:"pending"},{id:"stage-ready",title:"Preview Ready",description:"Preview opened while AI continues in background",status:"pending"}]),No(),c(!1),wr.current=!1;const Gn=bt.map(dn=>({name:dn.path.split("/").pop()||dn.path,path:dn.path,content:dn.content,language:dn.language}));ae(Gn).then(()=>{w(dn=>dn.map($e=>$e.id==="stage-saving"?{...$e,status:"done"}:$e.id==="stage-syncing"?{...$e,status:"running"}:$e))}).catch(dn=>{w($e=>$e.map(Qt=>Qt.id==="stage-saving"?{...Qt,status:"error",description:`Save failed: ${dn.message}`}:Qt))}),U&&Pr({action:"restart",projectId:U,files:bt.map(dn=>({path:dn.path,content:dn.content}))}).then(()=>{w(dn=>dn.map($e=>$e.id==="stage-syncing"?{...$e,status:"done"}:$e.id==="stage-preview"?{...$e,status:"done"}:$e.id==="stage-ready"?{...$e,status:"done"}:$e))}).catch(dn=>{w($e=>$e.map(Qt=>Qt.id==="stage-syncing"||Qt.id==="stage-preview"?{...Qt,status:"error",description:`Preview recovery failed: ${dn.message}`}:Qt))}),n("ai","I applied a fast fallback scaffold so preview opens immediately. You can keep building incrementally from here."),W.warning("AI generation stalled. Applied fast fallback scaffold and opened preview.")},[n,U,ae,I,C,M,N,A,E,w,T,B,c,No]);m.useEffect(()=>{if(!l||it||x.some(Pe=>Pe.status==="done"||Pe.status==="running"))return;const F=32e3,X=45e3,pe=window.setTimeout(()=>{var He;if(!l||it||x.some(bt=>bt.status==="done"||bt.status==="running")||Dc.current>=2)return;const Pe=Gh.current.trim();Pe&&(console.warn("[chat] First-build tool stall — aborting and rescuing"),Dc.current+=1,ua.current=!0,(He=ko.current)==null||He.abort(),window.setTimeout(()=>{ua.current=!1;try{window.dispatchEvent(new CustomEvent("sj:abort-stuck-build",{detail:{prompt:Pe}}))}catch{}},400))},F),xe=window.setTimeout(()=>{var He;if(!l||it||x.some(bt=>bt.status==="done"||bt.status==="running")||Kh.current)return;const Pe=Gh.current.trim();
6686Pe&&(console.warn("[chat] First-build hard timeout at 45s with no file output. Applying fast fallback scaffold."),ua.current=!0,(He=ko.current)==null||He.abort(),window.setTimeout(()=>{ua.current=!1,lN(Pe)},300))},X);return()=>{window.clearTimeout(pe),window.clearTimeout(xe)}},[l,it,x.length,lN]),m.useEffect(()=>{function F(pe){var Pe,He;const xe=(Pe=pe.detail)==null?void 0:Pe.prompt;!xe||Dc.current>=2||(Dc.current+=1,ua.current=!0,(He=ko.current)==null||He.abort(),window.setTimeout(()=>{var bt;ua.current=!1,(bt=Xn.current)==null||bt.call(Xn,xe,{isRescue:!0})},600))}function X(pe){var Pe,He;const xe=(Pe=pe.detail)==null?void 0:Pe.prompt;!xe||it||l||wr.current||(console.log("[chat] sj:trigger-initial-build fallback — starting first build"),(He=Xn.current)==null||He.call(Xn,xe))}return window.addEventListener("sj:abort-stuck-build",F),window.addEventListener("sj:trigger-initial-build",X),()=>{window.removeEventListener("sj:abort-stuck-build",F),window.removeEventListener("sj:trigger-initial-build",X)}},[it,l]);const QM=m.useCallback(()=>{const F=$o(gi.current),{flatFiles:X,pages:pe,preferredPage:xe,apis:Pe,schema:He}=_f(F);N(F),A(X.length),E(pe),M(Pe),B(He),xe?(T(xe.html),I(xe.id),C("preview")):(T(null),I(null))},[I,C,M,N,A,E,T,B]),Mc=m.useCallback((F,X)=>{if(ua.current)return;const xe=jl(F).filter(He=>{var jr;const bt=(jr=He.filename.split(".").pop())==null?void 0:jr.toLowerCase();if(bt==="tsx"||bt==="ts"||bt==="jsx"||bt==="js")try{return RI(He.content,{sourceType:"module",plugins:["jsx","typescript"],errorRecovery:!1}),!0}catch(un){return X||console.warn(`[chat] Partial file protection rejected ${He.filename}: ${un.message}`),!1}return!0}),Pe=rF(xe,X,F);if(xe.length>0){er.current.firstFileTime||(er.current.firstFileTime=Date.now()),er.current.emittedFileCount=xe.length;const He=Mo(xe),bt=gi.current,jr=bt.length>0?$l(bt,He):He;N(jr),A(Zr(jr).length),X||_t(jr,(le==null?void 0:le.name)||void 0,U||void 0),Hh.current?w(Gn=>{const dn=Gn.filter(Qt=>Qt.id.startsWith("db-")&&Qt.id!=="db-followup"),$e={id:"db-followup",title:"Generating Application",description:X?`Generating ${xe.length} file(s)...`:`Generated ${xe.length} file(s)`,status:X?"running":"done",logs:xe.map(Qt=>Qt.filename)};return[...dn,$e,...Pe]}):w(Gn=>{if(Gn.some($e=>$e.id.startsWith("smart-"))){const $e=xe.map(Qt=>Qt.filename);return eO(Gn,$e,X)}return Pe});const un=tp(xe);M(un);const In=np(xe);B(In);const Xr=id(Zr(jr).map(Gn=>({filename:Gn.path,language:Gn.language,content:Gn.content})));if(E(Xr),Xr.length>0){const Gn=Y1(Xr)||Xr[0];T(Gn.html),X?X&&!_&&(I(Gn.id),C("preview")):(I(Gn.id),C("preview"))}}else X&&!Hh.current&&w(He=>He.some(bt=>bt.id.startsWith("smart-"))?He:Pe.length>0&&Pe.some(bt=>bt.id.startsWith("phase-"))?Pe:[{id:"analyze",title:"Analyzing Request",description:"Understanding requirements and planning implementation",status:"running",logs:["Parsing user prompt...","Generating response..."]}])},[N,w,T,A,E,I,M,B,C]),my=m.useCallback(F=>{const X=Array.from(F);if(X.length===0)return;let pe=0;X.forEach(xe=>{if(xe.size>15*1024*1024){pe+=1;return}Z_(xe).then(Pe=>Ir(He=>[...He,Pe])).catch(Pe=>{console.error("[attachments] extract failed:",Pe),Ir(He=>[...He,{name:xe.name,type:xe.type||"application/octet-stream",size:xe.size,kind:"file",summary:`${xe.name} is attached, but text extraction failed: ${(Pe==null?void 0:Pe.message)||"unknown error"}. Use it as high-level reference only.`}])})}),pe>0&&W.error("Some files were too large",{description:"Upload files under 15 MB each."})},[]),eL=m.useCallback(F=>{const X=F.target.files;X&&(my(X),F.target.value="")},[my]),cN=m.useCallback(F=>{Ir(X=>X.filter((pe,xe)=>xe!==F))},[]),tL=m.useCallback(async()=>{if(typeof Notification>"u"){W.error("Notifications are not available in this browser.");return}try{const F=await Notification.requestPermission();Jr(F),F==="granted"?W.success("Notifications enabled",{description:"I'll let you know 
6686when a build finishes."}):W.message("Notifications not enabled")}catch{W.error("Could not enable notifications.")}},[]),nL=m.useCallback(()=>{Ps(!0);try{localStorage.setItem("sj_build_notifications_dismissed","1")}catch{}},[]),rL=m.useCallback((F,X)=>{if(!(typeof Notification>"u"||Notification.permission!=="granted"))try{new Notification(F,{body:X,icon:"/favicon.png"})}catch{}},[]),Xn=m.useRef(),bl=m.useRef(!1),uN=m.useRef(0),Lc=m.useRef(!1),dN=m.useRef(!1);m.useEffect(()=>{if(U)try{dN.current=localStorage.getItem(`auth_scaffolded_${U}`)==="1"}catch{}},[U]);const pN=m.useCallback(()=>{if(dN.current=!0,U)try{localStorage.setItem(`auth_scaffolded_${U}`,"1")}catch{}},[U]),[sL,hN]=m.useState(!1),[aL,gy]=m.useState(!1),[iL,fN]=m.useState(!1),[Yh,mN]=m.useState(""),[oL,gN]=m.useState(void 0),Jh=m.useRef(!1),Xh=m.useRef(null),{config:xN,updateConfig:lL}=mO(U);m.useEffect(()=>{if(U)try{Jh.current=localStorage.getItem(`cloud_enabled_${U}`)==="1"}catch{}},[U]);const cL=m.useCallback(F=>{var xe;if(l||bl.current)return;if(bl.current=!0,F.includes("React Native")||F.toLowerCase().includes("react-native")){n("user","⚛️ React Native (Expo)"),Xh.current="react-native",he("mobile"),R({...K,mobileFramework:"react-native"});const Pe=r.filter(He=>He.role==="user").pop();Pe&&setTimeout(()=>{var He;(He=Xn.current)==null||He.call(Xn,Pe.content)},300),bl.current=!1;return}if(F.includes("Mobile Web")||F.includes("PWA")||F.toLowerCase().includes("mobile web")||F.toLowerCase().includes("progressive web")){n("user","🌐 Mobile Web / PWA"),Xh.current="pwa",he("mobile"),R({...K,mobileFramework:"pwa"});const Pe=r.filter(He=>He.role==="user").pop();Pe&&setTimeout(()=>{var He;(He=Xn.current)==null||He.call(Xn,Pe.content)},300),bl.current=!1;return}if(F.includes("Flutter")||F.toLowerCase().includes("flutter")){n("user","🦋 Flutter (Dart)"),Xh.current="flutter",he("mobile"),R({...K,mobileFramework:"flutter"});const Pe=r.filter(He=>He.role==="user").pop();Pe&&setTimeout(()=>{var He;(He=Xn.current)==null||He.call(Xn,Pe.content)},300),bl.current=!1;return}if(F.includes("Add Auth First")||F.includes("scaffold")){n("user","🔐 Add Auth First"),n("ai","✅ Generating auth scaffold now (login, signup, reset password, and protected routes)."),pN(),gy(!0),hN(!0),bl.current=!1;return}(F.includes("Skip Auth")||F.includes("I'll Handle Auth")||F.includes("I have my own"))&&pN();const pe=/\*\*Next Phase:\*\*/i.test(F)?`${F}
6687
6688---
6689This is a PHASE CONTINUATION on an existing project. Build EXACTLY the selected option(s) above — nothing more, nothing less. If multiple options are selected, implement them together as one scoped incremental edit. Do NOT trigger a full fullstack rebuild. Do NOT add database/auth/API endpoints unless one of my selected options explicitly says to. Read the existing project files, add only what the selected option(s) describe, end with ask_next_phase listing whatever's still left.`:F;(xe=Xn.current)==null||xe.call(Xn,pe),setTimeout(()=>{bl.current=!1},1e3)},[l,K,R,r]),uL=m.useCallback(async F=>{var xe;const X=((xe=F.tables[0])==null?void 0:xe.tableName)||"";qa(Pe=>new Map(Pe).set(X,"creating"));const pe=[{id:"db-approve",title:"Schema Approved",description:"User approved the database schema proposal",status:"done",logs:[`${F.tables.length} table(s) to create`]}];F.tables.forEach(Pe=>{pe.push({id:`db-create-${Pe.tableName}`,title:`Creating Table: ${Pe.displayName||Pe.tableName}`,description:`${Pe.columns.length} columns`,status:"pending"})}),F.seedData&&Object.keys(F.seedData).length>0&&pe.push({id:"db-seed",title:"Seeding Data",description:`Inserting sample rows into ${Object.keys(F.seedData).length} table(s)`,status:"pending"}),pe.push({id:"db-followup",title:"Generating Application",description:"Building the full app with the new database",status:"pending"}),w(pe);try{if(w(un=>un.map(In=>In.id.startsWith("db-create-")?{...In,status:"running"}:In)),await ye(F.tables.map(un=>({tableName:un.tableName,displayName:un.displayName,columns:un.columns.map(In=>({name:In.name,type:In.type,nullable:In.nullable,default_value:In.default_value,is_primary:In.is_primary}))}))),w(un=>un.map(In=>In.id.startsWith("db-create-")?{...In,status:"done",logs:["✅ Table created"]}:In)),F.seedData){w($e=>$e.map(Qt=>Qt.id==="db-seed"?{...Qt,status:"running"}:Qt));let un=0;const In=[],Xr={},Gn=$e=>typeof $e!="string"?$e:$e.replace(/\{\{(\w+)\[(\d+)\]\.(\w+)\}\}/g,(Qt,ns,ur,tr)=>{const Na=Xr[ns],Kn=parseInt(ur,10);return Na&&Na[Kn]&&Na[Kn][tr]!==void 0?String(Na[Kn][tr]):crypto.randomUUID()}),dn=$e=>{const Qt={};for(const[ns,ur]of Object.entries($e))Qt[ns]=Gn(ur);return Qt};for(const[$e,Qt]of Object.entries(F.seedData)){Xr[$e]||(Xr[$e]=[]);for(const ns of Qt)try{const ur=dn(ns),tr=await me($e,ur),Na=tr==null?void 0:tr.data;Array.isArray(Na)&&Na.length>0?Xr[$e].push(Na[0]):Xr[$e].push(ur),un++}catch(ur){const tr=(ur==null?void 0:ur.message)||"Unknown seed error";In.push(`${$e}: ${tr}`),console.warn("Seed insert failed:",ur)}}if(In.length>0)throw w($e=>$e.map(Qt=>Qt.id==="db-seed"?{...Qt,status:"error",logs:[`Inserted ${un} row(s)`,...In.slice(0,3)]}:Qt)),new Error(`Seeding failed for ${In.length} row(s). ${In[0]}`);w($e=>$e.map(Qt=>Qt.id==="db-seed"?{...Qt,status:"done",logs:[`Inserted ${un} row(s)`]}:Qt))}qa(un=>new Map(un).set(X,"approved")),W.success(`✅ Created ${F.tables.length} table(s) successfully`),w(un=>un.map(In=>In.id==="db-followup"?{...In,status:"running",logs:["Sending build request to AI..."]}:In));const Pe=F.tables.map(un=>un.displayName||un.tableName).join(", "),He=F.seedData&&Object.keys(F.seedData).length>0?" and seeded with data":"",bt=LK(F)+`
6690
6691The tables (${Pe}) have been created${He}. Now continue building the FULL application using these tables.
6692
6693CRITICAL REQUIREMENTS:
66941. ALL pages must be linked — every navbar link must have a matching generated HTML page
66952. Authentication pages (login/signup) must use REAL Supabase Auth calls, not mock/localStorage auth
66963. Use REAL fetch calls to the REST proxy to load data from the created tables — do NOT hardcode duplicate data
66974. Every CTA button must navigate to a real page or trigger a real action
66985. Generate a SHARED navbar that is identical across all pages
66996. Only generate pages that are actually linked from navigation — no orphan pages`,jr=()=>{se.current?se.current(bt):n("user",bt)};setTimeout(()=>{jr();const un=setTimeout(()=>{wr.current||(w(Xr=>Xr.map(Gn=>Gn.id==="db-followup"?{...Gn,status:"error",logs:["Build did not start — timed out after 10s"]}:Gn)),W.error("Follow-up build failed to start.",{duration:15e3,action:{label:"Retry Build",onClick:()=>{w(Xr=>Xr.map(Gn=>Gn.id==="db-followup"?{...Gn,status:"running",logs:["Retrying build..."]}:Gn)),jr()}}}))},1e4),In=setInterval(()=>{wr.current&&(clearTimeout(un),clearInterval(In))},500);setTimeout(()=>clearInterval(In),12e3)},500)}catch(Pe){w(He=>He.map(bt=>(bt.id.startsWith("db-create-")||bt.id==="db-seed"||bt.id==="db-followup")&&bt.status!=="done"?{...bt,status:"error",logs:[...bt.logs||[],Pe.message]}:bt)),qa(He=>new Map(He).set(X,"pending")),W.error("Failed to create tables: "+Pe.message)}},[ye,me,n,se,w,c,D]),dL=m.useCallback(F=>{var pe;const X=((pe=F.tables[0])==null?void 0:pe.tableName)||"";qa(xe=>new Map(xe).set(X,"rejected")),n("user","❌ I rejected the proposed schema. Please suggest a different approach.")},[n]),yN=F=>{const X=F.toLowerCase(),pe=[[/analytic|metric|stats|chart/i,"an Analytics page at /analytics with chart cards for daily revenue (line chart), user signups by day (bar chart), top items (table or list), and traffic sources (donut chart). Use mock data matching the project's domain."],[/dashboard/i,"a Dashboard page with 4 KPI cards across the top, a primary chart, and a recent-activity list below."],[/profile|account/i,"a Profile page showing the current user's avatar, name, email, and an editable form."],[/setting/i,"a Settings page with sections for Profile, Notifications, Privacy, and a Danger Zone (delete account)."],[/billing|pricing|payment/i,"a Pricing page with 3 tiers and CTAs."],[/contact/i,"a Contact page with a form (name, email, message) and contact info."],[/login|
6699signin|sign in|auth/i,"a Login page + Signup page with email/password forms."],[/blog|posts|article/i,"a Blog index page listing 6 posts and a single-post page template."]];let xe="";for(const[Pe,He]of pe)if(Pe.test(X)){xe=He;break}return`IMPLEMENT THIS NOW. Generate the complete code via write_file tool calls. NO questions. NO analysis. NO clarifying prose. Make sensible default choices and proceed.
6700
6701User's request: "${F}"
6702${xe?`
6703Default scope (use unless user clearly meant otherwise): ${xe}`:""}
6704Match the existing project's design system, palette, typography, and component patterns. If adding or fixing a route/button flow, ensure the trigger, router entry, and target page/component all exist. Do not claim something is already wired unless you read and verified the exact files. After file writes, end with the standard ask_next_phase tool call using one short sentence only.`},bN=F=>F==="claude-haiku-4-5"?"claude-sonnet-4-6":"claude-opus-4-8",$c=F=>{var X;return((X=Pd.find(pe=>pe.id===af(F)))==null?void 0:X.backendModel)||"auto"},pL=F=>{const X=F.trim();return X.length===0||X.length>260||/https?:\/\//i.test(X)||!Sy(k)||/\b(entire app|whole app|all pages|from scratch|full app|complete app|global redesign|rebuild)\b/i.test(X)?null:/\b(meta tags?|open graph|og:|structured data|json-ld|semantic html|seo|title tag|description tag|canonical|robots)\b/i.test(X)||/\b(copy|text|label|button text|placeholder|alt text|spacing|color|font|padding|margin|small|minor|quick|simple)\b/i.test(X)?"claude-haiku-4-5":/\b(fix|repair|bug|error|broken)\b/i.test(X)?"claude-sonnet-4-6":null},Zh=F=>af(F)==="gpt-5-5"?"claude-sonnet-4-6":af(F),hL=(F,X,pe,xe)=>{if(xe)return{model:xe==="claude-haiku-4-5"?"claude-sonnet-4-6":xe,activeRole:"forced"};if(qr!=="auto")return{model:$c(Zh(qr)),activeRole:"forced"};const Pe=X||F==="issue-fix"?"fixer":"builder",He=Pe==="fixer"?vs.fixer:vs.builder,bt=He==="auto"&&Pe==="builder"?pL(pe):null;return bt?{model:bt,activeRole:Pe}:{model:$c(Zh(He)),activeRole:Pe}},wd=F=>({active:F,selectedProvider:qr,builder:$c(Zh(vs.builder)),fixer:$c(Zh(vs.fixer)),reviewer:$c(vs.reviewer),visual:$c(vs.visual),skillsGuidance:CJ(gl)||void 0}),xy=m.useRef(!1),jd=m.useRef(null),vN=m.useRef(null),xi=async(F,X)=>{var zN,qN,HN,WN,VN,GN,KN,YN,JN,XN,ZN,QN,ek,tk,nk,rk,sk,ak,ik,ok,lk,ck,uk,dk,pk,hk,fk,mk,gk,xk,yk,bk,vk,wk,jk,Nk;if(Bk(U),wr.current){if(l&&!(X!=null&&X.isRescue))return;l&&(X!=null&&X.isRescue)&&(ua.current=!0,(zN=ko.current)==null||zN.abort()),console.warn("[chat] Stale isSendingRef detected — resetting and sending."),wr.current=!1}const pe=F||ge.trim();if(!pe&&Mn.length===0)return;const xe=pe.startsWith(Pf)||!!(X!=null&&X.substrateDeepen),Pe=(qN=jd.current)==null?void 0:qN.fastPath;X=xe?{...X,isRescue:!0,substrateDeepen:!0}:X,Gh.current=xe?pe.replace(Pf,"").trim():pe,X!=null&&X.isRescue||(Kh.current=!1);const bt=!!(X!=null&&X.isAutoFix);if(bt||(Wh.current=!1,cy.current=!1),Qj.current||(Qj.current=!0,G.functions.invoke("chat",{body:{action:"warmup"}}).catch(()=>null)),U&&it&&!yd.current.has(U)&&(yd.current.add(U),Pr({action:"start",projectId:U,files:[]}).then(async ce=>{if(ce&&ce.ok===!1&&ce.code!=="vercel_preview_starting"){yd.current.delete(U);const Be=String(ce.error||ce.message||"");if(/isn't responding|port\s*5173|closed port|vite did not start|no service running/i.test(Be)||ce.status==="error"){console.info("[chat] Preview pre-warm failed — retrying with restart");const xr=await Pr({action:"restart",projectId:U,files:[]});xr!=null&&xr.ok&&yd.current.add(U)}else console.warn("[chat] Preview pre-warm failed:",ce.error||ce.code)}}).catch(ce=>{yd.current.delete(U),console.warn("[chat] Preview pre-warm threw:",ce)})),!F&&pe){const ce=Date.now();if(ly.current.text===pe&&ce-ly.current.at<2e3){console.warn("[chat] Duplicate send within 2s — dropping.");return}ly.current={text:pe,at:ce}}if(!F&&!(X!=null&&X.isRescue)&&Mn.length===0&&O2(pe)){n("user",pe),Se(""),Ir([]),n("ai",YX({isBuilding:l,planSteps:j,lastBuildErrors:ln,filesCount:Zr(k).length}));return}if(Ft&&!Zt){n("user",pe),Se(""),Ir([]),n("ai","Please verify your email before starting a build. I sent a verification link to your account email. Once you open it, refresh the studio or click **I verified** in Account settings."),w([{id:"email-verification-required",title:"Email verification required",description:"Verify your email before creating projects or running AI builds.",status:"error"}]),W.error("Verify your email first",{description:"Open the verification link 
6704we sent before starting AI builds."}),wr.current=!1;return}const jr=await Am(Ne.refresh,Ne),un=jr.balance,Xr=jr.plan===null&&un<Ts,Gn=un<Ts;{const ce=le&&le.isOwner===!1;if(Xr&&!ce){n("user",pe),Se(""),Ir([]),n("ai",Af({noPlan:!0,balance:un,requiredCredits:1})),w([{id:"credits-required",title:"Credits required",description:`Keep at least ${Ts} credits available to start builds.`,status:"error"}]),W.error("Credits required",{description:`Top up or pick a plan. Builds can run while you have ${Ts}+ credits.`,action:{label:"Top up",onClick:()=>{window.location.href=iu}}}),wr.current=!1;return}if(Gn&&!ce){n("user",pe),Se(""),Ir([]),n("ai",Af({noPlan:!1,balance:un,requiredCredits:1})),w([{id:"credits-required",title:"More credits needed",description:`Keep at least ${Ts} credits available to start builds.`,status:"error"}]),W.error("More credits needed",{description:`Top up to at least ${Ts} credits to keep building.`,action:{label:"Top up",onClick:()=>{window.location.href=iu}}}),wr.current=!1;return}}const dn=/^\s*(?:rollback|restore|revert|undo)(?:\s+to)?\s+v?(\d+)\s*\.?$/i.exec(pe);if(dn&&!(X!=null&&X.isRescue)&&!F&&U){const ce=parseInt(dn[1],10);try{const{data:Be}=await G.from("build_logs").select("id, prompt, started_at").eq("project_id",U).order("started_at",{ascending:!1}),Ut=(Be??[]).length;if(Ut===0||ce<1||ce>Ut){W.error("Version not found",{description:Ut===0?"No builds recorded yet for this project.":`Only versions 1–${Ut} exist. You asked for v${ce}.`}),wr.current=!1;return}const xr=(Be??[])[Ut-ce];n("user",pe),Se("");const On=await kn(xr.id);if(!On||!On.files||On.files.length===0){W.error("No snapshot for that version",{description:"Snapshots are only kept for builds that completed after the snapshot system shipped."}),n("ai",`Couldn't restore v${ce} — no snapshot saved for that build.`),wr.current=!1;return}const rs=[];for(const yn of On.files){const Zn=(yn.path||yn.name||"").split("/").filter(Boolean);let Un=rs;for(let tn=0;tn<Zn.length;tn++){const Tt=Zn[tn];if(tn===Zn.length-1){const Rn=Un.find(ar=>ar.type==="file"&&ar.name===Tt);Rn?Rn.content=yn.content||void 0:Un.push({name:Tt,type:"file",content:yn.content||void 0})}else{let Rn=Un.find(ar=>ar.type==="folder"&&ar.name===Tt);Rn||(Rn={name:Tt,type:"folder",children:[]},Un.push(Rn)),Un=Rn.children||[]}}}N(rs),T(null),n("ai",`✅ Restored to **v${ce}** — ${On.files.length} files. Original prompt: _"${xr.prompt.slice(0,80)}${xr.prompt.length>80?"…":""}"_`),W.success(`Restored to v${ce}`,{description:`${On.files.length} files restored.`}),wr.current=!1;return}catch(Be){W.error("Rollback failed",{description:Be.message}),wr.current=!1;return}}if(sN([]),X!=null&&X.isRescue||(xy.current=!1),l&&!F){const ce=[...Mn],Be={id:`q-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,text:pe,addedAt:Date.now(),attachments:ce};Rc(xr=>{const On=[...xr,Be];return qi.current=On,On}),Se(""),Ir([]);const Ut=ce.length>0?` with ${ce.length} attachment${ce.length===1?"":"s"}`:"";W.success(`Prompt queued (#${dy.length+1})${Ut} — will run after current build`,{duration:3e3});return}if(wr.current&&!(X!=null&&X.isRescue)&&!F)return;if(l&&!(X!=null&&X.isAutoFix)&&!(X!=null&&X.isRescue)&&!(F&&!it)){W.message("Build in progress — your prompt was queued",{duration:2500}),Rc(ce=>[...ce,{text:pe,attachments:[...Mn]}]),qi.current=[...qi.current,{text:pe,attachments:[...Mn]}];return}wr.current=!0,bd.current=!1;let $e=pe;if(xe&&($e=`[BACKGROUND UPGRADE — preview is live]
6705Upgrade src/content.ts only: set meta.layoutKind, domain navigation, routes (list|grid|calendar|funnel), and 8+ realistic mock rows.
6706
6707ORIGINAL REQUEST:
6708${pe.replace(Pf,"").trim()}`),Mn.length>0){const ce=Mn.map(Be=>Be.name).join(", ");$e=$e?`${$e}
6709
6710📎 Attached: ${ce}`:`📎 Attached: ${ce}`}const Qt=[...Mn],ns=wZ(Qt,k),ur=ns.length>0?tu($l(k,Mo(ns))):k;if(ns.length>0){const ce=ns.map(Be=>({name:Be.filename.split("/").pop()||Be.filename,path:Be.filename,content:Be.content,language:Be.language}));N(ur),ae(ce).catch(Be=>{console.warn("[attachments] Failed to persist attached image assets:",Be)})}X!=null&&X.isRescue||n("user",$e),Se(""),Ir([]);const tr={buildStart:Date.now()};er.current={buildStart:Date.now()},console.log(`[timing] build-start: ${new Date().toISOString()}`);const Na=/PHASE CONTINUATION on an existing project|\*\*Next Phase:\*\*/i.test(pe),Kn=!it;if(Kn&&U&&!Zj.current.has(U)){Zj.current.add(U);try{sessionStorage.removeItem(`sj-defer-warmup:${U}`)}catch{}Bk(U),Pr({action:"start",projectId:U,files:[]}).then(ce=>{ce!=null&&ce.preview_proxy_url&&window.dispatchEvent(new CustomEvent("sj:preview-url-ready",{detail:{projectId:U,url:ce.preview_proxy_url}}))}).catch(ce=>console.warn("[chat] early sandbox boot:",ce))}const Bn=!Kn&&(Sy(ur)||Na),ka=Sy(ur),vl=eZ(pe,ka)?{...ap(pe,ka),source:"keyword"}:await bX(pe,ka),Pn=Mm(pe)&&!/^BUILD TYPE:\s*FULL\s*STACK/i.test(pe)?{...vl,strategy:"website",confidence:Math.max(vl.confidence,.9),reason:"Website/reference URL request without explicit backend requirements",suggestedFeatures:vl.suggestedFeatures.length?vl.suggestedFeatures:["Responsive design","Navigation","Reference-inspired search UI","SEO meta tags","Contact form"],needsDatabase:!1,needsAuth:!1,needsApi:!1,needsRealtime:!1,needsFileStorage:!1,needsBilling:!1,useTemplate:vl.useTemplate==="dashboard-app"?"none":Kn?"saas-landing":vl.useTemplate}:vl,xL=xe&&Pe==="dashboard-app"?"dashboard-app":Pn.useTemplate,kN=Pn.strategy;tr.classifyEnd=Date.now(),console.log(`[timing] classify-intent: ${tr.classifyEnd-tr.buildStart}ms | Strategy: ${kN} via ${Pn.source??"unknown"} (confidence: ${Pn.confidence.toFixed(2)}, reason: ${Pn.reason})`+(Pn.domain?`, domain: ${Pn.domain}`:"")+((HN=Pn.integrations)!=null&&HN.length?`, integrations: ${Pn.integrations.join(",")}`:""));const SN=GX({text:$e,classifierIntegrations:Pn.integrations,mcpServers:de});if(SN&&!(X!=null&&X.isRescue)){const ce=`${U||"new"}:${$e.slice(0,160)}:${de.map(Be=>Be.name).join(",")}`;eN.current!==ce&&(n("ai",SN),eN.current=ce)}const Qh=zX($e)||Pn.needsApi===!0||Pn.strategy==="api-service",yL=Qh?"api":JX($e)?"design":"edit";if(U&&!F&&!Jh.current&&I2(Pn)&&xN&&xN.backend_mode==="studiojungle"&&!(localStorage.getItem(`cloud_enabled_${U}`)==="1"))try{localStorage.setItem(`cloud_enabled_${U}`,"1")}
6710catch{}const CN=Pn.targetPlatform==="mobile"||Pn.targetPlatform==="both",by=oe==="mobile"||oe==="both"||CN,PN=/\bBUILD TYPE:\s*MOBILE/i.test($e);CN&&oe!=="mobile"&&oe!=="both"&&he("mobile"),PN&&(!K.mobileFramework||K.mobileFramework==="none")&&R({...K,mobileFramework:"pwa"});const bL=U&&!F&&by&&!PN&&KX($e)&&!O2($e)&&(!K.mobileFramework||K.mobileFramework==="none"),vL=/\b(react\s*native|expo|flutter|dart|pwa|progressive\s+web|mobile\s+web|web\s+app)\b/i.test($e);if(bL&&!vL){n("ai",`📱 **Mobile Framework**
6711
6712I see you want to build a mobile app. What should Studio Jungle generate?
6713
6714\`\`\`questions
6715{
6716  "intro": "Native apps and mobile web apps ship differently. Pick the output you want before I generate files.",
6717  "questions": [
6718    {
6719      "id": "mobile_framework",
6720      "label": "Mobile framework",
6721      "question": "What should Studio Jungle generate?",
6722      "type": "choice",
6723      "options": [
6724        {"value": "mobile-web", "label": "🌐 Mobile Web / PWA", "description": "Fast browser launch: Vite React, installable PWA, Studio preview and web publish"},
6725        {"value": "react-native", "label": "⚛️ React Native / Expo", "description": "Native app source: Expo TypeScript files, app screens, components, and a matching clickable preview"},
6726        {"value": "flutter", "label": "🦋 Flutter", "description": "Native app source: Dart/Flutter files, Material widgets, and a matching clickable preview"}
6727      ]
6728    }
6729  ]
6730}
6731\`\`\``),wr.current=!1;return}const So=Kn&&!bt?[]:ln,yi=aZ(So),wl=So.length>0?"issue-fix":kN,Wi=hL(wl,So.length>0,$e,X==null?void 0:X.overrideModel),ef=F&&j.some(ce=>ce.id.startsWith("db-"));Hh.current=!!ef;const AN=$e.length>2e3,_N=wl!=="tool"&&wl!=="issue-fix",cs=Fn&&!Bn&&!ef&&_N&&!AN&&!(X!=null&&X.isRescue),Fc=rZ(Wi.model,cs),TN=le&&le.isOwner===!1;if(!TN&&Xr){n("ai",Af({noPlan:!0,balance:un,requiredCredits:Fc})),w([{id:"credits-required",title:"Credits required",description:`Keep at least ${Ts} credits available to start builds.`,status:"error"}]),W.error("Credits required",{description:`Top up or pick a plan. Builds can run while you have ${Ts}+ credits.`,action:{label:"Top up",onClick:()=>{window.location.href=iu}}}),wr.current=!1;return}if(!TN&&un<Fc){n("ai",Af({noPlan:!1,balance:un,requiredCredits:Fc})),w([{id:"credits-required",title:"More credits needed",description:`This build needs ${Fc} credits. You have ${un}.`,status:"error"}]),W.error("More credits needed",{description:`This build needs ${Fc} credits. You have ${un}.`,action:{label:"Top up",onClick:()=>{window.location.href=iu}}}),wr.current=!1;return}const wL=++uN.current;c(!0),v(null),A(0),So.length>0&&at(),ZM(),gi.current=Bn?$o(k):[];let Vi=$o(gi.current),Bc=null;const tf=new Map;let vy=0,nf=0,Nd=0;const EN=ce=>{const Be=tu(ce);Vi=$o(Be),gi.current=$o(Be);const{flatFiles:Ut,pages:xr,preferredPage:On,apis:rs,schema:yn}=_f(Be);N(Be),A(Ut.length),E(xr),M(rs),B(yn),On&&(T(On.html),_||I(On.id),C("preview"))},IN=async()=>{if(Bc&&(window.clearTimeout(Bc),Bc=null),tf.size===0)return;const ce=Array.from(tf.values());tf.clear(),await ae(ce)},ON=(ce,Be)=>{var On;const Ut=Lm(ce);if(!Ut)return;const xr=Ut.includes(".")&&((On=Ut.split(".").pop())==null?void 0:On.toLowerCase())||"text";tf.set(Ut,{name:Ut.split("/").pop()||Ut,path:Ut,content:Be,language:xr==="htm"?"html":xr}),Bc||(Bc=window.setTimeout(()=>{Bc=null,IN().catch(console.error)},700))},jL=ce=>{var Ut,xr,On,rs,yn,Zn;if(ue)return!1;const Be=typeof((Ut=ce.input)==null?void 0:Ut.path)=="string"?Lm(ce.input.path):"";if(!Be)return!1;if(ce.name==="write_file"&&typeof((xr=ce.input)==null?void 0:xr.content)=="string"){if(Bp(Vi,Be)===ce.input.content)return!1;if(!R2(Be,ce.input.content))return Nd+=1,console.warn(`[chat] Rejected incomplete file from write_file: ${Be}`),!1;er.current.streamStart===void 0&&(er.current.streamStart=Date.now(),console.log(`[timing] streamStart: ${er.current.streamStart-er.current.buildStart}ms after buildStart`));const tn=E0(Vi,Be,ce.input.content);return EN(tn),ON(Be,ce.input.content),!0}if(ce.name==="edit_file"||ce.name==="str_replace"){const Un=Bp(Vi,Be),tn=((On=ce.input)==null?void 0:On.old_str)??((rs=ce.input)==null?void 0:rs.search),Tt=((yn=ce.input)==null?void 0:yn.new_str)??((Zn=ce.input)==null?void 0:Zn.replace);if(Un!==null&&typeof tn=="string"&&typeof Tt=="string"){if(!Un.includes(tn))return Nd+=1,!1;const Rn=Un.replace(tn,Tt);if(Rn===Un)return!1;if(!R2(Be,Rn))return Nd+=1,console.warn(`[chat] Rejected incomplete file from ${ce.name}: ${Be}`),!1;er.current.streamStart===void 0&&(er.current.streamStart=Date.now(),console.log(`[timing] streamStart: ${er.current.streamStart-er.current.buildStart}ms after buildStart`));const ar=E0(Vi,Be,Rn);return EN(ar),ON(Be,Rn),!0}}return!1};Bn||N([]);const NL=Date.now();if(_e({prompt:$e,mode:y,provider:qr,use_orchestration:Fn&&!Bn&&y==="app-builder"}).then(ce=>
6731{ce&&(vd.current={id:ce.id,startedAt:NL})}),(()=>{if(Bn||ef||!_N||AN)return!1;if((Pn==null?void 0:Pn.complexity)==="high")return!0;const Be=new Set(["ecommerce","saas","dashboard","social","marketplace"]),Ut=new Set(["fullstack","api-service"]),xr=$e.trim().length>40;return!!(Ut.has(wl)&&xr||Be.has(String(Pn.domain||"").toLowerCase())&&xr)})(),cs){mt({active:!0,phases:AT.map(Be=>({...Be,status:"pending"})),currentPhaseIndex:-1,startedAt:Date.now(),completedAt:null,modelsUsed:[]});const ce=A2(Pn);ce[0].status="running",w(ce)}else if(ef)w(ce=>ce.map(Be=>Be.id==="db-followup"?{...Be,status:"running",description:"AI is generating the application...",logs:["Streaming response..."]}:Be));else if(So.length>0){const ce=(yi==null?void 0:yi.route)||(yi==null?void 0:yi.file)||"failing route";w([{id:"smart-fix-diagnose",title:`Inspect ${ce}`,description:yi!=null&&yi.file?`Reading ${yi.file} and direct imports only`:"Reading the selected route and direct imports only",status:"running"},{id:"smart-fix-locate",title:"Locate exact cause",description:"Use the captured build error to find the smallest fix",status:"pending"},{id:"smart-fix-apply",title:"Apply targeted fix",description:"Patch only affected files",status:"pending"},{id:"smart-fix-verify",title:"Verify route",description:"Run the real preview/build again",status:"pending"}])}else if(Qh)w(tb($e,"api"));else if(yL==="design")w(tb($e,"design"));else if(Bn)w(tb($e,"edit"));else{const ce=Kn?wX():A2(Pn);if(ce.length>0)ce[0].status="running",w(ce);else{const Be=hX(pe,Pn.strategy);Be.length>0?(Be[0].status="running",w(Be)):w([{id:"analyze",title:"Analyzing Request",description:"Understanding requirements and planning implementation",status:"running",logs:["Received user prompt"]}])}}const kL=jZ(ur,pe,wl),RN=bZ({userText:$e,strategy:wl,classification:Pn,existingFiles:ur,previousErrors:So.map(ce=>typeof ce=="string"?ce:JSON.stringify(ce)).slice(0,8)});ae([{name:"plan.md",path:Rp,content:RN,language:"md"}]).catch(ce=>console.warn("[studio-memory] Failed to save plan.md:",ce));const SL=`
6732
6733--- ACTIVE STUDIO MEMORY PLAN (${Rp}) ---
6734\`\`\`md
6735${nu(RN,1800)}
6736\`\`\`
6737--- END ACTIVE STUDIO MEMORY PLAN ---`;let rf="";if(by){const ce=Xh.current||K.mobileFramework||"react-native",Be=K.mobileBackend||"supabase";ce==="react-native"?rf=`
6738
6739IMPORTANT: This is a NATIVE MOBILE APP using React Native (Expo). You MUST:
67401. Generate React Native / Expo source code (NOT a single HTML prototype and NOT a Vite-only web app). Use \`expo-router\` for navigation.
67412. Use React Native components: View, Text, ScrollView, TouchableOpacity, FlatList, TextInput, Image, etc.
67423. Use \`react-native-paper\` or \`@rneui/themed\` for UI components (cards, buttons, lists).
67434. Use \`expo-linear-gradient\`, \`expo-image\`, \`expo-camera\`, \`expo-notifications\` for native features.
67445. File structure: app/(tabs)/ for tab navigation, app/(auth)/ for auth screens, src/components/ for shared components.
67456. Use StyleSheet.create() for styles (NOT Tailwind — unless nativewind is set up).
67467. Include app.json / app.config.ts with proper Expo configuration.
67478. Include package.json with all required dependencies.
67489. Backend: ${Be==="firebase"?"Use Firebase (Firestore, Firebase Auth, Cloud Functions). Include firebase.ts config file.":Be==="both"?"Use both Supabase AND Firebase. Include config for both.":"Use Supabase (Database, Auth, Edge Functions). Include supabase.ts client config."}
674910. Generate an HTML preview that shows the actual MOBILE APP SCREEN, not a second phone mockup. Studio Jungle already supplies the outer device frame.
675011. ALSO generate all the actual .tsx / .ts source files for the React Native project.
675112. The HTML preview MUST be a clickable prototype: bottom tabs switch screens, cards open detail views, search/filter controls update content, and the primary CTA/FAB opens a form or modal that can save state and show a toast/success state.
675213. The HTML preview MUST use max-width:430px, a fixed bottom nav with icons, mobile-first spacing, 44px+ tap targets, and realistic data/loading/empty/error/offline states where relevant.
675314. Do NOT show a code tree or architecture slide inside the user-facing preview unless explicitly requested. Put source files in Files.
675415. Every local import must resolve. If App.tsx imports ./screens/MapScreen, ./screens/VisitsScreen, ./components/CafeSheet, etc., emit those files in the same response. If you cannot emit every file, keep the prototype self-contained in App.tsx and remove the imports.
675516. Required native files on first build: package.json, app.json or app.config.ts, tsconfig.json, App.tsx or app/_layout.tsx, at least 3 screen files, shared components, and src/lib data/services. index.html may exist only as a Studio preview companion, never as the only file.`:ce==="flutter"?rf=`
6756
6757IMPORTANT: This is a NATIVE MOBILE APP using Flutter (Dart). You MUST:
67581. Generate Flutter / Dart source code (NOT a single HTML prototype and NOT a Vite-only web app). Use proper Material Design 3 widgets.
67592. Use proper Flutter project structure: lib/main.dart, lib/screens/, lib/widgets/, lib/models/, lib/services/.
67603. Use \`go_router\` or named routes for navigation with bottom navigation bar.
67614. Use \`provider\` or \`riverpod\` for state management.
67625. Use Material widgets: Scaffold, AppBar, BottomNavigationBar, Card, ListTile, TextField, ElevatedButton, etc.
67636. Include pubspec.yaml with all dependencies.
67647. Include proper theming with ThemeData and ColorScheme.
67658. Backend: ${Be==="firebase"?"Use Firebase (cloud_firestore, firebase_auth, cloud_functions). Include firebase_options.dart.":Be==="both"?"Use both Supabase AND Firebase.":"Use Supabase (supabase_flutter package). Include supabase_config.dart."}
67669. Generate an HTML preview that shows the actual MOBILE APP SCREEN, not a second phone mockup. Studio Jungle already supplies the outer device frame.
676710. ALSO generate all the actual .dart source files for the Flutter project.
676811. Use \`flutter_screenutil\` for responsive sizing.
676912. The HTML preview MUST be a clickable prototype: bottom tabs switch screens, cards open detail views, search/filter controls update content, and the primary CTA/FAB opens a form or modal that can save state and show a toast/success state.
677013. The HTML preview MUST use max-width:430px, a fixed bottom nav with icons, mobile-first spacing, 44px+ tap targets, and realistic data/loading/empty/error/offline states where relevant.
677114. Do NOT show a code tree or architecture slide inside the user-facing preview unless explicitly requested. Put source files in Files.
677215. Every local import must resolve. If lib/main.dart imports screens/widgets/services, emit those files in the same response. If you cannot emit every file, keep the prototype self-contained and remove the imports.
677316. Required native files on first build: pubspec.yaml, lib/main.dart, at least 3 screen files, shared widgets, models, and services. index.html may exist only as a Studio preview companion, never as the only file.`:rf=`
6774
6775IMPORTANT: This is a MOBILE WEB / PWA APP using Vite + React + TypeScript. You MUST NOT generate a single index.html prototype.
67761. Generate a real multi-file app: package.json, vite.config.ts, tsconfig.json, tsconfig.node.json, tailwind.config.ts, postcss.config.js, index.html, src/main.tsx, src/vite-env.d.ts, src/App.tsx, src/index.css, at least 3 files under src/screens/, at least 2 shared files under src/components/, and src/lib/data.ts or src/lib/state.ts.
67772. If any strategy says to generate exactly one HTML file, ignore that strategy because target=mobile overrides it.
67783. Every local import must resolve. If App.tsx imports ./screens/MapScreen, ./screens/VisitsScreen, ./components/CafeSheet, etc., emit those files in the same response.
67794. Use max-width: 430px layouts centered on the page.
67805. Use minimum 44px touch targets for all buttons and interactive elements.
67816. Use a FIXED BOTTOM NAVIGATION BAR with icons and labels (NOT a top navbar with text links).
67827. Use mobile-first design patterns: full-width cards, stacked layouts, swipeable components.
67838. Render the actual app screen only. Do NOT draw a second phone/device frame; Studio Jungle already wraps Mobile Preview in device chrome.
67849. Make the app clickable: bottom tabs switch screens, cards open detail views, search/filter controls update content, and the primary CTA/FAB opens a form or modal that saves state and shows a toast/success state.
678510. Use FAB (Floating Action Button) for primary actions where useful.
678611. Design for thumb-reachable zones.
678712. All text should be readable on small screens (min 14px body text).
678813. NO desktop patterns: no sidebars, no wide data tables, no breadcrumbs, no hover-dependent menus.
678914. Cards should be full-width with rounded corners and shadows.
679015. Forms should have full-width inputs with large submit buttons (h-12 min).
679116. Include realistic data plus loading, empty, error, and offline states where relevant.
679217. index.html may be the Vite entry and static fallback, but it must never be the only file for a mobile app.`}const CL=z();let wy="";const jy=$e.match(/https?:\/\/[^\s)<>"']+/i);if(jy&&!Qh){const ce=jy[0].replace(/[.,;:!?)]+$/,"");try{n("ai",`🌐 Fetching reference site **${ce}** to analyze its design...`);const Be=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/fetch-website",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},body:JSON.stringify({url:ce})});if(Be.ok){const Ut=await Be.json(),xr=(Ut.colors||[]).slice(0,10).join(", "),On=(Ut.fonts||[]).slice(0,5).join(", "),rs=(Ut.headings||[]).slice(0,10).map(yn=>`- ${yn}`).join(`
6793`);wy=`
6794
6795[REFERENCE WEBSITE — match this site's visual style, layout patterns, tone, and structure]
6796URL: ${Ut.url}
6797Title: ${Ut.title||Ut.ogTitle||"(none)"}
6798Description: ${Ut.description||"(none)"}
6799Color Palette (from CSS): ${xr||"(none)"}
6800Fonts Used: ${On||"(none)"}
6801Top Headings / Section Titles:
6802${rs||"(none)"}
6803
6804REFERENCE BODY HTML (cleaned, use to infer layout/sections/nav structure — DO NOT copy verbatim, recreate in your own high-quality way):
6805\`\`\`html
6806${(Ut.bodyHtml||"").slice(0,25e3)}
6807\`\`\`
6808
6809INSTRUCTIONS:
6810- Use the SAME overall structure (hero → features → pricing → footer, etc. — whatever the reference has)
6811- Use a SIMILAR color scheme (pick 2-3 colors from the palette above)
6812- Match the TONE and content style of the reference
6813- Recreate the key sections with your own polished content
6814- Do NOT copy verbatim text — paraphrase and adapt for the user's actual prompt
6815- The user's actual prompt below tells you WHAT TO BUILD — the reference tells you HOW IT SHOULD LOOK/FEEL`,n("ai",`✅ Analyzed **${Ut.title||ce}** — found ${(Ut.colors||[]).length} colors, ${(Ut.fonts||[]).length} fonts, ${(Ut.headings||[]).length} sections. Using as design reference.`)}else{const Ut=await Be.text().catch(()=>"");n("ai",`⚠️ Could not fetch **${ce}** (${Be.status}). Building without reference.${Ut?"\n`"+Ut.slice(0,200)+"`":""}`)}}catch(Be){n("ai",`⚠️ Reference fetch error: ${(Be==null?void 0:Be.message)||Be}. Building without reference.`)}}else jy&&Qh&&(wy=`
6816
6817[API INTEGRATION REQUEST — do NOT use as design reference]
6818The user included an API/curl/webhook URL. Treat it as functionality to wire into the app, not a website to visually analyze.
6819Required behavior:
6820- Never expose pasted API keys in frontend code.
6821- If the platform already redacted/stored a secret, reference the stored secret name.
6822- Otherwise ask for a \`\`\`secret_request\`\`\` for the key/header value.
6823- Create a Supabase Edge Function proxy for the API call.
6824- Wire the frontend form/button to call the edge function.
6825- Show loading, success, and error states.`);let sf="";try{sf=sessionStorage.getItem("sj_pending_reference_context")||"",sf&&sessionStorage.removeItem("sj_pending_reference_context")}catch{}const PL=eT(Qt,$e),AL=Kn&&!by&&!SX($e)?`
6826
6827=== FIRST-BUILD SPEED RULES (MANDATORY) ===
6828This is the FIRST build. Your #1 goal is SPEED TO PREVIEW. Generate ONLY these files:
68291. src/index.css — design tokens, global styles (Tailwind or vanilla CSS)
68302. src/App.tsx — routing with Home and NotFound routes only
68313. src/pages/Home.tsx — complete, visually polished hero section + 2-3 content sections with REAL content (no placeholder)
68324. src/components/Navbar.tsx — responsive navigation bar
68335. src/components/Footer.tsx — site footer with links
68346. src/pages/NotFound.tsx — styled 404 page
6835
6836Do NOT generate: Auth, Login, Signup, Dashboard, Database, API endpoints, Admin, Settings, CRM, migrations, or any backend code.
6837Do NOT plan architecture for future features.
6838Do NOT read or inspect any existing files.
6839Just generate the 6 files above with beautiful, production-quality content.
6840
6841After writing these files, end your response with a "Next Phase" question suggesting 3-5 features the user can add:
6842- Additional pages (About, Contact, Pricing, Blog)
6843- Authentication system
6844- Dashboard with data visualization
6845- API integrations
6846- Database and CRUD operations
6847=== END FIRST-BUILD SPEED RULES ===
6848`:"",DN=$e+AL+kL+SL+rf+CL+wy+PL,_L=DN+(sf?`
6849
6850${sf}`:""),Ny=[...r,{id:"new",role:"user",content:DN}].filter(ce=>ce.role==="user"||ce.role==="ai").map(ce=>({role:ce.role==="ai"?"assistant":"user",content:ce.id==="new"?_L:ce.role==="ai"?cm(ce.content):ce.content})),kd=cs?"orchestrate-build":"chat";er.current={buildStart:Date.now()},console.log(`[timing] buildStart: ${new Date(er.current.buildStart).toISOString()}`),console.log(`[chat] Starting build: endpoint=${kd}, shouldOrchestrate=${cs}, mode=${y}, provider=${qr}, isFirstBuild=${Kn}`);let MN=!1;if(cs&&U)try{const{data:ce}=await G.from("project_settings").select("auto_apply_approved_builds").eq("project_id",U).single();MN=!!(ce!=null&&ce.auto_apply_approved_builds)}catch{}const LN=cs&&!MN;LN&&p(!0),console.log(`[chat] URL: https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/${kd}`);const $N=await UX();let FN=null;if(!Kn)try{const{buildGithubContext:ce}=await ju(async()=>{const{buildGithubContext:Be}=await import("./github-context-Dv4ueDwl.js");return{buildGithubContext:Be}},__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]));FN=await ce($N,U)}catch{}const bi=new AbortController;ko.current=bi,ua.current=!1;let BN=!1;const UN=Bn?6e5:cs?9e5:Kn?18e4:6e5,TL=window.setTimeout(()=>{bi.signal.aborted||(console.warn(`[chat] Build exceeded ${UN}ms wall-clock budget; aborting cleanly.`),BN=!0,bi.abort(new DOMException("Build timed out","TimeoutError")))},UN);let ky=!1;const Ha=(ce,Be)=>{ky||(ky=!0,W9(ce,Be))};try{const ce=await fetch(`https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/${kd}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},signal:bi.signal,body:JSON.stringify({messages:Ny,mode:y,buildStrategy:wl,useToolUse:!0,isFirstBuild:!Bn,isAutoFix:bt,useApplyOnAccept:LN||f?!0:ue,composerMode:ts,substrate_deepen:xe,substrate_fast_path:Pe||void 0,intent:{domain:Pn.domain,aestheticHint:Pn.aestheticHint,integrations:Pn.integrations,aiSpecialists:Pn.aiSpecialists,needsRealtime:Pn.needsRealtime,needsFileStorage:Pn.needsFileStorage,needsBilling:Pn.needsBilling,source:Pn.source,useTemplate:xL},previousErrors:So.length>0?So:void 0,job_id:crypto.randomUUID(),currentFiles:Zr(ur).map(Et=>({path:Et.path,content:Et.content})),designMode:Er!=="auto"?Er:void 0,referenceUrl:Hs||void 0,referenceSummary:Ic||void 0,referenceArtifacts:Qt.map(({name:Et,type:Ht,size:Wt,kind:Vt,summary:Xt,dataUrl:Ct})=>({name:Et,type:Ht,size:Wt,kind:Vt,summary:Xt,dataUrl:Vt==="image"?Ct:void 0})),githubContext:FN||void 0,mcpServers:de.length>0?de:void 0,provider:qr,model:Wi.model,modelRoles:wd(Wi.activeRole),useOrchestration:cs,multi_agent_enabled:cs&&Fn,user_id:$N||void 0,projectId:U,settings:{buildMode:$,architecture:K,capabilities:Y,aiBehavior:Z,lifecycleStage:O,focusArea:ne,target:oe,brandGuidelines:lt(fe),existingInfrastructure:{edgeFunctions:yt.map(Et=>({name:Et.function_name,displayName:Et.display_name,description:Et.description,methods:Et.methods,path:Et.path,category:Et.feature_category,status:Et.status})),secrets:zt.map(Et=>({name:Et.secret_name,configured:Et.is_configured}))}}})});console.log(`[chat] Response status: ${ce.status}, ok: ${ce.ok}, hasBody: ${!!ce.body}`);const Be=ce.headers.get("X-Model-Used");Be&&v(Be);const Ut=ce.headers.get("X-Fast-Path"),xr=ce.headers.get("X-Requires-Deepen")==="1";Ut&&xr&&!(X!=null&&X.substrateDeepen)&&(jd.current={original:Gh.current,fastPath:Ut});const On=ce.headers.get("X-Agent-Run-Id");On&&(g(On),p(!0));const rs=ce.headers.get("X-Credits-Remaining");if(rs!==null){const Et=parseInt(rs,10);Number.isNaN(Et)||Ne.applyBalanceDelta(Et)}const yn=ce.headers.get("X-Stored-Secrets");
6850if(yn&&(le!=null&&le.id)){const Et=yn.split(",").filter(Boolean);if(Et.length>0){const Ht=`sj-secrets-toast:${le.id}`;let Wt=[];try{Wt=JSON.parse(sessionStorage.getItem(Ht)||"[]")}catch{}const Vt=Et.filter(Xt=>!Wt.includes(Xt));if(Vt.length>0){try{sessionStorage.setItem(Ht,JSON.stringify([...new Set([...Wt,...Vt])]))}catch{}W.success(Vt.length===1?`🔒 Saved as ${Vt[0]}`:`🔒 Saved ${Vt.length} secrets: ${Vt.join(", ")}`,{description:"Your keys are encrypted and reference-only — the AI never sees the value.",duration:6e3})}}}if(!ce.ok||!ce.body){const Et=await ce.text();console.error("Chat error:",ce.status,Et);let Ht="Failed to get a response",Wt,Vt;try{const Ve=JSON.parse(Et);Ht=Ve.error||Ht,Wt=Ve.code,Vt=Ve.redirect}catch{}if(ce.status===402&&(Wt==="NO_PLAN"||Wt==="INSUFFICIENT_CREDITS")){const Ve=Wt==="NO_PLAN";if(!Ve&&Wt==="INSUFFICIENT_CREDITS"&&(await Am(Ne.refresh,Ne)).balance>=Fc&&Dc.current<2)return Dc.current+=1,wr.current=!1,c(!1),await new Promise(tt=>window.setTimeout(tt,600)),xi(F||pe,{...X,isRescue:!0});W.error(Ve?"Subscribe to keep building":"Out of credits",{description:Ht,duration:1e4,action:{label:Ve?"See plans":"Top up",onClick:()=>{window.location.href=Vt||"/pricing"}}}),s(`💳 **${Ve?"Subscribe to continue":"Out of credits"}**
6851
6852${Ht}
6853
6854👉 [${Ve?"See plans":"Top up credits"}](/pricing)`),w([{id:"billing",title:Ve?"Subscription required":"Out of credits",description:Ht,status:"error"}]),wr.current=!1,c(!1);return}let Xt="Build Error",Ct="";ce.status===401||ce.status===403?(Xt="Session expired",Ct="Your sign-in expired. Sign out and back in, then retry — your files are safe."):ce.status===429?(Xt="Slow down",Ct="Hit the request limit. Wait 30 seconds and retry."):ce.status===402?(Xt="Out of credits",Ct=`${Ht||"You've used your monthly credits."} [Top up →](/pricing)`):ce.status===500||ce.status===502||ce.status===503?(Xt="Provider hiccup",Ct=`The AI provider returned ${ce.status}. Usually clears in a minute. Retry, or try the Fast route when the provider is busy.
6855
6856\`${Ht.slice(0,200)}\``):Ct=Ht||`Request failed (HTTP ${ce.status}). Retry, or simplify the prompt.`;const vt=Ao(`**${Xt}** — ${Ct}
6857
6858Your files weren't touched. Retry the same prompt to continue.`);s(vt),Ha(!1,`http_${ce.status}`),w(Ve=>Ve.some(nn=>nn.id.startsWith("smart-"))?Ve.map(nn=>nn.status==="running"||nn.status==="pending"?{...nn,status:"error"}:nn):[{id:"error",title:Xt,description:Ht,status:"error"}]),W.error(`${Xt}: ${Ht}`,{duration:8e3}),No(),c(!1),wr.current=!1;return}const Zn=ce.body.getReader(),Un=new TextDecoder;let tn="",Tt="",Rn="",ar="",Sa=0,As=!1,Hr=null,Ws=1,Yn=6,pn=null,Wr=[];const Vn=Et=>{s(cm(Et))},Wa=new Set(["codegen","validation"]),Vs=new Set(["codegen","validation","planning","schema"]),Os=18e4,Gi=async()=>Promise.race([Zn.read(),new Promise((Et,Ht)=>setTimeout(()=>Ht(new Error("STREAM_STALL")),Os))]);let Sd=0;try{for(;;){const{done:Et,value:Ht}=await Gi();if(Et){console.log(`[chat] Stream done after ${Sd} chunks, fullContent length: ${Tt.length}, codeContent length: ${Rn.length}`);break}Sd++;const Wt=Un.decode(Ht,{stream:!0});Sd<=3&&console.log(`[chat] Chunk #${Sd} (${Wt.length} bytes):`,Wt.slice(0,200)),tn+=Wt;let Vt;for(;(Vt=tn.indexOf(`
6859`))!==-1;){let Xt=tn.slice(0,Vt);if(tn=tn.slice(Vt+1),Xt.endsWith("\r")&&(Xt=Xt.slice(0,-1)),Xt.startsWith(":")||Xt.trim()===""||!Xt.startsWith("data: "))continue;const Ct=Xt.slice(6).trim();if(Ct==="[DONE]")break;try{const vt=JSON.parse(Ct),Ve=(VN=(WN=vt.choices)==null?void 0:WN[0])==null?void 0:VN.delta;(Ve==null?void 0:Ve.build_state)==="halted_iteration_limit"&&(ct(!0),cy.current||(Wh.current=!0));const tt=Ve==null?void 0:Ve.agent_event;if(tt&&typeof tt=="object")if(tt.kind==="agent_started"&&typeof tt.agent=="string")h(tt.agent),d(`${tt.agent[0].toUpperCase()}${tt.agent.slice(1)} ${typeof tt.round=="number"&&tt.round>1?`round ${tt.round} `:""}started`);else if(tt.kind==="agent_finished"&&typeof tt.agent=="string")d(`${tt.agent[0].toUpperCase()}${tt.agent.slice(1)} done`);else if(tt.kind==="reviewer_decision"){const en=String(tt.decision||"unknown");d(`Reviewer: ${en}`)}else tt.kind==="run_finished"&&h(null);if((GN=vt.pending_exec)!=null&&GN.resume_token&&Array.isArray(vt.pending_exec.calls)){pn=vt.pending_exec.resume_token,Wr=vt.pending_exec.calls,console.log(`[chat] pending_exec received: ${Wr.length} call(s); will run in WebContainer after stream ends`);continue}if((KN=vt.checkpoint)!=null&&KN.resume_token){Hr=vt.checkpoint.resume_token,typeof vt.checkpoint.segment=="number"&&(Ws=vt.checkpoint.segment),typeof vt.checkpoint.max_segments=="number"&&(Yn=vt.checkpoint.max_segments);continue}const rn=I6(Ve);rn&&(rn.type==="phase_start"&&(ar=rn.phase_id||""),mt(en=>{const Ze=[...en.phases],Rt=Ze.findIndex(hn=>hn.id===rn.phase_id);if(Rt===-1)return en;if(rn.type==="phase_start")return Ze[Rt]={...Ze[Rt],status:"running",startedAt:Date.now(),model:rn.model||Ze[Rt].model},v(`${rn.model} (Phase ${(rn.phase_index??0)+1}/${rn.total_phases??5})`),Tt||s(`⏳ ${rn.phase_name}...`),{...en,phases:Ze,currentPhaseIndex:rn.phase_index??Rt,modelsUsed:[...new Set([...en.modelsUsed,rn.model||""])]};if(rn.type==="phase_end"){const hn=Ze[Rt].startedAt||Date.now();return Ze[Rt]={...Ze[Rt],status:"done",completedAt:Date.now(),durationMs:Date.now()-hn},{...en,phases:Ze}}return rn.type==="phase_error"?(Ze[Rt]={...Ze[Rt],status:"error",error:rn.error},{...en,phases:Ze}):en}));const Le=Ve==null?void 0:Ve.content,sn=typeof Le=="string"?Le:(Array.isArray(Le)||Le&&typeof Le=="object","");if(sn){Tt+=sn,Vn(Tt);const en=!cs||Vs.has(ar)||!ar;en&&(Rn+=sn);const Ze=Date.now();Ze-Sa>300&&(Mc(Rn,!0),Sa=Ze)}const ht=Ve==null?void 0:Ve.tool_use;if(ht!=null&&ht.name){const en=SU(ht.name,ht.input||{},!Bn);if(en&&(u(en),d(en)),ht.name==="ask_next_phase"){cy.current=!0;const Ze=(YN=ht.input)==null?void 0:YN.options;if(Array.isArray(Ze)&&Ze.length>0){const Rt=Ze.filter(hn=>
6859typeof(hn==null?void 0:hn.label)=="string"&&hn.label.length>0).map(hn=>({label:hn.label,prompt:hn.description&&hn.description.length>0?hn.description:hn.label}));Rt.length>0&&sN(Rt)}}if(jL(ht)&&(vy+=1,Kn&&U&&vy>=2))try{const Ze=`sj-defer-warmup:${U}`;sessionStorage.getItem(Ze)&&(sessionStorage.removeItem(Ze),window.dispatchEvent(new CustomEvent("sj:first-preview-kick",{detail:{projectId:U}})))}catch{}}if(ht&&ue){const en=(JN=ht==null?void 0:ht.input)==null?void 0:JN.path;if(typeof en=="string"&&en.length>0){const Ze=(hn,Sn,nr="")=>{for(const us of hn){const vi=nr?`${nr}/${us.name}`:us.name;if(us.type==="file"&&vi===Sn)return us.content??"";if(us.type==="folder"&&us.children){const Va=Ze(us.children,Sn,vi);if(Va!==null)return Va}}return null},Rt=Ze(k,en);if(ht.name==="write_file"&&typeof((XN=ht==null?void 0:ht.input)==null?void 0:XN.content)=="string")nf+=1,$t({path:en,newContent:ht.input.content,oldContent:Rt,kind:Rt===null?"create":"modify",toolUseId:ht.id});else if((ht.name==="edit_file"||ht.name==="str_replace")&&Rt!==null){const hn=((ZN=ht==null?void 0:ht.input)==null?void 0:ZN.old_str)??((QN=ht==null?void 0:ht.input)==null?void 0:QN.search),Sn=((ek=ht==null?void 0:ht.input)==null?void 0:ek.new_str)??((tk=ht==null?void 0:ht.input)==null?void 0:tk.replace);if(typeof hn=="string"&&typeof Sn=="string")if(Rt.includes(hn)){const nr=Rt.replace(hn,Sn);nr!==Rt&&(nf+=1,$t({path:en,newContent:nr,oldContent:Rt,kind:"modify",toolUseId:ht.id}))}else Nd+=1}else ht.name==="delete_file"&&Rt!==null&&(nf+=1,$t({path:en,newContent:"",oldContent:Rt,kind:"delete",toolUseId:ht.id}))}}}catch(vt){if(vt instanceof SyntaxError&&!Ct.endsWith("}")){tn=Xt+`
6860`+tn;break}console.error("[chat] Error processing SSE line:",vt==null?void 0:vt.message,"jsonStr:",Ct==null?void 0:Ct.slice(0,200))}}}}catch(Et){if((Et==null?void 0:Et.message)==="STREAM_STALL"){As=!0,console.warn("[chat] Stream stalled — recovering partial content");try{Zn.cancel()}catch{}}else throw Et}if(tn.trim())for(const Et of tn.split(`
6861`)){if(!Et||!Et.startsWith("data: "))continue;const Ht=Et.slice(6).trim();if(Ht!=="[DONE]")try{const Vt=(sk=(rk=(nk=JSON.parse(Ht).choices)==null?void 0:nk[0])==null?void 0:rk.delta)==null?void 0:sk.content,Xt=typeof Vt=="string"?Vt:"";if(Xt){const Ct=Xt.match(/\[\[__SJ_REFUND:(\d+):([a-z_]+)__\]\]/);if(Ct){const vt=parseInt(Ct[1],10);if(!Number.isNaN(vt)&&vt>0){try{Ne.refresh()}catch{}W.success(`Refunded ${vt} credit${vt===1?"":"s"} — first attempt produced no code`,{duration:5e3})}const Ve=Xt.replace(/\[\[__SJ_REFUND:\d+:[a-z_]+__\]\]/g,"");Ve&&(Tt+=Ve,(!cs||Vs.has(ar)||!ar)&&(Rn+=Ve),Vn(Tt))}else Tt+=Xt,(!cs||Vs.has(ar)||!ar)&&(Rn+=Xt),Vn(Tt)}}catch{}}for(;pn&&Wr.length>0;){const Et=pn,Ht=Wr;pn=null,Wr=[],console.log(`[chat] Running ${Ht.length} exec call(s) for token=${Et}`);let Wt=[];try{const Ve=i3(Ht,k);Ve?(Wt=Ve.results,Ve.files!==k&&(N(Ve.files),ae([{name:"package.json",path:"package.json",content:((ak=Zr(Ve.files).find(nn=>nn.path==="package.json"))==null?void 0:ak.content)||"",language:"json"}]).catch(console.warn))):Wt=await NU(Ht,k)}catch(Ve){console.warn("[chat] exec batch threw:",Ve.message),Wt=Ht.map(nn=>({tool_use_id:nn.tool_use_id,content:`❌ Local execution error: ${Ve.message}`}))}let Vt;try{Vt=await fetch(`https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/${kd}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},signal:bi.signal,body:JSON.stringify({resume_token:Et,exec_results:Wt,messages:[],mode:y,projectId:U,provider:qr,model:Wi.model,modelRoles:wd(Wi.activeRole),useToolUse:!0,useApplyOnAccept:ue,composerMode:ts})})}catch(Ve){console.warn("[chat] exec resume fetch threw:",Ve.message);break}if(!Vt.ok||!Vt.body){console.warn(`[chat] exec resume returned ${Vt.status}`);break}const Xt=Vt.body.getReader(),Ct=new TextDecoder;let vt="";try{for(;;){const Ve=await Promise.race([Xt.read(),new Promise((tt,rn)=>setTimeout(()=>rn(new Error("STREAM_STALL")),Os))]);if(Ve.done)break;vt+=Ct.decode(Ve.value,{stream:!0});let nn;for(;(nn=vt.indexOf(`
6862`))!==-1;){let tt=vt.slice(0,nn);if(vt=vt.slice(nn+1),tt.endsWith("\r")&&(tt=tt.slice(0,-1)),tt.startsWith(":")||tt.trim()===""||!tt.startsWith("data: "))continue;const rn=tt.slice(6).trim();if(rn==="[DONE]")break;try{const Le=JSON.parse(rn);if((ik=Le.pending_exec)!=null&&ik.resume_token&&Array.isArray(Le.pending_exec.calls)){pn=Le.pending_exec.resume_token,Wr=Le.pending_exec.calls;continue}if((ok=Le.checkpoint)!=null&&ok.resume_token){Hr=Le.checkpoint.resume_token,typeof Le.checkpoint.segment=="number"&&(Ws=Le.checkpoint.segment),typeof Le.checkpoint.max_segments=="number"&&(Yn=Le.checkpoint.max_segments);continue}const sn=(uk=(ck=(lk=Le.choices)==null?void 0:lk[0])==null?void 0:ck.delta)==null?void 0:uk.content,ht=typeof sn=="str
6862ing"?sn:"";ht&&(Tt+=ht,(!cs||Vs.has(ar)||!ar)&&(Rn+=ht),Vn(Tt))}catch{}}}}catch(Ve){if((Ve==null?void 0:Ve.message)==="STREAM_STALL"){As=!0,console.warn("[chat] exec resume stream stalled");try{Xt.cancel()}catch{}}else console.warn("[chat] exec resume stream error:",Ve==null?void 0:Ve.message)}}for(Hr&&Bn&&(console.warn("[chat] Incremental edit hit server checkpoint; stopping auto-resume to avoid long-running small edits."),Hr=null,As=!0);Hr;){const Et=Hr;if(Hr=null,Ws>Yn){console.warn(`[chat] hit client max_segments (${Yn}) — stopping auto-resume`);break}let Ht;try{Ht=await fetch(`https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/${kd}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},signal:bi.signal,body:JSON.stringify({resume_token:Et,messages:[],mode:y,projectId:U,provider:qr,model:Wi.model,modelRoles:wd(Wi.activeRole),useToolUse:!0,useApplyOnAccept:ue,composerMode:ts})})}catch(Ct){console.warn("[chat] resume fetch threw:",Ct.message);break}if(!Ht.ok||!Ht.body){console.warn(`[chat] resume fetch returned ${Ht.status} — stopping auto-resume`);break}const Wt=Ht.body.getReader(),Vt=new TextDecoder;let Xt="";try{for(;;){const Ct=await Promise.race([Wt.read(),new Promise((Ve,nn)=>setTimeout(()=>nn(new Error("STREAM_STALL")),Os))]);if(Ct.done)break;Xt+=Vt.decode(Ct.value,{stream:!0});let vt;for(;(vt=Xt.indexOf(`
6863`))!==-1;){let Ve=Xt.slice(0,vt);if(Xt=Xt.slice(vt+1),Ve.endsWith("\r")&&(Ve=Ve.slice(0,-1)),Ve.startsWith(":")||Ve.trim()===""||!Ve.startsWith("data: "))continue;const nn=Ve.slice(6).trim();if(nn==="[DONE]")break;try{const tt=JSON.parse(nn);if((dk=tt.checkpoint)!=null&&dk.resume_token){Hr=tt.checkpoint.resume_token,typeof tt.checkpoint.segment=="number"&&(Ws=tt.checkpoint.segment),typeof tt.checkpoint.max_segments=="number"&&(Yn=tt.checkpoint.max_segments);continue}const rn=(fk=(hk=(pk=tt.choices)==null?void 0:pk[0])==null?void 0:hk.delta)==null?void 0:fk.content,Le=typeof rn=="string"?rn:"";Le&&(Tt+=Le,(!cs||Vs.has(ar)||!ar)&&(Rn+=Le),Vn(Tt))}catch{}}}}catch(Ct){if((Ct==null?void 0:Ct.message)==="STREAM_STALL"){As=!0,console.warn("[chat] Resume stream stalled — recovering partial content");try{Wt.cancel()}catch{}}else console.warn("[chat] Resume stream error:",Ct==null?void 0:Ct.message)}}if(console.log(`[chat] Stream complete. fullContent: ${Tt.length} chars, codeContent: ${Rn.length} chars, timedOut: ${As}`),No(),As&&Tt){const Ht=jl(Rn||Tt).length,Wt=window.__sjStallRetries||0,Vt=2;!Bn&&Ht>0&&Wt<Vt?(window.__sjStallRetries=Wt+1,console.log(`[chat] stream stall auto-resume (retry ${Wt+1}/${Vt}, ${Ht} files recovered)`),W.info("Auto-continuing the build…",{duration:3e3}),setTimeout(()=>{se.current&&se.current("Continue from where the previous turn was cut off — finish any incomplete files and emit any missing pages from the original plan.")},600)):Ht>0?(Tt+=Bn?`
6864
6865---
6866_Recovered ${Ht} file${Ht===1?"":"s"} before the small edit timed out. I stopped instead of chaining another long build; retry the edit if anything is missing._`:`
6867
6868---
6869_Recovered ${Ht} file${Ht===1?"":"s"} after multiple auto-continue attempts. If anything looks incomplete, send "continue" to finish._`,Vn(Tt),W.warning(Bn?`Recovered ${Ht} file${Ht===1?"":"s"} before timeout`:`Recovered ${Ht} files — send "continue" if anything is missing`,{duration:6e3}),window.__sjStallRetries=0):(Tt+=`
6870
6871---
6872_The build couldn't complete a single file before stalling. Try a shorter prompt or retry in a moment._`,Vn(Tt),W.error("Build stalled before any code was generated — retry in a moment",{duration:8e3}),Ha(!1,"stream_stall_no_recovery"),window.__sjStallRetries=0)}else As||(window.__sjStallRetries=0);if(Tt){const Et=cs&&Rn?Rn:Tt,Ht=jl(Et);if(console.log(`[chat] Final code extraction: ${Ht.length} blocks from ${Et.length} chars. Files:`,Ht.map(Wt=>Wt.filename)),Mc(Et,!1),i(cm(Tt)),y==="data-copilot"){const Vt=jl(Tt).find(Xt=>Xt.language==="sql");if(Vt&&ie.length>0){const Xt=ie[0],Ct=Vt.content.trim();Te(Ct),st(!0),Ee(null),Me(null),C("preview");try{const vt=await Je(Xt.id,Ct);Me(vt.rows||[]),W.success(`Query returned ${vt.rowCount} rows`)}catch(vt){Ee(vt.message),W.error("Query failed: "+vt.message)}finally{st(!1)}}else ie.length||(Ee("No database connected. Please connect a database first."),C("preview"))}else if(y==="workflow"){const Wt=IK(Tt);Wt&&(xt(Wt),C("preview"))}else{const Wt=jl(Et);if(Wt.length>0){const Vt=!!(Pn.needsAuth||Pn.needsDatabase||Pn.needsApi),Xt=Wt.filter(Le=>Le.filename.endsWith(".sql")&&/CREATE\s+TABLE/i.test(Le.content)),Ct=Wt.some(Le=>/login|register|signup|auth|profile/i.test(Le.filename)||/\b(signIn|signUp|useAuth|AuthProvider|createClient)\b/.test(Le.content));Vt&&Ct&&Xt.length===0&&(gt("SCHEMA_CHECK: Auth/login UI generated 
6872without schema.sql (CREATE TABLE). Emit users/profile tables before declaring build complete."),w(Le=>Le.some(sn=>sn.id==="schema-missing")?Le.map(sn=>sn.id==="schema-missing"?{...sn,status:"error",description:"schema.sql with CREATE TABLE is required for auth/database features"}:sn):[...Le,{id:"schema-missing",title:"Database schema missing",description:"Auth/login requires schema.sql with user tables",status:"error",logs:["No CREATE TABLE migration found — backend cannot work without schema"]}])),C("preview");const vt=tu($l(gi.current,Mo(Wt))),Ve=Zr(vt).map(Le=>({name:Le.path.split("/").pop()||Le.path,path:Le.path,content:Le.content,language:Le.language})),nn=tp(Wt),tt=np(Wt);if(await Promise.all([ae(Ve),ve(nn),re(tt),Fe(Wt.map(Le=>({filename:Le.filename,content:Le.content})))]).catch(Le=>{console.error(Le),W.error("Preview updated locally, but cloud file save failed. Refresh may show older files.",{duration:8e3})}),U){const Le=Wt.filter(ht=>/^supabase\/functions\/[^/]+\/index\.ts$/.test(ht.filename)),sn=Wt.filter(ht=>ht.filename.endsWith(".sql")&&/CREATE\s+TABLE/i.test(ht.content));if(Le.length>0||sn.length>0){const ht=await Jt().catch(()=>!1);w(Ze=>[...Ze,{id:"deploy-project",title:"Backend changes staged",description:ht?`${Le.length} function(s), ${sn.length} migration(s) — click Deploy when ready`:`${Le.length} function(s), ${sn.length} migration(s) — use Cloud tab to connect Supabase`,status:"pending",logs:[`${Le.length} edge function${Le.length===1?"":"s"} + ${sn.length} migration${sn.length===1?"":"s"} staged.`,"Preview runs with mock/local data during build — no Supabase redirect.",ht?'Click "Deploy now" when you want schema/functions on your database.':"Open Cloud → Connect Supabase → Provision when you need a live database."],action:{label:ht?"Deploy now":"Connect & deploy",onClick:()=>en()}}]);const en=async()=>{w(Ze=>Ze.map(Rt=>Rt.id==="deploy-project"?{...Rt,status:"running",logs:["Deploying to project infrastru
6872cture..."]}:Rt));try{const Ze=await qt(U,Wt.map(Or=>({filename:Or.filename,content:Or.content,language:Or.language})),{projectName:(le==null?void 0:le.name)||U,onProvisionStart:()=>{w(Or=>Or.map(Rr=>Rr.id==="deploy-project"?{...Rr,logs:[...Rr.logs||[],"🔧 Database not provisioned — auto-provisioning now..."]}:Rr))},onNeedRegion:()=>iN(U),onNeedsConnect:async()=>{w(Rr=>Rr.map(Gs=>Gs.id==="deploy-project"?{...Gs,logs:[...Gs.logs||[],"🔗 Redirecting to Supabase to authorize (one-time)…"]}:Gs));const Or=await Ae();return Or.redirecting?!1:Or.success?(W.success("Supabase connected — provisioning your database…"),!0):(W.error(Or.error||"Could not connect Supabase"),!1)},onProvisionDone:(Or,Rr)=>{if(w(Gs=>Gs.map(Ki=>Ki.id==="deploy-project"?{...Ki,logs:[...Ki.logs||[],Or?"✅ Database provisioned successfully! Retrying migration...":"❌ Auto-provisioning failed"]}:Ki)),Or&&Rr){const Gs=Rr.supabase_url.replace(/^https?:\/\//,"").replace(/\.supabase\.co.*/,".supabase.co");W.success(`Database ready · ${Gs} · ${Rr.region}`,{duration:8e3})}}}),Rt=[],hn=Ze.functions.pending||0,Sn=!!Ze.schema.pending||!!Ze.pendingConnect;Ze.functions.deployed>0&&Rt.push(`✅ ${Ze.functions.deployed} function(s) deployed`),hn>0&&Rt.push(`⏸ ${hn} function(s) staged until Supabase is connected`),Ze.functions.failed>0&&Rt.push(`❌ ${Ze.functions.failed} function(s) failed`);const nr=[];for(const Or of Ze.functions.results)Or.success||(Rt.push(`  → ${Or.slug}: ${Or.error}`),nr.push(`**${Or.slug}**: ${Or.error}`));Ze.autoProvisioned&&Rt.push("🔧 Database was auto-provisioned for this project"),Ze.schema.success?Rt.push("✅ Schema migrated to project DB"):Sn&&sn.length>0?Rt.push("⏸ Schema migration staged until Supabase is connected"):sn.length>0&&(Rt.push(`❌ Schema migration: ${Ze.schema.error||"failed"}`),nr.push(`**Schema migration**: ${Ze.schema.error||"failed"}`));const us=hn>0||Sn,vi=Ze.functions.failed>0||nr.length>0,Va=!us&&Ze.functions.failed===0&&(sn.length===0||Ze.schema.success);if(Va&&window.dispatchEvent(new CustomEvent("sj:infra-changed",{detail:{projectId:U}})),w(Or=>Or.map(Rr=>Rr.id==="deploy-project"?{...Rr,status:Va?"done":us&&!vi?"pending":"error",description:Va?"All artifacts deployed successfully":us&&!vi?"Backend changes staged - connect Supabase to deploy":"Some deployments failed",logs:Rt,action:Va?void 0:us&&!vi?{label:"Connect & deploy",onClick:()=>en()}:Rr.action}:Rr)),Ze.functions.deployed>0){W.success(`🚀 ${Ze.functions.deployed} API(s) deployed live to project`);try{if(Ze.functions.results.filter(Rr=>Rr.success).map(Rr=>Rr.slug).length>0){N(Gs=>{const Ki=JSON.parse(JSON.stringify(Gs)),kk=EL=>{var Sk;for(const Yi of EL)Yi.type==="folder"&&Yi.children?kk(Yi.children):Yi.type==="file"&&Yi.content&&(Sk=Yi.name)!=null&&Sk.endsWith(".html")&&Yi.content.includes("SUPABASE_URL")&&(Yi.content=Yi.content.replace(/SUPABASE_URL\s*=\s*['"](?:''|"")?['"]/g,"SUPABASE_URL='https://xfmlsevleobdlnjqxmdi.supabase.co'").replace(/SUPABASE_KEY\s*=\s*['"](?:''|"")?['"]/g,"SUPABASE_KEY='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo'"))};return kk(Ki),Ki});const Rr=P;if(Rr.length>0){const Gs=Rr.find(Ki=>Ki.id===_)||Rr[0];Gs!=null&&Gs.html&&T(Gs.html)}}}catch(Or){console.error("[chat] URL injection error:",Or)}}if(Ze.autoProvisioned&&Ze.schema.success&&W.success("Database auto-provisioned and schema deployed!",{duration:5e3}),us&&!vi)n("ai",`**Backend changes staged**
6873
6874I generated the schema/function files but did not push them because Supabase is not connected yet. Connect Supabase, then click **Connect & deploy** to run the migration.`),W.info("Backend changes staged - connect Supabase to deploy",{duration:8e3,action:{label:"Connect",onClick:()=>en()}});else if(!Va){const Or=nr.map(Rr=>`- ${Rr}`).join(`
6875`);n("ai",`⚠️ **Deployment partially failed**
6876
6877${Ze.functions.deployed>0?`✅ ${Ze.functions.deployed} function(s) deployed successfully
6878`:""}**Failed items:**
6879${Or}
6880
6881**Common causes:**
6882- Missing environment secrets (API keys)
6883- Syntax errors in edge functions
6884- Database schema conflicts
6885
6886**Next steps:**
68871. Check the error details above
68882. Fix the root cause, then click **Retry Deploy** in the toast
68893. Or re-run your prompt to regenerate the code`),W.error("Some deployments failed — check chat for details",{duration:1e4,action:{label:"Retry Deploy",onClick:()=>en()}})}}catch(Ze){w(Rt=>Rt.map(hn=>hn.id==="deploy-project"?{...hn,status:"error",description:Ze.message,logs:[`❌ ${Ze.message}`]}:hn)),n("ai",`⚠️ **Deployment failed**
6890
6891**Error:** ${Ze.message}
6892
6893**Your code was generated successfully** — only the deployment step failed.
6894
6895**Next steps:**
68961. Check your internet connection
68972. Ensure your project has Cloud enabled
68983. Click **Retry Deploy** in the toast notification`),W.error(`Deploy failed: ${Ze.message}`,{duration:1e4,action:{label:"Retry Deploy",onClick:()=>en()}})}}}}const rn=TK(Wt);if(rn.length>0&&ie.length>0){const Le=ie[0],{ddl:sn,dml:ht}=EK(rn),en=[...sn,...ht];W.info(`Executing ${en.length} SQL statement(s) on ${Le.name}...`);const Ze=[];w(Sn=>[...Sn,{id:"sql-exec",title:`SQL Execution (${Le.name})`,description:`Running ${en.length} statement(s) against ${Le.db_type} database`,status:"running",logs:["Starting SQL execution..."],sqlResults:[]}]);for(const Sn of en)try{const nr=await Je(Le.id,Sn);Ze.push({sql:Sn,status:"success",rowCount:nr==null?void 0:nr.rowCount})}catch(nr){Ze.push({sql:Sn,status:"error",error:nr.message}),console.error("SQL execution failed:",Sn,nr.message)}const Rt=Ze.filter(Sn=>Sn.status==="success").length,hn=Ze.filter(Sn=>Sn.status==="error").length;w(Sn=>Sn.map(nr=>nr.id==="sql-exec"?{...nr,status:hn>0?"error":"done",description:`${Rt} succeeded, ${hn} failed`,logs:Ze.map(us=>us.status==="success"?`✅ ${us.sql.slice(0,60)}...`:`❌ ${us.sql.slice(0,40)}... — ${us.error}`),sqlResults:Ze}:nr)),Rt>0&&W.success(`✅ Executed ${Rt} SQL statement(s) on ${Le.name}`),hn>0&&W.error(`⚠️ ${hn} statement(s) failed — check Plan tab for details`)}}else{const Vt=/```(?:questions|secret_request|secret-request|autodb|checkpoint)\b/.test(Tt),Xt=/\?\s*$/.test(pe.trim())||/^(what|why|how|when|where|which|can|could|do|does|did|is|are|was|were|should|would|will|tell me|explain|show me)\b/i.test(pe.trim());if(Vt){console.log("[chat] No code blocks but a protocol block (questions/secret_request/autodb/checkpoint) was emitted — suppressing no-code warning");const Ct=vy>0||nf>0,vt=/✅|build complete|done|restyled|wired|updated|created|added|fixed/i.test(Tt);if(!Ct&&vt&&!Xt)if(gZ(pe,Vi))w(Ve=>Ve.map(nn=>nn.status==="running"?{...nn,status:"done",description:"Feature already in project"}:nn));else{const Ve=Ao(Nd>0?"**No visible change applied.** The model tried to edit existing files, but the patch text did not match the current project. I did not change your files. Retry the same prompt and I'll force a targeted read-then-edit pass.":"**No visible change applied.** The model returned a success/next-step response without any file mutation. I did not change your files. Retry the prompt and I'll force it to emit real edits before saying done.");s(Ve),i(Ve),w(nn=>nn.map(tt=>tt.status==="running"?{...tt,status:"error",description:"No file changes were applied"}:tt)),W.error("No file changes were applied — retry will force a real edit",{duration:7e3})}else w(Ve=>Ve.map(nn=>nn.status==="running"?{...nn,status:"done"}:nn))}else{const Ct=cs?(Yt.phases||[]).filter(tt=>tt.status==="error"&&tt.error):[],vt=Ct.length>0?Ct.map(tt=>`- **${tt.name}:** ${tt.error}`).join(`
6899`):null;if(cs&&vt&&!bd.current){bd.current=!0,console.log("[chat] Pipeline failed before code generation — auto-retrying with single-model mode"),s(`⚠️ **Pipeline failed during generation**
6900
6901${vt}
6902
6903⏳ Automatically retrying with single-model mode for reliability...`),W.info("Pipeline failed — retrying with direct model...",{duration:4e3}),mt(tt=>({...tt,active:!1,completedAt:Date.now()})),w([{id:"retry-single",title:"Retrying (Single Model)",description:"Pipeline failed — using direct model call for reliability",status:"running",logs:["Auto-retry triggered after pipeline error..."]}]);try{const tt=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},signal:bi.signal,body:JSON.stringify({messages:Ny,mode:y,provider:qr,model:Wi.model,modelRoles:wd(Wi.activeRole),projectId:U,settings:{buildMode:$,architecture:K,capabilities:Y,aiBehavior:Z,lifecycleStage:O,focusArea:ne,target:oe,brandGuidelines:lt(fe),existingInfrastru
6903cture:{edgeFunctions:yt.map(Le=>({name:Le.function_name,displayName:Le.display_name,description:Le.description,methods:Le.methods,path:Le.path,category:Le.feature_category,status:Le.status})),secrets:zt.map(Le=>({name:Le.secret_name,configured:Le.is_configured}))}}})}),rn=tt.headers.get("X-Model-Used");if(rn&&v(rn),tt.ok&&tt.body){const Le=tt.body.getReader(),sn=new TextDecoder;let ht="",en="";for(;;){const{done:Ze,value:Rt}=await Promise.race([Le.read(),new Promise((Sn,nr)=>setTimeout(()=>nr(new Error("STREAM_STALL")),45e3))]);if(Ze)break;ht+=sn.decode(Rt,{stream:!0});let hn;for(;(hn=ht.indexOf(`
6904`))!==-1;){let Sn=ht.slice(0,hn).trim();if(ht=ht.slice(hn+1),!Sn.startsWith("data: "))continue;const nr=Sn.slice(6).trim();if(nr==="[DONE]")break;try{const vi=(xk=(gk=(mk=JSON.parse(nr).choices)==null?void 0:mk[0])==null?void 0:gk.delta)==null?void 0:xk.content;if(vi){en+=vi,s(en);const Va=Date.now();Va-Sa>500&&(Mc(en,!0),Sa=Va)}}catch{break}}}if(en){Tt=en,Rn=en,Mc(en,!1),i(en);const Ze=jl(en);if(Ze.length>0){C("preview"),w(Sn=>Sn.map(nr=>nr.id==="retry-single"?{...nr,status:"done",description:`Generated ${Ze.length} file(s)`}:nr)),W.success(`✅ Retry succeeded — generated ${Ze.length} file(s)`,{duration:5e3});const Rt=$l(gi.current,Mo(Ze)),hn=Zr(Rt).map(Sn=>({name:Sn.path.split("/").pop()||Sn.path,path:Sn.path,content:Sn.content,language:Sn.language}));await Promise.all([ae(hn),ve(tp(Ze)),re(np(Ze)),Fe(Ze.map(Sn=>({filename:Sn.filename,content:Sn.content})))]).catch(Sn=>{console.error(Sn),W.error("Preview updated locally, but cloud file save failed. Refresh may show older files.",{duration:8e3})})}else w(Rt=>Rt.map(hn=>hn.id==="retry-single"?{...hn,status:"error",description:"No code blocks in retry response"}:hn));return}}}catch(tt){console.error("Auto-retry after pipeline error failed:",tt)}}if(w(tt=>{const rn=tt.filter(Le=>Le.id.startsWith("smart-"));return rn.length>0?rn.map(Le=>Le.status==="running"?{...Le,status:"error"}:Le):[{id:"no-code",title:"No Code Generated",description:vt||"The model returned analysis text but no file code blocks.",status:"error"}]}),!vt&&!xy.current){xy.current=!0;const tt=(()=>{for(let rn=r.length-1;rn>=0;rn--)if(r[rn].role==="user")return r[rn].content;return""})();if(tt){if(Kn&&(/\bBUILD TYPE:\s*(LANDING|WEBSITE|FULL\s*STACK|MOBILE)/i.test(tt)||Pn.useTemplate==="saas-landing"||Pn.useTemplate==="dashboard-app"||Mm(tt)))console.log("[chat] No code generated — auto-rescuing via fast substrate (same prompt)"),s(`⏳ **Retrying with instant preview path** — first attempt returned no files. Re-running with the locked fast build shell.
6905
6906_No charge for the failed turn — credits will refund._`),W.info("Auto-retrying with instant preview…",{duration:4e3});else{const Le=((yk=Pd.find(en=>en.id===qr))==null?void 0:yk.backendModel)||"auto",sn=bN(Le),ht=yN(tt);console.log("[chat] No code generated — auto-rescuing with",sn,"and reformulated prompt"),s(`⏳ **Re-routing through a stronger model** — first attempt returned analysis only. Auto-retrying with explicit build framing.
6907
6908_No charge for the failed turn — credits will refund._`),W.info("Auto-retrying with a stronger route…",{duration:4e3}),Lc.current=!0,c(!1),wr.current=!1,setTimeout(()=>{xi(ht,{overrideModel:sn,isRescue:!0})},50);return}Lc.current=!0,c(!1),wr.current=!1,setTimeout(()=>{xi(tt,{isRescue:!0})},50);return}}const nn=Ao(vt?`**Build failed before code generation.** Files untouched.
6909
6910\`${vt.slice(0,300)}\``:'**No code generated — auto-rescue also failed.** Files untouched. The model may not have understood the request even with explicit build framing. Try rephrasing the goal more concretely (e.g. instead of "analytics working" → "an Analytics page with chart cards for daily revenue, top products, and traffic sources"), or break it into a smaller piece.');s(nn),Ha(!1,vt?"build_pre_code_error":"no_code_after_rescue"),W.error(vt?"Build failed before code generation.":"Auto-rescue also returned no code. See message for next steps.",{duration:7e3})}}}}else if(bd.current)s(Ao("**Empty response.** Your files are safe — the AI provider returned no content this time. This usually clears on retry. If it doesn't, try a smaller prompt or use the Standard route.")),Ha(!1,"empty_response"),W.error("Empty response — retry to continue.",{duration:6e3});else{bd.current=!0;const Et=((bk=Pd.find(Vt=>Vt.id===qr))==null?void 0:bk.backendModel)||"auto",Ht=Et.includes("opus")?Et:Et.includes("sonnet")?"claude-opus-4-8":"claude-sonnet-4-6",Wt=cs?"Pipeline timed out":"Empty response";console.log(`[chat] ${Wt} — auto-retrying with ${Ht}`),s(`⏳ **${Wt}** — auto-retrying with a stronger model for reliability...`),W.info(`${Wt} — retrying automatically…`,{duration:4e3}),mt(Vt=>({...Vt,active:!1,completedAt:Date.now()})),w([{id:"retry-single",title:"Retrying (Single Model)",description:"Pipeline timed out — using direct model call for reliability",status:"running",logs:["Auto-retry triggered..."]}]);try{const Vt=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${await Lo()}`},signal:bi.signal,body:JSON.stringify({messages:Ny,mode:y,provider:qr,model:Ht,modelRoles:wd("forced"),useToolUse:!0,composerMode:ts,projectId:U,settings:{buildMode:$,architecture:K,capabilities:Y,aiBehavior:Z,lifecycleStage:O,focusArea:ne,target:oe,brandGuidelines:lt(fe),existingInfrastru
6910cture:{edgeFunctions:yt.map(Ct=>({name:Ct.function_name,displayName:Ct.display_name,description:Ct.description,methods:Ct.methods,path:Ct.path,category:Ct.feature_category,status:Ct.status})),secrets:zt.map(Ct=>({name:Ct.secret_name,configured:Ct.is_configured}))}}})}),Xt=Vt.headers.get("X-Model-Used");if(Xt&&v(Xt),Vt.ok&&Vt.body){const Ct=Vt.body.getReader(),vt=new TextDecoder;let Ve="",nn="";for(;;){const{done:tt,value:rn}=await Promise.race([Ct.read(),new Promise((sn,ht)=>setTimeout(()=>ht(new Error("STREAM_STALL")),45e3))]);if(tt)break;Ve+=vt.decode(rn,{stream:!0});let Le;for(;(Le=Ve.indexOf(`
6911`))!==-1;){let sn=Ve.slice(0,Le).trim();if(Ve=Ve.slice(Le+1),!sn.startsWith("data: "))continue;const ht=sn.slice(6).trim();if(ht==="[DONE]")break;try{const Ze=(jk=(wk=(vk=JSON.parse(ht).choices)==null?void 0:vk[0])==null?void 0:wk.delta)==null?void 0:jk.content;if(Ze){nn+=Ze,s(nn);const Rt=Date.now();Rt-Sa>500&&(Mc(nn,!0),Sa=Rt)}}catch{break}}}if(nn){Tt=nn,Rn=nn,Mc(nn,!1),i(nn);const tt=jl(nn);if(tt.length>0){C("preview"),w(sn=>sn.map(ht=>ht.id==="retry-single"?{...ht,status:"done",description:`Generated ${tt.length} file(s)`}:ht)),W.success(`✅ Retry succeeded — generated ${tt.length} file(s)`,{duration:5e3});const rn=$l(gi.current,Mo(tt)),Le=Zr(rn).map(sn=>({name:sn.path.split("/").pop()||sn.path,path:sn.path,content:sn.content,language:sn.language}));await Promise.all([ae(Le),ve(tp(tt)),re(np(tt)),Fe(tt.map(sn=>({filename:sn.filename,content:sn.content})))]).catch(sn=>{console.error(sn),W.error("Preview updated locally, but cloud file save failed. Refresh may show older files.",{duration:8e3})})}else w(rn=>rn.map(Le=>Le.id==="retry-single"?{...Le,status:"error",description:"No code blocks in retry response"}:Le))}else w(rn=>rn.map(Le=>Le.id==="retry-single"?{...Le,status:"error"}:Le)),s(Ao("**Empty response — retry also failed.** Your files are untouched. Try a shorter prompt, or retry in a moment.")),Ha(!1,"empty_after_retry"),W.error("Empty response from the AI provider. Try again or shorten the prompt.",{duration:6e3})}else w(vt=>vt.map(Ve=>Ve.id==="retry-single"?{...Ve,status:"error"}:Ve)),s(Ao("**Retry failed.** Anthropic may be having a moment. Wait 30 seconds and retry — your files are safe.")),Ha(!1,"retry_failed"),W.error("Retry failed — wait a moment and try again.",{duration:6e3})}catch(Vt){console.error("Auto-retry failed:",Vt),w(Ct=>Ct.map(vt=>vt.id==="retry-single"?{...vt,status:"error",description:Vt.message}:vt));const Xt=`**Auto-retry failed.** ${Vt.message}
6912
6913Your files are safe — retry manually, or switch to the Fast route when the provider is under load.`;s(Ao(Xt)),Ha(!1,"auto_retry_threw")}}}catch(ce){console.error("[chat] OUTER CATCH - Stream error:",ce,"stack:",ce==null?void 0:ce.stack);const Be=bi.signal.reason,Ut=BN||(Be==null?void 0:Be.name)==="TimeoutError"||/timed out|timeout/i.test((Be==null?void 0:Be.message)||"");if(ua.current||(ce==null?void 0:ce.name)==="AbortError"&&!Ut){console.warn("[chat] Build cancelled by user — skipping error UI");return}const On=Ut?"Build timed out":(ce==null?void 0:ce.message)||"Network error",rs=Ut||On.toLowerCase().includes("timeout")||On.toLowerCase().includes("aborted"),yn=On.toLowerCase().includes("network")||On.toLowerCase().includes("fetch");let Zn=`**Connection error** — ${On}
6914
6915Your files are safe. `;rs?Zn+="Request timed out. Break your prompt into smaller steps, or switch to Fast routing.":yn?Zn+="Check your internet, then retry.":Zn+="Retry the prompt. If it persists, simplify the request or pick a different routing tier.",s(Ao(Zn)),Ha(!1,rs?"timeout":yn?"network":"unknown"),w(Un=>Un.some(tn=>tn.id.startsWith("smart-"))?Un.map(tn=>tn.status==="running"?{...tn,status:"error"}:tn):[{id:"error",title:rs?"Timeout":"Connection Error",description:On,status:"error"}]),W.error(`Connection error: ${On}`,{duration:6e3}),No()}finally{window.clearTimeout(TL),await IN().catch(console.error),No();const ce=ua.current;if(c(!1),wr.current=!1,Hh.current=!1,ko.current===bi&&(ko.current=null,ua.current=!1),vd.current){const yn=vd.current.id,Zn=Date.now()-vd.current.startedAt;try{o({durationMs:Zn})}catch{}const Un=r[r.length-1];let tn=j.some(pn=>pn.status==="error")||ln.length>0;const Tt=Zr(Vi).filter(pn=>Ul(pn.path)&&!fp(pn.path,pn.content)),Rn=Tt.map(pn=>pn.path);er.current.totalStreamTime=Date.now();const ar=er.current.emittedFileCount||0;if(console.log("[timing] Final Build Timings:",{buildStart:new Date(er.current.buildStart).toISOString(),streamStartOffsetMs:er.current.streamStart?er.current.streamStart-er.current.buildStart:0,planningDurationMs:er.current.firstFileTime&&er.current.streamStart?er.current.firstFileTime-er.current.streamStart:0,firstFileTimeOff
6915setMs:er.current.firstFileTime?er.current.firstFileTime-er.current.buildStart:0,totalStreamTimeMs:er.current.totalStreamTime-er.current.buildStart,previewVisibleTimeOffsetMs:q?Date.now()-er.current.buildStart:null}),!ce&&ar>0&&Tt.length<ar){const pn=`[chat] File integrity mismatch: AI emitted ${ar} valid blocks but only ${Tt.length} files were persisted.`;console.error(pn),tn=!0,gt(`FILE_COUNT_MISMATCH: ${pn}`),w(Wr=>[...Wr.filter(Vn=>Vn.id!=="file-integrity-mismatch"),{id:"file-integrity-mismatch",title:"File integrity mismatch",description:`Generated ${ar}, saved ${Tt.length}. Recovery required.`,status:"error"}]),W.error(`File mismatch: generated ${ar}, saved ${Tt.length}`)}const Sa=Tt.length>0&&!tn,As=ce?"cancelled":tn?"failed":Sa?"completed":"empty";if(!ky&&!ce&&(As==="completed"?Ha(!0,"build_completed"):As==="empty"?Ha(!1,"empty_build"):As==="failed"&&Ha(!1,"build_failed")),U&&As==="completed"&&!ce&&!(X!=null&&X.substrateDeepen)&&jd.current&&vN.current!==U){const{original:pn,fastPath:Wr}=jd.current;vN.current=U,jd.current=null,Nt(`${Pf}
6916${pn}`),console.log(`[chat] Queued substrate deepen (${Wr}) after fast preview`)}if(U&&As==="completed"&&Tt.length>0){const pn={action:"update-blueprint",projectId:U,promptSummary:pe.slice(0,800),filesTouched:Rn.slice(0,60)};(async()=>{var Vs;const Wr="https://xfmlsevleobdlnjqxmdi.supabase.co",Vn="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo",Wa=await Lo().catch(()=>null);for(let Os=1;Os<=3;Os++){try{const Gi=await fetch(`${Wr}/functions/v1/chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wa||Vn}`,apikey:Vn},body:JSON.stringify(pn)});if(Gi.ok?((Vs=await Gi.json())==null?void 0:Vs.ok)===!0:!1)return;Os===3&&console.error("[blueprint] update failed after 3 attempts",{projectId:U,promptSummaryHead:pe.slice(0,120),status:Gi.status})}catch(Gi){Os===3&&console.error("[blueprint] update threw after 3 attempts",{projectId:U,promptSummaryHead:pe.slice(0,120),error:Gi.message})}Os<3&&await new Promise(Gi=>setTimeout(Gi,Math.pow(2,Os)*1e3))}})()}const Hr=tn?(Nk=j.find(pn=>pn.status==="error"))==null?void 0:Nk.description:void 0,Ws=yZ(k,Dp),Yn=vZ(Ws,{userText:pe,status:As,fileNames:Rn,model:b||void 0,error:Hr});ae([{name:"build-notes.md",path:Dp,content:Yn,language:"md"}]).catch(pn=>console.warn("[studio-memory] Failed to save build-notes.md:",pn)),dt(yn,{status:As,files_generated:Tt.length,file_names:Rn,plan_steps:j,error_message:Hr,ai_response_preview:(Un==null?void 0:Un.role)==="ai"?Un.content.slice(0,2e3):void 0,model_used:b||void 0,orchestration_phases:Yt.active?Yt.phases:void 0,duration_ms:Zn}),!ce&&!tn&&Tt.length>0&&(kt(yn,{files:k}),ee(pe,Rn,b||void 0).catch(console.error),S&&rt(S)),vd.current=null}Yt.active&&mt(yn=>({...yn,completedAt:Date.now()}));const Be=r[r.length-1];(Be==null?void 0:Be.role)==="ai"&&_0(Be.content,j).forEach(Zn=>{const Un=P0(Zn);on(Zn,Un==null?void 0:Un.name)});let Ut=!1;const xr=j.some(yn=>yn.status==="error"),On=k.filter(yn=>yn.type==="file"&&yn.content);if(!ce&&!xr&&On.length>0&&U&&tZ({isIncremental:Bn,shouldOrchestrate:cs,prompt:pe,generatedFileCount:On.length,isAutoFix:bt,buildIncomplete:Wh.current})&&(Ut=(await mZ(On,j,n,w,Zn=>{if(!se.current||Zn.length===0)return;Lc.current=!0;const Un=Zn.slice(0,8).map((tn,Tt)=>`${Tt+1}. ${tn}`).join(`
6917`);se.current(`Post-build review found issues. REPAIR ONLY — minimal targeted fixes, no rebuild.
6918
6919${Un}`,{overrideModel:"claude-haiku-4-5",isAutoFix:!0})})).triggeredRepair),!ce){const yn=Zr(Vi).filter(Yn=>Ul(Yn.path)&&!fp(Yn.path,Yn.content)),Zn=j.some(Yn=>Yn.status==="error"&&!(yn.length>0&&/no files generated/i.test(Yn.description||""))),Un=yn.length>0&&!Zn&&ln.length===0;let tn=t1(Zr(Vi));const Tt=tn.length>0?HE(tn):{files:tn,added:[]};if(Tt.added.length>0&&(tn=Tt.files,console.log(`[chat] auto-patched package.json deps before notify: ${Tt.added.join(", ")}`),U)){const Yn=Tt.files.find(pn=>pn.path==="package.json");Yn&&(ae([{name:"package.json",path:"package.json",content:Yn.content,language:"json"}]).catch(pn=>console.warn("[chat] dep patch persist failed:",pn)),G.functions.invoke("e2b-preview-runtime",{body:{action:"add_deps",project_id:U,deps:Tt.added,files:[{path:"package.json",content:Yn.content}]}}).catch(pn=>console.warn("[chat] dep add_deps failed:",pn)))}const Rn=tn.length>0?n1(tn):null,ar=Rn&&l0(Rn)?KE(Rn).length:0,Sa=u7(tn),As=Bn?2e3:750;await new Promise(Yn=>setTimeout(Yn,As));let Hr=null;if(!Zn&&U&&Un)try{let pn=0;const Wr=2;for(let Vn=0;Vn<8;Vn++){const{data:Wa}=await G.functions.invoke("e2b-preview-runtime",{body:{action:"build_status",project_id:U}});if(!Wa)break;if(o3(Wa)&&pn<Wr){if(pn++,console.log(`[chat] silent preview auto-restart ${pn}/${Wr} (phase=${Wa.phase}, healthy=${Wa.previewHealthy})`),window.dispatchEvent(new CustomEvent("sj:auto-restart-preview")),Vn<7){await new Promise(Os=>setTimeout(Os,6e3));continue}break}const Vs=PU(Wa);if(Vs.kind==="ok"){Hr=null;break}if(Vs.kind==="failed"){if(Hr=Vs.error,Vn<7){await new Promise(Os=>setTimeout(Os,3e3));continue}break}if(Vn<7){await new Promise(Os=>setTimeout(Os,4e3));continue}break}}catch(Yn){console.error("[chat] build_status polling failed:",Yn),Hr=(Yn==null?void 0:Yn.message)||"Server error while polling preview status"}Hr&&/recovery command was killed|preview isn't responding/i.test(Hr)&&(Hr=null);const Ws=AU({planHasError:Zn,previewError:Hr,featureComplete:Un,depCheckErrorC
6919ount:ar,autoStubCount:Sa,repairHandoff:Ut,buildCancelled:ce,skippedHandoff:Lc.current,buildGeneration:wL,activeBuildGeneration:uN.current});if(Lc.current&&(Lc.current=!1),!Ws.notify&&!Ws.success&&!Un&&yn.length===0&&!ce){const Yn=!Bn&&yn.length===0;W.error("Build produced no files",{description:Yn?'The model returned no code. Click Retry, or rephrase the goal more concretely (e.g. "a landing page with a hero, 3 feature cards, and a contact form").':"Click Retry — the AI will read existing files before editing.",duration:8e3}),w(pn=>pn.map(Wr=>Wr.status==="running"?{...Wr,status:"error",description:"No files generated — retry"}:Wr))}if(Ws.notify){const Yn=(le==null?void 0:le.name)||"Your project",pn=U===(le==null?void 0:le.id);pn&&rL(Ws.success?"Build complete":"Build needs attention",Ws.success?`${Yn} is ready to preview.`:Ws.message?`${Yn}: ${Ws.message}`:`${Yn} finished with errors.`),Ws.success?(ln.length>0&&at(),w(Wr=>Wr.map(Vn=>Vn.status==="running"?{...Vn,status:"done"}:yn.length>0&&/no files generated/i.test(Vn.description||"")?{...Vn,status:"done",description:"Files generated"}:Vn)),W.success("Build complete",{description:"Preview is ready. You can queue the next task anytime."}),U&&(le!=null&&le.name)&&I2(Pn)&&tn.some(Vn=>/\.sql$/i.test(Vn.path)&&/CREATE\s+TABLE/i.test(Vn.content))&&(async()=>{try{const{data:Vn}=await G.from("project_cloud_config").select("env_vars").eq("project_id",U).maybeSingle(),Wa=(Vn==null?void 0:Vn.env_vars)||{};if(Wa.SUPABASE_URL&&Wa.SUPABASE_ANON_KEY)return;const Vs=await iN(U);if(!Vs)return;W.info("Setting up your database…",{description:"Pick completed — provisioning now."}),await fy(U,le.name,Vs)}catch(Vn){console.warn("[chat] post-build auto-provision skipped:",Vn)}})()):Hr&&pn?W.error("Build failed — preview is broken",{description:Hr.slice(0,240)}):Sa>0&&!Ut&&pn?W.error("Build needs attention",{description:`${Sa} placeholder file(s) need real content — repair will run or retry the prompt.`}):ar>0&&Hr&&!Ut&&pn&&!Wh.current?W.error("Build needs attention",{description:`${ar} missing import/route issue(s) — check the build log.`}):Zn&&pn&&W.error("Build needs attention",{description:"One or more plan steps failed. Check the build log for details."})}}const rs=qi.current;if(rs.length>0){const yn=rs[0],Zn=rs.slice(1);Rc(Zn),qi.current=Zn;const Un=Array.isArray(yn.attachments)?yn.attachments:[];Un.length>0&&Ir(Un),W.info(`Processing queued prompt: "${yn.text.slice(0,50)}${yn.text.length>50?"...":""}"`,{duration:3e3}),setTimeout(()=>{var tn;(tn=Xn.current)==null||tn.call(Xn,yn.text)},500)}}},wN=(F,X)=>{try{const pe=xi(F,X);return pe&&typeof pe.catch=="function"?pe.catch(xe=>{console.error("[chat] handleSend rejected",xe);try{W.error("Build crashed — please retry. Engineering has been notified.",{duration:6e3}),w(Pe=>[...Pe.filter(He=>He.id!=="handle-send-crash"),{id:"handle-send-crash",title:"Build crashed",description:xe instanceof Error?xe.message.slice(0,200):String(xe).slice(0,200),status:"error"}]),c(!1)}catch{}}):Promise.resolve()}catch(pe){console.error("[chat] handleSend threw synchronously",pe);try{W.error("Build crashed — please retry.",{duration:6e3}),w(xe=>[...xe.filter(Pe=>Pe.id!=="handle-send-crash"),{id:"handle-send-crash",title:"Build crashed",description:pe instanceof Error?pe.message.slice(0,200):String(pe).slice(0,200),status:"error"}]),c(!1)}catch{}return Promise.resolve()}};Xn.current=wN,se.current=(F,X)=>wN(F,X);const fL=F=>{if(wt){if(F.key==="ArrowDown"){F.preventDefault(),Ce(X=>(X+1)%et.length);return}if(F.key==="ArrowUp"){F.preventDefault(),Ce(X=>(X-1+et.length)%et.length);return}if(F.key==="Enter"&&!F.shiftKey){F.preventDefault(),At(et[De]||et[0]);return}if(F.key==="Escape"){F.preventDefault(),Se("");return}}F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),xi())},mL=m.useCallback((F,X)=>{Rc(pe=>{const xe=pe.map(Pe=>Pe.id===F?{...Pe,text:X}:Pe);return qi.current=xe,xe})},[]),gL=m.useCallback(F=>{Rc(X=>{const pe=X.filter(xe=>xe.id!==F);return qi.current=pe,pe}),W.success("Prompt removed from queue")},[]),jN=m.useCallback(()=>{const F=gr.trim();if(!F)return;const X={id:`q-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,text:F,addedAt:Date.now()};Rc(pe=>{const xe=[...pe,X];return qi.current=xe,xe}),vr(""),W.success(`Queued follow-up (#${qi.current.length})`)},[gr]),yy=m.useMemo(()=>py.length>0?py:XX(r,k),[py,r,k]);return a.jsxs("div",{className:"h-full bg-card flex flex-col overflow-hidden",children:[a.jsx(sX,{open:KM,onClose:()=>rN(!1)}),a.jsxs("div",{className:"h-12 border-b flex items-center justify-between px-4 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ri,{className:"h-6 w-6 rounded-lg"}),a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-muted-foreground",children:"— Studio Jungle AI"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(EJ,{}),t&&a.jsx("button",{onClick:t,className:"ml-1 w-7 h-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors border border-transparent",title:"Hide chat panel","aria-label":"Hide chat panel",children:a.jsx(yT,{className:"w-3.5 h-3.5"})})]})]}),a.jsxs($r,{className:"flex-1 min-h-0 [contain:layout_style]",children:[a.jsxs("div",{ref:Oc,className:"p-4 space-y-4",children:[r.length===0&&!l&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 space-y-6 animate-fade-in",children:[a.jsx("div",{className:"w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center",children:a.jsx(Dn,{className:"w-6 h-6 text-primary"})}),a.jsxs("div",{className:"text-center space-y-1.5",children:[a.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"What would you like to build?"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick a suggestion or type your own idea"})]}),a.jsx("div",{className:"w-full space-y-2",children:[{icon:no,label:"Build a modern landing page",prompt:"Build a modern SaaS landing page with a hero section, features grid, pricing cards, testimonials, and a footer."},{icon:Zd,label:"Create an e-commerce store",prompt:"Create an e-commerce product page with a product gallery, reviews section, add-to-cart functionality, and related products."},{icon:si,label:"Design an analytics dashboard",prompt:"Design an analytics dashboard with charts, KPI cards, a sidebar navigation, and a data table with filters."},{icon:hr,label:"Build a portfolio website",prompt:"Build a creative portfolio website with an about section, project showcase grid, skills section, and contact form."}].map(F=>
6919a.jsxs("button",{onClick:()=>{Se(F.prompt)},className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border bg-secondary/30 hover:bg-secondary/60 hover:border-primary/20 transition-all text-left group",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0 group-hover:bg-primary/15 transition-colors",children:a.jsx(F.icon,{className:"w-4 h-4 text-primary"})}),a.jsx("span",{className:"text-xs font-medium text-foreground",children:F.label})]},F.label))}),te.length>1&&a.jsxs("div",{className:"w-full mt-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[a.jsx(Lr,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-xs font-semibold text-muted-foreground",children:"Recent Projects"})]}),a.jsx("div",{className:"space-y-1.5",children:te.filter(F=>F.id!==(le==null?void 0:le.id)).slice(0,3).map(F=>a.jsxs("button",{onClick:()=>We(F.id),className:"w-full flex items-center gap-2.5 px-3 py-2 rounded-lg border bg-card hover:bg-secondary/50 hover:border-primary/20 transition-all text-left group",children:[a.jsx(cc,{className:"w-4 h-4 text-primary/60 group-hover:text-primary shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"text-xs font-medium text-foreground block truncate",children:F.name}),F.description&&a.jsx("span",{className:"text-[10px] text-muted-foreground block truncate",children:F.description})]}),a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground/50",children:["#",F.id.slice(0,6)]})]},F.id))})]})]}),r.filter((F,X,pe)=>pe.findIndex(xe=>xe.id===F.id)===X).map((F,X,pe)=>{const xe=F.role==="ai"&&X===pe.length-1,He=(F.role==="ai"?_0(F.content,j):[]).map(dn=>P0(dn)).filter(Boolean),bt=6*60*60*1e3,jr=X>0?pe[X-1]:null,un=F.createdAt||0,In=(jr==null?void 0:jr.createdAt)||0,Xr=un>0&&(!jr||In>0&&un-In>bt);let Gn=null;if(Xr){const dn=new Date(un),$e=new Date,Qt=new Date($e.getFullYear(),$e.getMonth(),$e.getDate()).getTime(),ns=Qt-24*60*60*1e3,ur=dn.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});un>=Qt?Gn=`Today · ${ur}`:un>=ns?Gn=`Yesterday · ${ur}`:Gn=`${dn.toLocaleDateString([],{month:"short",day:"numeric",year:"numeric"})} · ${ur}`}return a.jsxs(m.Fragment,{children:[Gn&&a.jsxs("div",{className:"flex items-center gap-3 py-1.5 select-none",children:[a.jsx("div",{className:"flex-1 h-px bg-border"}),a.jsx("span",{className:"text-[10px] font-medium text-muted-foreground/70 uppercase tracking-wider",children:Gn}),a.jsx("div",{className:"flex-1 h-px bg-border"})]}),a.jsxs("div",{className:L("flex gap-3",F.role==="user"?"justify-end":""),children:[F.role==="ai"&&a.jsx(ri,{className:"w-7 h-7 shrink-0 mt-0.5"}),a.jsxs("div",{className:L("min-w-0 space-y-1.5 overflow-hidden",F.role==="ai"?"max-w-[92%] flex-1":"max-w-[88%]"),style:{wordBreak:"break-word",overflowWrap:"anywhere"},children:[a.jsx("div",{className:L("rounded-xl px-3.5 py-2.5 text-[13px] leading-[1.55] overflow-hidden",F.role==="user"?"bg-primary text-primary-foreground rounded-br-md":"bg-card/95 text-secondary-foreground rounded-bl-md ring-1 ring-border/60 shadow-sm",F.role==="ai"&&"[&_*]:max-w-full [&_pre]:whitespace-pre-wrap [&_code]:break-words [&_p]:break-words [&_h1]:break-words [&_h2]:break-words [&_h3]:break-words [&_li]:break-words"),children:F.role==="ai"?a.jsx(dZ,{content:F.content,onQuestionSubmit:cL,onSchemaApprove:uL,onSchemaReject:dL,schemaStatuses:cr,isLastAiMessage:xe,projectId:U,onSecretsSaved:dn=>{n("user",`✅ Secrets saved: ${dn.join(", ")}. Please continue with the implementation.`)},onContinueBuild:dn=>{const $e=zK(dn);xi($e)},onRetry:()=>{var dn;for(let $e=pe.length-1;$e>=0;$e--)if(pe[$e].role==="user"){const Qt=pe[$e].content,ns=((dn=Pd.find(tr=>tr.id===qr))==null?void 0:dn.backendModel)||"auto",ur=bN(ns);xi(yN(Qt),{overrideModel:ur,isRescue:!0});return}}}):F.content}),F.role==="ai"&&xe&&!l&&(j.length>0||x.length>0)&&(()=>{const dn=(()=>{for(let tr=X-1;tr>=0;tr--)if(pe[tr].role==="user")return pe[tr].content;return""})(),$e=Zr(k).filter(tr=>Ul(tr.path)&&!fp(tr.path,tr.content)),Qt=$e.length>0?j.some(tr=>tr.status==="error"&&!/no files generated/i.test(tr.description||"")):j.some(tr=>tr.status==="error"),ns=XI(dn),ur=rX(dn,$e.length,Qt);return a.jsx("div",{className:"mt-1.5",children:a.jsx(nX,{title:ns||"Build complete",outcome:Qt?"Build finished with errors — check details for the failing steps.":void 0,kind:ur,fileCount:$e.length,durationMs:F.durationMs,onShowDetail
6919s:()=>rN(!0),onOpenPreview:()=>C("preview")})})})(),F.role==="ai"&&He.length>0&&!l&&a.jsx(fZ,{tools:He}),F.role==="ai"&&!l&&(F.durationMs||F.createdAt)&&a.jsx(hZ,{message:F})]}),F.role==="user"&&a.jsx("div",{className:"w-7 h-7 rounded-full bg-foreground/10 flex items-center justify-center shrink-0 mt-0.5",children:a.jsx(_w,{className:"w-3.5 h-3.5"})})]})]},F.id)}),l&&a.jsxs("div",{className:"flex gap-3 max-w-[90%] [contain:layout]",children:[a.jsx(ri,{className:"w-7 h-7 shrink-0 mt-0.5"}),a.jsx("div",{className:"flex-1 min-w-[280px] min-h-[96px]",children:a.jsx(pZ,{planSteps:j})})]})]}),!l&&r.length>0&&((NN=r[r.length-1])==null?void 0:NN.role)==="ai"&&a.jsxs("div",{className:"mt-4 border-t border-border/50 bg-background/55 px-3 py-3 shrink-0 rounded-xl",children:[a.jsx("div",{className:"mb-2 flex items-center justify-between gap-2",children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"flex h-6 w-6 items-center justify-center rounded-lg bg-primary/10 text-primary",children:a.jsx(Dn,{className:"h-3.5 w-3.5"})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Best Next Steps"}),a.jsx("div",{className:"text-[11px] text-muted-foreground/80",children:"Picked from this project"})]})]})}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:yy.slice(0,4).map((F,X)=>a.jsxs("button",{onClick:()=>Se(F.prompt),className:"group flex min-h-[76px] items-start gap-2 rounded-xl border bg-card/85 px-2.5 py-2 text-left shadow-sm transition-all hover:-translate-y-0.5 hover:border-primary/35 hover:bg-primary/[0.035] hover:shadow-md",children:[a.jsx("span",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-secondary text-[10px] font-semibold text-muted-foreground ring-1 ring-border group-hover:bg-primary group-hover:text-primary-foreground group-hover:ring-primary",children:X+1}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"block line-clamp-2 text-[12px] font-semibold leading-snug text-foreground",children:F.label}),a.jsx("span",{className:"mt-1 block line-clamp-2 text-[10.5px] leading-snug text-muted-foreground",children:F.prompt})]})]},F.label))}),yy.length>4&&a.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:yy.slice(4,6).map(F=>a.jsx("button",{onClick:()=>Se(F.prompt),className:"rounded-full border bg-card/70 px-2.5 py-1 text-[10.5px] font-medium text-muted-foreground transition-all hover:border-primary/30 hover:bg-primary/5 hover:text-foreground",children:F.label},F.label))})]}),typeof Notification<"u"&&ca!=="granted"&&!ws&&a.jsx("div",{className:"mt-4 border-t border-border/50 px-3 py-2.5 shrink-0 rounded-xl",children:a.jsxs("div",{className:"flex items-center gap-2 rounded-xl border bg-background/70 px-3 py-2 shadow-sm",children:[a.jsx(L$,{className:"h-4 w-4 text-foreground shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:"Enable notifications"}),a.jsx("div",{className:"text-xs text-muted-foreground",children:"Get notified when Studio Jungle completes a task."})]}),a.jsx("button",{type:"button",onClick:tL,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground hover:bg-primary/90 transition",children:"Enable"}),a.jsx("button",{type:"button",onClick:nL,className:"rounded-lg p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground transition","aria-label":"Dismiss notifications prompt",children:a.jsx(qn,{className:"h-4 w-4"})})]})})]}),l&&a.jsx("div",{className:"border-t px-3 py-2.5 shrink-0",children:a.jsxs("div",{className:"flex items-center gap-2 rounded-xl border bg-background/70 px-3 py-2 shadow-sm",children:[a.jsx(Ik,{className:"h-4 w-4 text-primary shrink-0"}),a.jsx("input",{value:gr,onChange:F=>vr(F.target.value),onKeyDown:F=>{F.key==="Enter"&&jN()},placeholder:"Queue follow-up...",className:"min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"}),a.jsx("button",{type:"button",onClick:jN,disabled:!gr.trim(),className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-45 transition",children:"Queue"})]})}),a.jsx(X9,{queue:dy,onEdit:mL,onDelete:gL,isProcessing:l&&dy.length>0}),a.jsx(i1,{open:YM,onClose:XM,onConfirm:JM}),a.jsx(IJ,{}),a.jsx(OJ,{}),a.jsx("div",{className:"border-t p-3 shrink-0",children:a.jsxs("div",{className:L("relative flex flex-col overflow-visible rounded-2xl border transition-all","bg-card shadow-sm",nN&&"ring-2 ring-primary/40 border-primary/50 bg-primary/5"),onDragOver:F=>{F.preventDefault(),F.stopPropagation(),uy(!0)},onDragLeave:F=>{F.preventDefault(),F.stopPropagation(),uy(!1)},onDrop:F=>{F.preventDefault(),F.stopPropagation(),uy(!1);const X=F.dataTransfer.files;X!=null&&X.length&&my(X)},children:[nN&&a.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-primary/5 border-2 border-dashed border-primary/30 pointer-events-none",children:a.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-primary",children:[a.jsx(ym,{className:"w-4 h-4"}),"Drop files here"]})}),a.jsx("input",{ref:tN,type:"file",multiple:!0,accept:"image/*,.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt,.md,.csv,.tsv,.json,.xml,.html,.css,.js,.jsx,.ts,.tsx",onChange:eL,className:"hidden"}),Mn.length>0&&a.jsx("div",{className:"border-b bg-secondary/20 px-3 py-3",children:a.jsx("div",{className:"flex gap-2 overflow-x-auto whitespace-nowrap [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden",children:Mn.map((F,X)=>{var xe,Pe;return((xe=F.type)==null?void 0:xe.startsWith("image/"))&&F.dataUrl?a.jsxs("div",{className:"group relative h-20 w-20 overflow-hidden rounded-xl border bg-background shadow-sm",title:F.name,children:[a.jsx("img",{src:F.dataUrl,alt:F.name,className:"h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-black/45 px-1.5 py-1 text-[10px] font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:a.jsx("span",{className:"block truncate",children:F.name})}),a.jsx("button",{onClick:()=>cN(X),className:"absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-black/65 text-white opacity-90 shadow-sm transition hover:bg-black","aria-label":`Remove ${F.name}
6919`,children:a.jsx(qn,{className:"h-3 w-3"})})]},`${F.name}-${X}`):a.jsxs("div",{className:"group relative flex max-w-[220px] items-center gap-2 rounded-xl border bg-background px-3 py-2 pr-8 shadow-sm",title:F.name,children:[a.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:(Pe=F.type)!=null&&Pe.includes("presentation")||F.name.match(/\.pptx?$/i)?a.jsx(no,{className:"h-4 w-4 text-primary"}):F.name.match(/\.(tsx?|jsx?|html|css|json|xml|md)$/i)?a.jsx(dT,{className:"h-4 w-4 text-primary"}):a.jsx(kh,{className:"h-4 w-4 text-primary"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"truncate text-xs font-medium text-foreground",children:F.name}),a.jsx("div",{className:"text-[10px] text-muted-foreground",children:sZ(F.size)||F.kind})]}),a.jsx("button",{onClick:()=>cN(X),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground transition hover:text-foreground","aria-label":`Remove ${F.name}`,children:a.jsx(qn,{className:"h-3.5 w-3.5"})})]},`${F.name}-${X}`)})})}),wt&&a.jsxs("div",{className:"border-b bg-background/95 px-2 py-2",children:[a.jsxs("div",{className:"mb-1 flex items-center justify-between px-2 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:[a.jsx("span",{children:"Studio Jungle commands"}),a.jsx("span",{children:"Enter to pick"})]}),a.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border bg-card p-1 shadow-sm",children:et.map((F,X)=>{const pe=F.icon,xe=X===De;return a.jsxs("button",{type:"button",onMouseEnter:()=>Ce(X),onClick:()=>At(F),className:L("flex w-full items-start gap-3 rounded-lg px-3 py-2 text-left transition",xe?"bg-primary/10 text-foreground":"hover:bg-secondary/70"),children:[a.jsx("span",{className:L("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",xe?"bg-primary text-primary-foreground":"bg-secondary text-primary"),children:a.jsx(pe,{className:"h-4 w-4"})}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"font-mono text-xs font-semibold text-primary",children:F.command}),a.jsx("span",{className:"text-sm font-semibold",children:F.title})]}),a.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:F.description})]})]},F.command)})})]}),a.jsx("textarea",{ref:Ie,value:ge,onChange:F=>Se(F.target.value),onKeyDown:fL,onFocus:()=>Jb(U),placeholder:Ke?"Describe what you want to build...":"View-only access — composer disabled",rows:Mn.length>0?2:3,disabled:!Ke,className:L("w-full shrink-0 resize-none bg-transparent px-4 pb-3 pt-3 text-sm placeholder:text-muted-foreground focus:outline-none transition-all",!Ke&&"opacity-50 cursor-not-allowed")}),a.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-1.5 px-2 pb-2",children:[a.jsxs("div",{className:"flex w-full flex-wrap items-center gap-1 [&>*]:shrink-0",children:[a.jsx(GJ,{disabled:!1,onAttach:()=>{var F;return(F=tN.current)==null?void 0:F.click()},onReference:()=>Qn(!0),onConnectors:()=>{Se(F=>F.trim()?F:"Add an integration — guide me through which API and the keys it needs.")}}),a.jsx(Q_,{value:qr,onChange:xd,roleConfig:vs,onRoleConfigChange:fi,isBuilding:l}),a.jsx($I,{value:gl,onChange:mi,isBuilding:l}),a.jsxs("button",{onClick:()=>mr(!Fn),disabled:l,className:L("flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium transition-all border",Fn?"bg-primary/10 border-primary/20 text-primary":"bg-transparent border-transparent text-muted-foreground hover:text-foreground hover:bg-secondary/80",l&&"opacity-50 cursor-not-allowed"),title:Fn?"Reviewer pass: ON — Studio Jungle runs a second QA pass":"Reviewer pass: OFF — Studio Jungle builds in one pass",children:[a.jsx(J$,{className:"w-3.5 h-3.5 shrink-0"}),a.jsx("span",{className:"hidden min-[520px]:inline",children:"Pipeline"})]}),a.jsxs("button",{onClick:()=>je(!ue),disabled:l,className:L("flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium transition-all border",ue?"bg-amber-500/10 border-amber-500/30 text-amber-600 dar
6919k:text-amber-400":"bg-transparent border-transparent text-muted-foreground hover:text-foreground hover:bg-secondary/80",l&&"opacity-50 cursor-not-allowed"),title:ue?"Diff Mode: ON — Review AI edits in Files tab before they apply":"Diff Mode: OFF — AI edits auto-apply (legacy behavior)",children:[a.jsx(Vg,{className:"w-3.5 h-3.5 shrink-0"}),a.jsx("span",{className:"hidden min-[520px]:inline",children:"Diff"})]}),a.jsx(TJ,{value:Er,onChange:Ec,isBuilding:l}),a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>Qn(F=>!F),disabled:l,className:L("flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium transition-all border",Hs?"bg-blue-500/10 border-blue-500/30 text-blue-600 dark:text-blue-400":"bg-transparent border-transparent text-muted-foreground hover:text-foreground hover:bg-secondary/80",l&&"opacity-50 cursor-not-allowed"),title:Hs?`Reference: ${(()=>{try{return new URL(Hs).hostname}catch{return Hs}})()} — click to change`:"Import a reference URL — AI will mirror its design",children:[a.jsx(Yo,{className:"w-3.5 h-3.5 shrink-0"}),a.jsx("span",{className:"hidden min-[560px]:inline",children:Hs?(()=>{try{return new URL(Hs).hostname.replace(/^www\./,"")}catch{return"Reference"}})():"Reference"})]}),cn&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Qn(!1)}),a.jsxs("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 bg-card border rounded-xl shadow-xl z-50 overflow-hidden",children:[a.jsxs("div",{className:"px-3 py-2 border-b",children:[a.jsx("span",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Reference URL"}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"AI will mirror the palette, fonts, and layout from this site."})]}),a.jsxs("div",{className:"p-3 space-y-2",children:[a.jsx("input",{type:"url",value:Ye,onChange:F=>pt(F.target.value),onKeyDown:F=>{F.key==="Enter"&&Xe(Ye)},placeholder:"vercel.com or https://stripe.com",autoFocus:!0,className:"w-full text-sm rounded-lg border border-border bg-card px-3 py-2 focus:outline-none focus:border-primary/40 focus:ring-1 focus:ring-primary/20"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>void Xe(Ye),disabled:Bt||!Ye.trim(),className:"flex-1 text-xs px-3 py-1.5 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5",children:[Bt?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(Yo,{className:"w-3 h-3"}),Bt?"Fetching…":"Import"]}),Hs&&a.jsx("button",{onClick:()=>{St(),Qn(!1)},className:"text-xs px-3 py-1.5 rounded-lg border hover:bg-muted",children:"Clear"})]}),Hs&&a.jsxs("div",{className:"text-[10px] text-muted-foreground break-all",children:["✓ Active: ",a.jsx("span",{className:"text-foreground font-mono",children:Hs})]})]})]})]})]})]}),a.jsxs("div",{className:"flex w-full shrink-0 items-center justify-end gap-1.5 border-t border-border/40 pt-1",children:[(()=>{var xe;const F={"claude-haiku-4-5":"1 credit","claude-sonnet-4-6":"5 credits","claude-opus-4-8":"30 credits","claude-opus-4-7":"30 credits","claude-fable-5":"60 credits"},X=(xe=Pd.find(Pe=>Pe.id===qr))==null?void 0:xe.backendModel,pe=X&&F[X]?F[X]:"1–30 credits";return a.jsxs("span",{className:"hidden xl:inline text-[9px] text-muted-foreground/60 tabular-nums pointer-events-none select-none mr-0.5",title:"Estimated cost for this build. Smart routing picks the cheapest model that can do the job.",children:["~",pe]})})(),l?a.jsx(Q,{id:"chat-stop-btn",size:"icon",variant:"outline",onClick:()=>{var F;console.warn("[chat] User clicked Stop — aborting active build and restoring previous snapshot"),ua.current=!0,(F=ko.current)==null||F.abort(),QM(),c(!1),wr.current=!1,No(),W.message("Build stopped — reverted to the last stable preview.",{duration:3e3})},className:"h-8 w-8 rounded-lg shrink-0",title:"Stop / cancel current build",children:a.jsx(qn,{className:"w-3.5 h-3.5"})}):a.jsxs("div",{className:"relative",children:[a.jsxs("button",{type:"button",onClick:()=>Qs(F=>!F),disabled:l,className:L("h-8 px-2.5 rounded-lg flex items-center gap-1.5 text-[11px] font-medium border transition-colors shrink-0",ts==="draft"?"bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400":"bg-secondary/50 border-border/60 text-foreground hover:bg-secondary/80",l&&"opacity-50 cursor-not-allowed"),title:ts==="apply"?"Build mode: Studio Jungle makes changes directly. Press Option+P to switch to Plan.":"Plan mode: Studio Jungle discusses before building. Press Option+P to switch to Build.",children:[ts==="apply"?"Build":"Plan",a.jsx(Yr,{className:L("w-3 h-3 opacity-60 transition-transform",Tc&&"rotate-180")}
6919)]}),Tc&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Qs(!1)}),a.jsxs("div",{className:"absolute bottom-full right-0 z-50 mb-2 w-72 overflow-hidden rounded-xl border bg-card shadow-xl",children:[a.jsxs("button",{type:"button",onClick:()=>{zi("apply"),Qs(!1)},className:L("flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-secondary/70",ts==="apply"&&"bg-primary/5"),children:[a.jsx(mn,{className:L("mt-0.5 h-4 w-4 shrink-0",ts==="apply"?"text-primary":"text-transparent")}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"block text-sm font-semibold text-foreground",children:"Build"}),a.jsx("span",{className:"block text-xs text-muted-foreground",children:"Make changes directly"})]})]}),a.jsxs("button",{type:"button",onClick:()=>{zi("draft"),Qs(!1)},className:L("flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-secondary/70",ts==="draft"&&"bg-amber-500/10"),children:[a.jsx(mn,{className:L("mt-0.5 h-4 w-4 shrink-0",ts==="draft"?"text-amber-600 dark:text-amber-400":"text-transparent")}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"block text-sm font-semibold text-foreground",children:"Plan"}),a.jsx("span",{className:"block text-xs text-muted-foreground",children:"Discuss before building"})]})]}),a.jsxs("div",{className:"flex items-center gap-2 border-t px-4 py-2 text-xs text-muted-foreground",children:[a.jsx("span",{children:"Toggle with"}),a.jsx("kbd",{className:"rounded border bg-muted px-1.5 py-0.5 text-[10px] font-semibold",children:"⌥"}),a.jsx("kbd",{className:"rounded border bg-muted px-1.5 py-0.5 text-[10px] font-semibold",children:"P"})]})]})]})]}),a.jsx(Q,{id:"chat-send-btn",size:"icon",onClick:()=>xi(),disabled:!ge.trim()&&Mn.length===0||!Ke,className:"h-8 w-8 rounded-lg shrink-0",title:Ke?l?"Add to queue (or click X to stop current)":ts==="draft"?"Send in Plan mode":"Send in Build mode":"View-only access — ask the owner to upgrade your role to send prompts",children:l?a.jsx(Ik,{className:"w-3.5 h-3.5"}):a.jsx(Li,{className:"w-3.5 h-3.5"})})]})]})]})}),U&&a.jsx(l3,{open:sL,onOpenChange:F=>{hN(F),F||gy(!1)},autoGenerate:aL,onGenerated:()=>{n("ai","✅ Auth scaffold was created. You can continue building with login/auth enabled now."),gy(!1)}}),a.jsx(FX,{open:iL,intent:oL,onAllow:(F,X)=>{if(fN(!1),Jh.current=!0,U)try{localStorage.setItem(`cloud_enabled_${U}`,"1")}catch{}if(X)try{localStorage.setItem("sj_cloud_always_allow","1")}catch{}lL({region:F}),Yh&&(xi(Yh),mN(""),gN(void 0))},onSkip:()=>{if(fN(!1),Jh.current=!0,U)try{localStorage.setItem(`cloud_enabled_${U}`,"1")}catch{}Yh&&(xi(Yh),mN(""),gN(void 0))}})]})}function D2(e,t){const r=e.length===0?[]:e.split(`
6920`),n=t.length===0?[]:t.split(`
6921`),s=r.length,i=n.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let f=1;f<=s;f++)for(let x=1;x<=i;x++)o[f][x]=r[f-1]===n[x-1]?o[f-1][x-1]+1:Math.max(o[f-1][x],o[f][x-1]);const l=[];let c=s,u=i,d=0,p=0,h=0;for(;c>0&&u>0;)r[c-1]===n[u-1]?(l.push({kind:"context",oldLineNum:c,newLineNum:u,text:r[c-1]}),h++,c--,u--):o[c-1][u]>=o[c][u-1]?(l.push({kind:"remove",oldLineNum:c,newLineNum:null,text:r[c-1]}),p++,c--):(l.push({kind:"add",oldLineNum:null,newLineNum:u,text:n[u-1]}),d++,u--);for(;c>0;)l.push({kind:"remove",oldLineNum:c,newLineNum:null,text:r[c-1]}),p++,c--;for(;u>0;)l.push({kind:"add",oldLineNum:null,newLineNum:u,text:n[u-1]}),d++,u--;return l.reverse(),{lines:l,stats:{added:d,removed:p,unchanged:h}}}function SZ(e){const t=[];return e.added>0&&t.push(`+${e.added}`),e.removed>0&&t.push(`-${e.removed}`),t.length?t.join(" "):"no changes"}function CZ(e,t=3){const r=[],n=e.lines;let s=0;for(;s<n.length;){if(n[s].kind!=="context"){r.push(n[s]),s++;continue}let i=s;for(;i<n.length&&n[i].kind==="context";)i++;const o=i-s,l=s===0,c=i===n.length,u=l?0:Math.min(t,o),d=c?0:Math.min(t,o-u);if(o<=u+d)for(let p=s;p<i;p++)r.push(n[p]);else{for(let p=0;p<u;p++)r.push(n[s+p]);r.push({kind:"separator",hiddenCount:o-u-d});for(let p=0;p<d;p++)r.push(n[i-d+p])}s=i}return r}const PZ={create:{label:"Create",icon:hT,color:"text-green-500"},modify:{label:"Modify",icon:Vg,color:"text-amber-500"},delete:{label:"Delete",icon:pT,color:"text-red-500"}};function AZ(){const{pendingFileChanges:e,acceptPendingChange:t,rejectPendingChange:r,acceptAllPendingChanges:n,rejectAllPendingChanges:s,triggerBuildRef:i}=gn(),{canEdit:o}=Ih(),l=(c,u,d,p)=>{const h=d.trim();if(!h)return;r(c);const f=p.split(`
6922`).slice(0,8).join(`
6923`),x=`Edit ONLY the file \`${u}\` based on this feedback: "${h}"
6924
6925The previously proposed change was rejected. Here are the first 8 lines of the rejected proposal for context (do NOT re-emit them verbatim — interpret the feedback against the EXISTING file content via read_file first):
6926
6927\`\`\`
6928${f}
6929\`\`\`
6930
6931Use read_file to inspect the existing version, then str_replace for surgical changes. Do not modify any other files.`;i.current&&i.current(x)};return e.length===0?null:a.jsxs("div",{"data-pending-changes-panel":!0,className:"border-b bg-amber-50/40 dark:bg-amber-950/20",children:[a.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-amber-200/50 dark:border-amber-900/30",children:[a.jsx(tl,{className:"w-4 h-4 text-amber-600"}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"text-sm font-semibold text-foreground",children:[e.length," pending change",e.length===1?"":"s"]}),a.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Review the AI's proposed edits. Apply to commit, Reject to discard."})]}),o?a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:s,className:"text-xs px-3 py-1 rounded-md border hover:bg-muted transition",children:"Reject all"}),a.jsxs("button",{onClick:n,className:"text-xs px-3 py-1 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition flex items-center gap-1.5",children:[a.jsx(Wn,{className:"w-3 h-3"})," Apply all"]})]}):a.jsx("span",{className:"text-[11px] text-amber-700 dark:text-amber-400 italic",children:"View-only — ask owner to apply"})]}),a.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:e.map(c=>a.jsx(_Z,{change:c,onAccept:()=>t(c.id),onReject:()=>
6931r(c.id),onComment:u=>l(c.id,c.path,u,c.newContent||"")},c.id))})]})}function _Z({change:e,onAccept:t,onReject:r,onComment:n}){const[s,i]=m.useState(!1),[o,l]=m.useState(!1),[c,u]=m.useState(""),d=PZ[e.kind],p=d.icon,h=m.useMemo(()=>e.kind==="delete"?D2(e.oldContent??"",""):D2(e.oldContent??"",e.newContent),[e.kind,e.oldContent,e.newContent]),f=m.useMemo(()=>CZ(h,3),[h]),x=g=>{g.preventDefault();const y=c.trim();y&&(n(y),u(""),l(!1))};return a.jsxs("div",{className:"border-b border-amber-200/30 dark:border-amber-900/20 last:border-b-0",children:[a.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 hover:bg-amber-100/30 dark:hover:bg-amber-950/30",children:[a.jsx("button",{onClick:()=>i(g=>!g),className:"p-0.5 hover:bg-muted rounded",children:s?a.jsx(Yr,{className:"w-3.5 h-3.5"}):a.jsx(ia,{className:"w-3.5 h-3.5"})}),a.jsx(p,{className:L("w-3.5 h-3.5 shrink-0",d.color)}),a.jsx("span",{className:"text-[11px] font-medium text-muted-foreground tabular-nums",children:d.label}),a.jsx("span",{className:"text-xs font-mono text-foreground truncate flex-1",children:e.path}),a.jsx("span",{className:"text-[10px] tabular-nums text-muted-foreground",children:SZ(h.stats)}),a.jsx("button",{onClick:()=>l(g=>!g),className:L("text-[11px] px-2 py-0.5 rounded border transition",o?"bg-primary/10 text-primary border-primary/30":"hover:bg-muted text-muted-foreground hover:text-foreground"),title:"Comment — ask the AI to revise this file",children:a.jsx(Tp,{className:"w-3 h-3"})}),a.jsx("button",{onClick:r,className:"text-[11px] px-2 py-0.5 rounded border hover:bg-muted text-muted-foreground hover:text-foreground transition",title:"Discard this change",children:a.jsx(qn,{className:"w-3 h-3"})}),a.jsxs("button",{onClick:t,className:"text-[11px] px-2 py-0.5 rounded bg-primary text-primary-foreground hover:bg-primary/90 transition flex items-center gap-1",title:"Apply this change",children:[a.jsx(Wn,{className:"w-3 h-3"})," Apply"]})]}),o&&a.jsxs("form",{onSubmit:x,className:"px-4 py-2 border-t border-amber-200/30 dark:border-amber-900/20 bg-card/50 flex items-center gap-2",children:[a.jsx(Tp,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}
6931),a.jsx("input",{autoFocus:!0,type:"text",value:c,onChange:g=>u(g.target.value),placeholder:`What should change in ${e.path.split("/").pop()}? e.g. "make the CTA bigger and use indigo"`,className:"flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground/60"}),a.jsx("button",{type:"button",onClick:()=>{l(!1),u("")},className:"text-[11px] px-2 py-0.5 rounded border hover:bg-muted text-muted-foreground transition",children:"Cancel"}),a.jsxs("button",{type:"submit",disabled:!c.trim(),className:"text-[11px] px-2 py-0.5 rounded bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition flex items-center gap-1",children:[a.jsx(Li,{className:"w-3 h-3"})," Send"]})]}),s&&a.jsx("div",{className:"border-t border-amber-200/20 dark:border-amber-900/20 bg-card/50 max-h-[40vh] overflow-auto",children:a.jsx(TZ,{lines:f})})]})}function TZ({lines:e}){return a.jsx("div",{className:"font-mono text-[11px] leading-relaxed",children:e.map((t,r)=>{if(t.kind==="separator")return a.jsxs("div",{className:"px-3 py-0.5 text-center text-muted-foreground/60 bg-muted/30 text-[10px]",children:["⋯ ",t.hiddenCount," unchanged line",t.hiddenCount===1?"":"s"," ⋯"]},r);const n=t.kind==="add"?"bg-green-500/10":t.kind==="remove"?"bg-red-500/10":"",s=t.kind==="add"?"+":t.kind==="remove"?"-":" ",i=t.kind==="add"?"text-green-600":t.kind==="remove"?"text-red-600":"text-muted-foreground/40";return a.jsxs("div",{className:L("flex gap-2 px-3",n),children:[a.jsx("span",{className:"select-none text-[10px] text-muted-foreground/50 tabular-nums w-7 text-right shrink-0",children:t.oldLineNum??""}),a.jsx("span",{className:"select-none text-[10px] text-muted-foreground/50 tabular-nums w-7 text-right shrink-0",children:t.newLineNum??""}),a.jsx("span",{className:L("select-none w-3 shrink-0",i),children:s}),a.jsx("span",{className:"whitespace-pre-wrap break-all flex-1 text-foreground",children:t.text||" "})]},r)})})}const EZ=m.lazy(()=>ju(()=>import("./MonacoEditor-DOseMS1r.js"),__vite__mapDeps([59,1,2,3,4,5])).then(e=>({default:e.MonacoEditor}))),IZ=/\.(png|jpe?g|gif|webp|avif|svg|ico|pdf|zip|tar\.gz|tgz|pptx?|docx?|xlsx?|csv|tsv|json|xml|mp4|mov|webm|mp3|wav)$/i,OZ=/\.(tsx?|jsx?|css|scss|html?|mdx?|sql|ya?ml|toml|lock)$/i,RZ=/\.(csv|tsv|json|xml|txt)$/i;function xO({node:e,depth:t=0,onSelectFile:r}){var c;const[n,s]=m.useState(t<1),{selectedFile:i}=gn(),o=e.type==="folder",l=(i==null?void 0:i.name)===e.name&&(i==null?void 0:i.type)==="file";return a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>o?s(!n):r(e),className:L("w-full flex items-center gap-1.5 py-1 px-2 text-sm rounded-md transition-colors hover:bg-secondary",l&&"bg-primary/10 text-primary"),style:{paddingLeft:`${t*16+8}px`},children:[o?a.jsxs(a.Fragment,{children:[n?a.jsx(Yr,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}):a.jsx(ia,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),n?a.jsx(cc,{className:"w-4 h-4 text-primary/70 shrink-0"}):a.jsx(Y$,{className:"w-4 h-4 text-primary/70 shrink-0"})]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"w-3.5"}),a.jsx(Wb,{className:"w-4 h-4 text-muted-foreground shrink-0"})]}),a.jsx("span",{className:"truncate",children:e.name})]}),o&&n&&((c=e.children)==null?void 0:c.map((u,d)=>a.jsx(xO,{node:u,depth:t+1,onSelectFile:r},d)))]})}function yO(e){return e===".sj"||e===".studiojungle"}function bO(e){return e.reduce((t,r)=>yO(r.name)?t:r.type==="file"?t+1:t+bO(r.children||[]),0)}function I0(e,t,r){return e.map(n=>n===t&&n.type==="file"?{...n,content:r}:n.type==="folder"&&n.children?{...n,children:I0(n.children,t,r)}:n)}function vO(e,t,r=""){for(const n of e){const s=r?`${r}/${n.name}`:n.name;if(n===t)return s;if(n.type==="folder"&&n.children){const i=vO(n.children,t,s);if(i)return i}}return null}function um(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"?r.push({name:n.name,path:s,content:n.content||""}):n.type==="folder"&&n.children&&r.push(...um(n.children,s))}return r}function M2(e){return IZ.test(e)&&!OZ.test(e)}function wO(e){return/\.(png|jpe?g|gif|webp|avif|svg|ico)$/i.test(e)?"image":/\.(pdf|pptx?|docx?|xlsx?)$/i.test(e)?"document":/\.(zip|tar\.gz|tgz)$/i.test(e)?"archive":/\.(mp4|mov|webm|mp3|wav)$/i.test(e)?"media":/\.(csv|tsv|json|xml)$/i.test(e)?"data":"file"}function jO(e){const t=wO(e);return t==="image"?ad:t==="archive"?aT:t==="data"?Hn:kh}function NO(e){var r;const t=e.startsWith("data:")?Math.round((((r=e.split(",")[1])==null?void 0:r.length)||e.length)*.75):new Blob([e]).size;return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function kO(e){const t=e.content||"";return/^(https?:)?\/\//i.test(t)||t.startsWith("data:")?t:/\.svg$/i.test(e.path)||t.trim().startsWith("<svg")?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`:""}function L2(e){const t=kO(e),r=document.createElement("a");r.download=e.name,r.href=t||URL.createObjectURL(new Blob([e.content||""],{type:"application/octet-stream"})),document.body.appendChild(r),r.click(),r.remove(),t||URL.revokeObjectURL(r.href)}function DZ(){const{project:e,files:t,setFiles:r,selectedFile:n,setSelectedFile:s,generatedPages:i,setActivePageId:o,setPreviewHtml:l,setActiveWorkspaceTab:c,saveProjectFiles:u}=gn(),{canEdit:d}=Ih(),p=t.filter(_=>!yO(_.name)),h=m.useMemo(()=>bO(t),[t]),[f,x]=m.useState(null),[g,y]=m.useState([]),[b,v]=m.useState(!1),[k,N]=m.useState("files"),j=m.useMemo(()=>n?vO(t,n)||n.name:"",[t,n]),[w,S]=m.useState(!1),T=m.useRef(null),C=m.useCallback(_=>{!n||n.type!=="file"||_!==n.content&&(r(I0(t,n,_)),s({...n,content:_}),S(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{const I=I0(t,n,_);
6931u(um(I)).then(()=>S(!1)).catch(()=>{})},700))},[t,n,r,s,u]),A=m.useCallback(_=>{x(null),N("files"),s(_)},[s]);m.useEffect(()=>{let _=!1;const I=um(t).filter(M=>M2(M.path)).map(M=>({name:M.name,path:M.path,content:M.content,language:M.language}));async function D(){if(!(e!=null&&e.id)){y(I);return}v(!0);const{data:M,error:B}=await G.from("project_files").select("name,path,content,language,updated_at").eq("project_id",e.id).order("updated_at",{ascending:!1});if(!_){if(B)y(I);else{const $=(M||[]).filter(K=>M2(K.path)).map(K=>({name:K.name,path:K.path,content:K.content||"",language:K.language,updatedAt:K.updated_at}));y($.length?$:I)}v(!1)}}return D(),()=>{_=!0}},[t,e==null?void 0:e.id]),m.useEffect(()=>{function _(I){(I.metaKey||I.ctrlKey)&&I.key==="s"&&(I.preventDefault(),T.current&&(clearTimeout(T.current),T.current=null),u(um(t)).then(()=>S(!1)).catch(()=>{}))}return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[t,u]);const P=n?i.find(_=>_.filename===n.name||_.filename.endsWith(n.name)):null,E=()=>{P&&(o(P.id),l(P.html),c("preview"))};return a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx(AZ,{}),a.jsxs("div",{className:"flex flex-1 min-h-0",children:[a.jsxs("div",{className:"w-56 border-r shrink-0",children:[a.jsx("div",{className:"h-10 border-b flex items-center px-2",children:a.jsxs("div",{className:"grid grid-cols-2 gap-1 rounded-lg bg-secondary/60 p-0.5 w-full",children:[a.jsxs("button",{onClick:()=>N("files"),className:L("h-7 rounded-md text-[11px] font-semibold transition-colors inline-flex items-center justify-center gap-1.5",k==="files"?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[a.jsx(Wb,{className:"h-3.5 w-3.5"}),"Files"]}),a.jsxs("button",{onClick:()=>N("assets"),className:L("h-7 rounded-md text-[11px] font-semibold transition-colors inline-flex items-center justify-center gap-1.5",k==="assets"?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[a.jsx(ad,{className:"h-3.5 w-3.5"}),"Assets",g.length>0&&a.jsx("span",{className:L("min-w-[16px] h-[16px] px-1 rounded-full text-[9px] font-semibold flex items-center justify-center",k==="assets"?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:g.length})]})]})}),a.jsx($r,{className:"h-[calc(100%-40px)]",children:a.jsx("div",{className:"p-2",children:k==="files"?a.jsxs("div",{children:[a.jsxs("div",{className:"px-1.5 pb-1.5 flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Source files"}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:h})]}),p.map((_,I)=>a.jsx(xO,{node:_,onSelectFile:A},I))]}):a.jsxs("div",{children:[a.jsxs("div",{className:"px-1.5 pb-1.5 flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Project assets"}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:g.length})]}),b?a.jsx("div",{className:"px-2 py-3 text-xs text-muted-foreground",children:"Loading assets…"}):g.length>0?a.jsx("div",{className:"space-y-1",children:g.map(_=>{const I=jO(_.path),D=(f==null?void 0:f.path)===_.path;return a.jsxs("button",{onClick:()=>{x(_),N("assets"),s(null)},className:L("w-full flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs transition-colors hover:bg-secondary",D&&"bg-primary/10 text-primary"),children:[a.jsx(I,{className:"w-4 h-4 shrink-0 text-muted-foreground"}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"block truncate font-medium",children:_.name}),a.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:NO(_.content)})]})]},_.path)})}):a.jsx("div",{className:"rounded-lg border border-dashed p-3 text-xs leading-relaxed text-muted-foreground",children:"Uploaded images, decks, zips, and generated asset files will appear here once they are saved with this project."})]})})})]}),a.jsx("div",{className:"flex-1 min-w-0 flex flex-col",children:f?a.jsx(MZ,{asset:f}):n&&n.type==="file"&&typeof n.content=="string"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"h-10 border-b flex items-center px-4 gap-2 shrink-0",children:[a.jsx(Wb,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-sm font-medium",children:n.name}),w&&a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-500",title:"Unsaved changes"}),P&&a.jsxs("button",{onClick:E,className:"ml-2 flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium bg-primary/10 text-primary hover:bg-primary/20 transition-colors",title:"View in Preview",children:[a.jsx(ys,{className:"w-3 h-3"}),"Preview"]}),a.jsxs("button",{onClick:()=>window.dispatchEvent(new CustomEvent("sj:cmd-k-request-selection")),className:"ml-auto flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium bg-primary/10 text-primary hover:bg-primary/20 transition-colors",title:"Highlight code first, then ⌘K — Studio Jungle AI rewrites the selection",children:[a.jsx(ri,{className:"h-4 w-4"}),"Studio Jungle AI ",a.jsx("span",{className:"text-[9px] font-mono opacity-70 ml-0.5",children:"⌘K"})]}),a.jsxs("span",{className:"text-[10px] text-muted-foreground inline-flex items-center gap-1",children:[a.jsx(Kg,{className:"w-3 h-3"}),d?w?"Saving…":"Saved":"Read-only"]})]}),a.jsx("div",{className:"flex-1 min-h-0",children:a.jsx(m.Suspense,{fallback:a.jsx("div",{className:"h-full flex items-center justify-center text-muted-foreground text-xs",children:"Loading editor…"}),children:a.jsx(EZ,{filename:j||n.name,value:n.content,onChange:d?C:void 0,readOnly:!d})})})]}):a.jsx("div",{className:"h-full flex items-center justify-center text-muted-foreground text-sm",children:"Select a file to view its contents"})})]})]})}function MZ({asset:e}){const t=kO(e),r=wO(e.path),n=jO(e.path),s=r==="image"&&t,i=/\.pdf$/i.test(e.path)&&t,o=RZ.test(e.path)&&!e.content.startsWith("data:");return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"h-10 border-b flex items-center px-4 gap-2 shrink-0",children:[a.jsx(n,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-sm font-medium truncate",children:e.name}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:NO(e.content)}),a.jsxs("button",{onClick:()=>L2(e),className:"ml-auto flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium bg-primary/10 text-primary hover:bg-primary/20 transition-colors",children:[a.jsx(Hb,{className:"w-3 h-3"}),"Download"]})]}),a.jsx("div",{className:"flex-1 min-h-0 bg-muted/20",children:s?a.jsx("div",{className:"h-full flex items-center justify-center p-6",children:a.jsx("img",{src:t,alt:e.name,className:"max-h-full max-w-full rounded-lg border bg-background object-contain shadow-sm"})}):i?a.jsx("iframe",{title:e.name,src:t,className:"h-full w-full bg-background"}):o?a.jsx($r,{className:"h-full",children:a.jsx("pre",{className:"p-5 text-xs leading-relaxed whitespace-pre-wrap",children:e.content})}):a.jsx("div",{className:"h-full flex items-center justify-center p-8",children:a.jsxs("div",{className:"max-w-sm rounded-xl border bg-background p-6 text-center shadow-sm",children:[a.jsx(n,{className:"mx-auto mb-3 h-8 w-8 text-muted-foreground"}),a.jsx("div",{className:"font-semibold",children:"Preview is not available for this file type."}),a.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"You can still download the saved project asset."}),a.jsxs("button",{onClick:()=>L2(e),className:"mt-4 inline-flex items-center gap-2 rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90",children:[a.jsx(Hb,{className:"h-4 w-4"}),"Download file"]})]})})})]})}function O0(e,t,r=""){for(const n of e){const s=r?`${r}/${n.name}`:n.name;if(n===t)return s;if(n.type==="folder"&&n.children){const i=O0(n.children,t,s);if(i)return i}}return null}function LZ(){const{files:e,selectedFile:t}=gn(),[r,n]=m.useState(null),[s,i]=m.useState(""),[o,l]=m.useState(!1),c=m.useRef(null),u=m.useCallback((g={})=>{const y=window.getSelection();if(!y||y.rangeCount===0){g.silentOnNoSelection||W.message("Highlight some code first",{description:"Select code in the Files tab viewer, then press ⌘K (or click Studio Jungle AI)."});return}const b=y.toString();if(!b||!b.trim()){g.silentOnNoSelection||W.message("Highlight some code first",{description:"Drag-select the code you want the AI to rewrite, then try again."});return}const v=y.getRangeAt(0);let k=v.commonAncestorContainer,N=!1;for(;k;){if(k instanceof HTMLElement&&k.matches('code[class*="language-"]')){N=!0;break}k=k.parentNode}if(!N){g.silentOnNoSelection||W.message("Selection isn't in the code viewer",{description:"Open a file in the Files tab and drag-select the code you want the AI to edit."});return}if(!t){W.message("Open a file first",{description:"Click a file in the Files tab to load it, then highlight + ⌘K."});return}const j=O0(e,t)||t.name,w=v.getBoundingClientRect();w.width===0&&w.height===0||(n({text:b,filePath:j,rect:{top:w.top,left
6931:w.left,width:w.width,height:w.height}}),i(""),requestAnimationFrame(()=>{var S;return(S=c.current)==null?void 0:S.focus()}))},[e,t]);if(m.useEffect(()=>{function g(y){var N,j,w;if(!(y.metaKey||y.ctrlKey)||y.shiftKey||y.altKey)return;const v=y.key.toLowerCase();if(v!=="k"&&v!=="j")return;const k=(j=(N=y.target)==null?void 0:N.tagName)==null?void 0:j.toLowerCase();k==="input"||k==="textarea"||(w=y.target)!=null&&w.isContentEditable||(y.preventDefault(),u())}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[u]),m.useEffect(()=>{function g(y){const b=y.detail;if((b==null?void 0:b.source)==="monaco"&&b.text&&b.filename){const v=t?O0(e,t)||t.name:b.filename,k=b.rect||{top:100,left:100,width:200,height:20};n({text:b.text,filePath:v,rect:k}),i(""),requestAnimationFrame(()=>{var N;return(N=c.current)==null?void 0:N.focus()});return}u()}return window.addEventListener("sj:cmd-k-trigger",g),()=>window.removeEventListener("sj:cmd-k-trigger",g)},[u,e,t]),m.useEffect(()=>{function g(){W.message("Highlight some code first",{description:"Select code in the editor, then click Studio Jungle AI or press ⌘K."})}return window.addEventListener("sj:cmd-k-no-selection",g),()=>window.removeEventListener("sj:cmd-k-no-selection",g)},[]),m.useEffect(()=>{function g(y){r&&(y.key==="Escape"?(y.preventDefault(),n(null)):y.key==="Enter"&&(y.metaKey||y.ctrlKey)&&s.trim()&&(y.preventDefault(),x()))}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[r,s]),!r)return null;const d=window.innerHeight-200,p=r.rect.top+r.rect.height+6,h=p>d?Math.max(8,r.rect.top-200):p,f=Math.max(8,Math.min(window.innerWidth-420,r.rect.left));async function x(){const g=s.trim();!r||!g||o||(l(!0),window.dispatchEvent(new CustomEvent("sj:cmd-k-edit",{detail:{instruction:g,selectedText:r.text,filePath:r.filePath}})),W.success("Sent to Studio Jungle AI",{description:`Editing ${r.filePath} (${r.text.length} chars)`}),l(!1),n(null))}return a.jsxs("div",{role:"dialog","aria-label":"Ask Studio Jungle AI to edit selection",className:"fixed z-[110] w-[400px] rounded-lg border bg-card shadow-2xl",style:{top:h,left:f},onClick:g=>g.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b bg-muted/30 rounded-t-lg",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(ri,{className:"h-5 w-5"}),a.jsx("span",{className:"text-[11px] font-semibold",children:"Studio Jungle AI edit"}),a.jsxs("span",{className:"font-mono text-[10px] text-muted-foreground truncate max-w-[180px]",children:[r.filePath," · ",r.text.length," chars"]})]}),a.jsx("button",{onClick:()=>n(null),className:"w-5 h-5 flex items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground","aria-label":"Close",children:a.jsx(qn,{className:"w-3.5 h-3.5"})})]}),a.jsxs("div",{className:"p-3 space-y-2",children:[a.jsx("textarea",{ref:c,value:s,onChange:g=>i(g.target.value),rows:3,placeholder:"Tell Studio Jungle AI what to change. E.g. 'add error handling', 'extract into a function', 'rename to fooBar', 'add JSDoc'.",className:"w-full text-sm bg-background border rounded-md px-2.5 py-1.5 resize-none focus:outline-none focus:ring-1 focus:ring-primary/40 leading-snug"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground",children:"⌘↵ submit · esc cancel"}),a.jsxs("button",{onClick:x,disabled:!s.trim()||o,className:L("flex items-center gap-1 px-2.5 py-1 rounded text-[11px] font-semibold",!s.trim()||o?"bg-muted text-muted-foreground cursor-not-allowed":"bg-primary text-primary-foreground hover:bg-primary/90"),children:[o?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(Dn,{className:"w-3 h-3"}),"Send to Studio Jungle AI"]})]})]})]})}function $Z(e){return e==null}var FZ=$Z;const an=zs(FZ);var SO={exports:{}},lr={};/**
6932 * @license React
6933 * react-is.production.min.js
6934 *
6935 * Copyright (c) Facebook, Inc. and its affiliates.
6936 *
6937 * This source code is licensed under the MIT license found in the
6938 * LICENSE file in the root directory of this source tree.
6939 */var J1=Symbol.for("react.element"),X1=Symbol.for("react.portal"),yx=Symbol.for("react.fragment"),bx=Symbol.for("react.strict_mode"),vx=Symbol.for("react.profiler"),wx=Symbol.for("react.provider"),jx=Symbol.for("react.context"),BZ=Symbol.for("react.server_context"),Nx=Symbol.for("react.forward_ref"),kx=Symbol.for("react.suspense"),Sx=Symbol.for("react.suspense_list"),Cx=Symbol.for("react.memo"),Px=Symbol.for("react.lazy"),UZ=Symbol.for("react.offscreen"),CO;CO=Symbol.for("react.module.reference");function Ua(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case J1:switch(e=e.type,e){case yx:case vx:case bx:case kx:case Sx:return e;
6939default:switch(e=e&&e.$$typeof,e){case BZ:case jx:case Nx:case Px:case Cx:case wx:return e;default:return t}}case X1:return t}}}lr.ContextConsumer=jx;lr.ContextProvider=wx;lr.Element=J1;lr.ForwardRef=Nx;lr.Fragment=yx;lr.Lazy=Px;lr.Memo=Cx;lr.Portal=X1;lr.Profiler=vx;lr.StrictMode=bx;lr.Suspense=kx;lr.SuspenseList=Sx;lr.isAsyncMode=function(){return!1};lr.isConcurrentMode=function(){return!1};lr.isContextConsumer=function(e){return Ua(e)===jx};lr.isContextProvider=function(e){return Ua(e)===wx};lr.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===J1};lr.isForwardRef=function(e){return Ua(e)===Nx};lr.isFragment=function(e){return Ua(e)===yx};lr.isLazy=function(e){return Ua(e)===Px};lr.isMemo=function(e){return Ua(e)===Cx};lr.isPortal=function(e){return Ua(e)===X1};lr.isProfiler=function(e){return Ua(e)===vx};lr.isStrictMode=function(e){return Ua(e)===bx};lr.isSuspense=function(e){return Ua(e)===kx};lr.isSuspenseList=function(e){return Ua(e)===Sx};lr.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===yx||e===vx||e===bx||e===kx||e===Sx||e===UZ||typeof e=="object"&&e!==null&&(e.$$typeof===Px||e.$$typeof===Cx||e.$$typeof===wx||e.$$typeof===jx||e.$$typeof===Nx||e.$$typeof===CO||e.getModuleId!==void 0)};lr.typeOf=Ua;SO.exports=lr;var zZ=SO.exports,qZ=WL;function HZ(e){return qZ(e)&&e!=+e}var WZ=HZ;const dd=zs(WZ);var Js=function(t){return t===0?0:t>0?1:-1},zl=function(t){return ic(t)&&t.indexOf("%")===t.length-1},Oe=function(t){return VL(t)&&!dd(t)},VZ=function(t){return an(t)},xs=function(t){return Oe(t)||ic(t)},GZ=0,Sc=function(t){var r=++GZ;return"".concat(t||"").concat(r)},Xs=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Oe(t)&&!ic(t))return n;var i;if(zl(t)){var o=t.indexOf("%");i=r*parseFloat(t.slice(0,o))/100}else i=+t;return dd(i)&&(i=n),s&&i>r&&(i=r),i},qo=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},KZ=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},s=0;s<r;s++)if(!n[t[s]])n[t[s]]=!0;else return!0;return!1},ms=function(t,r){return Oe(t)&&Oe(r)?function(n){return t+n*(r-t)}:function(){return r}};function $m(e,t,r){return!e||!e.length?null:e.find(function(n){return n&&(typeof t=="function"?t(n):ba(n,t))===r})}var YZ=function(t,r){return Oe(t)&&Oe(r)?t-r:ic(t)&&ic(r)?t.localeCompare(r):t instanceof Date&&r instanceof Date?t.getTime()-r.getTime():String(t).localeCompare(String(r))};function xu(e,t){for(var r in e)if({}.hasOwnProperty.call(e,r)&&(!{}.hasOwnProperty.call(t,r)||e[r]!==t[r]))return!1;for(var n in t)if({}.hasOwnProperty.call(t,n)&&!{}.hasOwnProperty.call(e,n))return!1;return!0}function R0(e){"@babel/helpers - typeof";return R0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},R0(e)}var JZ=["viewBox","children"],XZ=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRen
6939dering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],$2=["points","pathLength"],rb={svg:JZ,polygon:$2,polyline:$2},Z1=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDrag
6939Capture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"],Fm=function(t,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(m.isValidElement(t)&&(n=t.props),!rd(n))return null;var s={};return Object.keys(n).forEach(function(i){Z1.includes(i)&&(s[i]=r||function(o){return n[i](n,o)})}),s},ZZ=function(t,r,n){return function(s){return t(r,n,s),null}},gc=function(t,r,n){if(!rd(t)||R0(t)!=="object")return null;var s=null;return Object.keys(t).forEach(function(i){var o=t[i];Z1.includes(i)&&typeof o=="function"&&(s||(s={}),s[i]=ZZ(o,r,n))}),s},QZ=["children"],eQ=["children"];function F2(e,t){if(e==null)return{};var r=tQ(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function tQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function D0(e){"@babel/helpers - typeof";return D0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},D0(e)}var B2={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},co=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},U2=null,sb=null,Q1=function e(t){if(t===U2&&Array.isArray(sb))return sb;var r=[];return m.Children.forEach(t,function(n){an(n)||(zZ.isFragment(n)?r=r.concat(e(n.props.children)):r.push(n))}),sb=r,U2=t,r};function wa(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(s){return co(s)}):n=[co(t)],Q1(e).forEach(function(s){var i=ba(s,"type.displayName")||ba(s,"type.name");n.indexOf(i)!==-1&&r.push(s)}),r}function fa(e,t){var r=wa(e,t);return r&&r[0]}var z2=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,s=r.height;return!(!Oe(n)||n<=0||!Oe(s)||s<=0)},nQ=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],rQ=function(t){return t&&t.type&&ic(t.type)&&nQ.indexOf(t.type)>=0},PO=function(t){return t&&D0(t)==="object"&&"clipDot"in t},sQ=function(t,r,n,s){var i,o=(i=rb==null?void 0:rb[s])!==null&&i!==void 0?i:[];return r.startsWith("data-")||!Kt(t)&&(s&&o.includes(r)||XZ.includes(r))||n&&Z1.includes(r)},Pt=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var s=t;if(m.isValidElement(t)&&(s=t.props),!rd(s))return null;var i={};
6939return Object.keys(s).forEach(function(o){var l;sQ((l=s)===null||l===void 0?void 0:l[o],o,r,n)&&(i[o]=s[o])}),i},M0=function e(t,r){if(t===r)return!0;var n=m.Children.count(t);if(n!==m.Children.count(r))return!1;if(n===0)return!0;if(n===1)return q2(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var s=0;s<n;s++){var i=t[s],o=r[s];if(Array.isArray(i)||Array.isArray(o)){if(!e(i,o))return!1}else if(!q2(i,o))return!1}return!0},q2=function(t,r){if(an(t)&&an(r))return!0;if(!an(t)&&!an(r)){var n=t.props||{},s=n.children,i=F2(n,QZ),o=r.props||{},l=o.children,c=F2(o,eQ);return s&&l?xu(i,c)&&M0(s,l):!s&&!l?xu(i,c):!1}return!1},H2=function(t,r){var n=[],s={};return Q1(t).forEach(function(i,o){if(rQ(i))n.push(i);else if(i){var l=co(i.type),c=r[l]||{},u=c.handler,d=c.once;if(u&&(!d||!s[l])){var p=u(i,l,o);n.push(p),s[l]=!0}}}),n},aQ=function(t){var r=t&&t.type;return r&&B2[r]?B2[r]:null},iQ=function(t,r){return Q1(r).indexOf(t)},oQ=["children","width","height","viewBox","className","style","title","desc"];function L0(){return L0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},L0.apply(this,arguments)}function lQ(e,t){if(e==null)return{};var r=cQ(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function cQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function $0(e){var t=e.children,r=e.width,n=e.height,s=e.viewBox,i=e.className,o=e.style,l=e.title,c=e.desc,u=lQ(e,oQ),d=s||{width:r,height:n,x:0,y:0},p=fn("recharts-surface",i);return H.createElement("svg",L0({},Pt(u,!0,"svg"),{className:p,width:r,height:n,style:o,viewBox:"".concat(d.x," ").concat(d.y," ").concat(d.width," ").concat(d.height)}),H.createElement("title",null,l),H.createElement("desc",null,c),t)}var uQ=["children","className"];function F0(){return F0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},F0.apply(this,arguments)}function dQ(e,t){if(e==null)return{};var r=pQ(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function pQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var Tn=H.forwardRef(function(e,t){var r=e.children,n=e.className,s=dQ(e,uQ),i=fn("recharts-layer",n);return H.createElement("g",F0({className:i},Pt(s,!0),{ref:t}),r)}),li=function(t,r){for(var n=arguments.length,s=new Array(n>2?n-2:0),i=2;i<n;i++)s[i-2]=arguments[i]};function Cr(e){return function(){return e}}const AO=Math.cos,Bm=Math.sin,hi=Math.sqrt,Um=Math.PI,Ax=2*Um,B0=Math.PI,U0=2*B0,Dl=1e-6,hQ=U0-Dl;function _O(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=arguments[t]+e[t]}function fQ(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return _O;const r=10**t;return function(n){this._+=n[0];for(let s=1,i=n.length;s<i;++s)this._+=Math.round(arguments[s]*r)/r+n[s]}}class mQ{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?_O:fQ(t)}moveTo(t,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,r){this._append`L${this._x1=+t},${this._y1=+r}`}quadraticCurveTo(t,r,n,s){this._append`Q${+t},${+r},${this._x1=+n},${this._y1=+s}`}bezierCurveTo(t,r,n,s,i,o){this._append`C${+t},${+r},${+n},${+s},${this._x1=+i},${this._y1=+o}`}arcTo(t,r,n,s,i){if(t=+t,r=+r,n=+n,s=+s,i=+i,i<0)throw new Error(`negative radius: ${i}`);let o=this._x1,l=this._y1,c=n-t,u=s-r,d=o-t,p=l-r,h=d*d+p*p;if(this._x1===null)this._append`M${this._x1=t},${this._y1=r}`;else if(h>Dl)if(!(Math.abs(p*c-u*d)>
6939Dl)||!i)this._append`L${this._x1=t},${this._y1=r}`;else{let f=n-o,x=s-l,g=c*c+u*u,y=f*f+x*x,b=Math.sqrt(g),v=Math.sqrt(h),k=i*Math.tan((B0-Math.acos((g+h-y)/(2*b*v)))/2),N=k/v,j=k/b;Math.abs(N-1)>Dl&&this._append`L${t+N*d},${r+N*p}`,this._append`A${i},${i},0,0,${+(p*f>d*x)},${this._x1=t+j*c},${this._y1=r+j*u}`}}arc(t,r,n,s,i,o){if(t=+t,r=+r,n=+n,o=!!o,n<0)throw new Error(`negative radius: ${n}`);let l=n*Math.cos(s),c=n*Math.sin(s),u=t+l,d=r+c,p=1^o,h=o?s-i:i-s;this._x1===null?this._append`M${u},${d}`:(Math.abs(this._x1-u)>Dl||Math.abs(this._y1-d)>Dl)&&this._append`L${u},${d}`,n&&(h<0&&(h=h%U0+U0),h>hQ?this._append`A${n},${n},0,1,${p},${t-l},${r-c}A${n},${n},0,1,${p},${this._x1=u},${this._y1=d}`:h>Dl&&this._append`A${n},${n},0,${+(h>=B0)},${p},${this._x1=t+n*Math.cos(i)},${this._y1=r+n*Math.sin(i)}`)}rect(t,r,n,s){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+s}h${-n}Z`}toString(){return this._}}function ej(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new mQ(t)}function tj(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function TO(e){this._context=e}TO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function _x(e){return new TO(e)}function EO(e){return e[0]}function IO(e){return e[1]}function OO(e,t){var r=Cr(!0),n=null,s=_x,i=null,o=ej(l);e=typeof e=="function"?e:e===void 0?EO:Cr(e),t=typeof t=="function"?t:t===void 0?IO:Cr(t);function l(c){var u,d=(c=tj(c)).length,p,h=!1,f;for(n==null&&(i=s(f=o())),u=0;u<=d;++u)!(u<d&&r(p=c[u],u,c))===h&&((h=!h)?i.lineStart():i.lineEnd()),h&&i.point(+e(p,u,c),+t(p,u,c));if(f)return i=null,f+""||null}return l.x=function(c){return arguments.length?(e=typeof c=="function"?c:Cr(+c),l):e},l.y=function(c){return arguments.length?(t=typeof c=="function"?c:Cr(+c),l):t},l.defined=function(c){return arguments.length?(r=typeof c=="function"?c:Cr(!!c),l):r},l.curve=function(c){return arguments.length?(s=c,n!=null&&(i=s(n)),l):s},l.context=function(c){return arguments.length?(c==null?n=i=null:i=s(n=c),l):n},l}function Tf(e,t,r){var n=null,s=Cr(!0),i=null,o=_x,l=null,c=ej(u);e=typeof e=="function"?e:e===void 0?EO:Cr(+e),t=typeof t=="function"?t:Cr(t===void 0?0:+t),r=typeof r=="function"?r:r===void 0?IO:Cr(+r);function u(p){var h,f,x,g=(p=tj(p)).length,y,b=!1,v,k=new Array(g),N=new Array(g);for(i==null&&(l=o(v=c())),h=0;h<=g;++h){if(!(h<g&&s(y=p[h],h,p))===b)if(b=!b)f=h,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),x=h-1;x>=f;--x)l.point(k[x],N[x]);l.lineEnd(),l.areaEnd()}b&&(k[h]=+e(y,h,p),N[h]=+t(y,h,p),l.point(n?+n(y,h,p):k[h],r?+r(y,h,p):N[h]))}if(v)return l=null,v+""||null}function d(){return OO().defined(s).curve(o).context(i)}return u.x=function(p){return arguments.length?(e=typeof p=="function"?p:Cr(+p),n=null,u):e},u.x0=function(p){return arguments.length?(e=typeof p=="function"?p:Cr(+p),u):e},u.x1=function(p){return arguments.length?(n=p==null?null:typeof p=="function"?p:Cr(+p),u):n},u.y=function(p){return arguments.length?(t=typeof p=="function"?p:Cr(+p),r=null,u):t},u.y0=function(p){return arguments.length?(t=typeof p=="function"?p:Cr(+p),u):t},u.y1=function(p){return arguments.length?(r=p==null?null:typeof p=="function"?p:Cr(+p),u):r},u.lineX0=u.lineY0=function(){return d().x(e).y(t)},u.lineY1=function(){return d().x(e).y(r)},u.lineX1=function(){return d().x(n).y(t)},u.defined=function(p){return arguments.length?(s=typeof p=="function"?p:Cr(!!p),u):s},u.curve=function(p){return arguments.length?(o=p,i!=null&&(l=o(i)),u):o},u.context=function(p){return arguments.length?(p==null?i=l=null:l=o(i=p),u):i},u}class RO{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function gQ(e){return new RO(e,!0)}function xQ(e){return new RO(e,!1)}const nj={draw(e,t){const r=hi(t/Um);e.moveTo(r,0),e.arc(0,0,r,0,Ax)}},yQ={draw(e,t){const r=hi(t/5)/2;e.moveTo(-3*r,-r),e.lineTo(-r,-r),e.lineTo(-r,-3*r),e.lineTo(r,-3*r),e.lineTo(r,-r),e.lineTo(3*r,-r),e.lineTo(3*r,r),e.lineTo(r,r),e.lineTo(r,3*r),e.lineTo(-r,3*r),e.lineTo(-r,r),e.lineTo(-3*r,r),e.closePath()}},DO=hi(1/3),bQ=DO*2,vQ={draw(e,t){const r=hi(t/bQ),n=r*DO;e.moveTo(0,-r),e.lineTo(n,0),e.lineTo(0,r),e.lineTo(-n,0),e.closePath()}},wQ={draw(e,t){const r=hi(t),n=-r/2;e.rect(n,n,r,r)}},jQ=.8908130915292852,MO=Bm(Um/10)/Bm(7*Um/10),NQ=Bm(Ax/10)*MO,kQ=-AO(Ax/10)*MO,SQ={draw(e,t){const r=hi(t*jQ),n=NQ*r,s=kQ*r;e.moveTo(0,-r),e.lineTo(n,s);for(let i=1;i<5;++i){const o=Ax*i/5,l=AO(o),c=Bm(o);
6939e.lineTo(c*r,-l*r),e.lineTo(l*n-c*s,c*n+l*s)}e.closePath()}},ab=hi(3),CQ={draw(e,t){const r=-hi(t/(ab*3));e.moveTo(0,r*2),e.lineTo(-ab*r,-r),e.lineTo(ab*r,-r),e.closePath()}},Ca=-.5,Pa=hi(3)/2,z0=1/hi(12),PQ=(z0/2+1)*3,AQ={draw(e,t){const r=hi(t/PQ),n=r/2,s=r*z0,i=n,o=r*z0+r,l=-i,c=o;e.moveTo(n,s),e.lineTo(i,o),e.lineTo(l,c),e.lineTo(Ca*n-Pa*s,Pa*n+Ca*s),e.lineTo(Ca*i-Pa*o,Pa*i+Ca*o),e.lineTo(Ca*l-Pa*c,Pa*l+Ca*c),e.lineTo(Ca*n+Pa*s,Ca*s-Pa*n),e.lineTo(Ca*i+Pa*o,Ca*o-Pa*i),e.lineTo(Ca*l+Pa*c,Ca*c-Pa*l),e.closePath()}};function _Q(e,t){let r=null,n=ej(s);e=typeof e=="function"?e:Cr(e||nj),t=typeof t=="function"?t:Cr(t===void 0?64:+t);function s(){let i;if(r||(r=i=n()),e.apply(this,arguments).draw(r,+t.apply(this,arguments)),i)return r=null,i+""||null}return s.type=function(i){return arguments.length?(e=typeof i=="function"?i:Cr(i),s):e},s.size=function(i){return arguments.length?(t=typeof i=="function"?i:Cr(+i),s):t},s.context=function(i){return arguments.length?(r=i??null,s):r},s}function zm(){}function qm(e,t,r){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+r)/6)}function LO(e){this._context=e}LO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:qm(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:qm(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function TQ(e){return new LO(e)}function $O(e){this._context=e}$O.prototype={areaStart:zm,areaEnd:zm,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:qm(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function EQ(e){return new $O(e)}function FO(e){this._context=e}FO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+e)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:qm(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function IQ(e){return new FO(e)}function BO(e){this._context=e}BO.prototype={areaStart:zm,areaEnd:zm,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function OQ(e){return new BO(e)}function W2(e){return e<0?-1:1}function V2(e,t,r){var n=e._x1-e._x0,s=t-e._x1,i=(e._y1-e._y0)/(n||s<0&&-0),o=(r-e._y1)/(s||n<0&&-0),l=(i*s+o*n)/(n+s);return(W2(i)+W2(o))*Math.min(Math.abs(i),Math.abs(o),.5*Math.abs(l))||0}function G2(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function ib(e,t,r){var n=e._x0,s=e._y0,i=e._x1,o=e._y1,l=(i-n)/3;e._context.bezierCurveTo(n+l,s+l*t,i-l,o-l*r,i,o)}function Hm(e){this._context=e}Hm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:ib(this,this._t0,G2(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,ib(this,G2(this,r=V2(this,e,t)),r);break;default:ib(this,this._t0,r=V2(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function UO(e){this._context=new zO(e)}(UO.prototype=Object.create(Hm.prototype)).point=function(e,t){Hm.prototype.point.call(this,t,e)};function zO(e){this._context=e}zO.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,s,i){this._context.bezierCurveTo(t,e,n,r,i,s)}};function RQ(e){return new Hm(e)}function DQ(e){return new UO(e)}function qO(e){this._context=e}qO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,r=e.length;if(r)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),r===2)this._context.lineTo(e[1],t[1]);else for(var n=K2(e),s=K2(t),i=0,o=1;o<r;++i,++o)this._context.bezierCurveTo(n[0][i],s[0][i],n[1][i],s[1][i],e[o],t[o]);(this._line||this._line!==0&&r===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function K2(e){var t,r=e.length-1,n,s=new Array(r),i=new Array(r),o=new Array(r);for(s[0]=0,i[0]=2,o[0]=e[0]+2*e[1],t=1;t<r-1;++t)s[t]=1,i[t]=4,o[t]=4*e[t]+2*e[t+1];for(s[r-1]=2,i[r-1]=7,o[r-1]=8*e[r-1]+e[r],t=1;t<r;++t)n=s[t]/i[t-1],i[t]-=n,o[t]-=n*o[t-1];for(s[r-1]=o[r-1]/i[r-1],t=r-2;t>=0;--t)s[t]=(o[t]-s[t+1])/i[t];for(i[r-1]=(e[r]+s[r-1])/2,t=0;t<r-1;++t)i[t]=2*e[t+1]-s[t+1];return[s,i]}function MQ(e){return new qO(e)}function Tx(e,t){this._context=e,this._t=t}Tx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;
vendor: 9,153 bytes, lines 6939-6942
6939default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function LQ(e){return new Tx(e,.5)}function $Q(e){return new Tx(e,0)}function FQ(e){return new Tx(e,1)}function _u(e,t){if((o=e.length)>1)for(var r=1,n,s,i=e[t[0]],o,l=i.length;r<o;++r)for(s=i,i=e[t[r]],n=0;n<l;++n)i[n][1]+=i[n][0]=isNaN(s[n][1])?s[n][0]:s[n][1]}function q0(e){for(var t=e.length,r=new Array(t);--t>=0;)r[t]=t;return r}function BQ(e,t){return e[t]}function UQ(e){const t=[];return t.key=e,t}function zQ(){var e=Cr([]),t=q0,r=_u,n=BQ;function s(i){var o=Array.from(e.apply(this,arguments),UQ),l,c=o.length,u=-1,d;for(const p of i)for(l=0,++u;l<c;++l)(o[l][u]=[0,+n(p,o[l].key,u,i)]).data=p;for(l=0,d=tj(t(o));l<c;++l)o[d[l]].index=l;return r(o,d),o}return s.keys=function(i){return arguments.length?(e=typeof i=="function"?i:Cr(Array.from(i)),s):e},s.value=function(i){return arguments.length?(n=typeof i=="function"?i:Cr(+i),s):n},s.order=function(i){return arguments.length?(t=i==null?q0:typeof i=="function"?i:Cr(Array.from(i)),s):t},s.offset=function(i){return arguments.length?(r=i??_u,s):r},s}function qQ(e,t){if((n=e.length)>0){for(var r,n,s=0,i=e[0].length,o;s<i;++s){for(o=r=0;r<n;++r)o+=e[r][s][1]||0;if(o)for(r=0;r<n;++r)e[r][s][1]/=o}_u(e,t)}}function HQ(e,t){if((s=e.length)>0){for(var r=0,n=e[t[0]],s,i=n.length;r<i;++r){for(var o=0,l=0;o<s;++o)l+=e[o][r][1]||0;n[r][1]+=n[r][0]=-l/2}_u(e,t)}}function WQ(e,t){if(!(!((o=e.length)>0)||!((i=(s=e[t[0]]).length)>0))){for(var r=0,n=1,s,i,o;n<i;++n){for(var l=0,c=0,u=0;l<o;++l){for(var d=e[t[l]],p=d[n][1]||0,h=d[n-1][1]||0,f=(p-h)/2,x=0;x<l;++x){var g=e[t[x]],y=g[n][1]||0,b=g[n-1][1]||0;f+=y-b}c+=p,u+=f*p}s[n-1][1]+=s[n-1][0]=r,c&&(r-=u/c)}s[n-1][1]+=s[n-1][0]=r,_u(e,t)}}function Up(e){"@babel/helpers - typeof";return Up=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Up(e)}var VQ=["type","size","sizeType"];function H0(){return H0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},H0.apply(this,arguments)}function Y2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function J2(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Y2(Object(r),!0).forEach(function(n){GQ(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Y2(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function GQ(e,t,r){return t=KQ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function KQ(e){var t=YQ(e,"string");return Up(t)=="symbol"?t:t+""}function YQ(e,t){if(Up(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Up(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function JQ(e,t){if(e==null)return{};var r=XQ(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function XQ(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var HO={symbolCircle:nj,symbolCross:yQ,symbolDiamond:vQ,symbolSquare:wQ,symbolStar:SQ,symbolTriangle:CQ,symbolWye:AQ},ZQ=Math.PI/180,QQ=function(t){var r="symbol".concat(Hg(t));return HO[r]||nj},eee=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var s=18*ZQ;return 1.25*t*t*(Math.tan(s)-Math.tan(s*2)*Math.pow(Math.tan(s),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},tee=function(t,r){HO["symbol".concat(Hg(t))]=r},rj=function(t){var r=t.type,n=r===void 0?"circle":r,s=t.size,i=s===void 0?64:s,o=t.sizeType,l=o===void 0?"area":o,c=JQ(t,VQ),u=J2(J2({},c),{},{type:n,size:i,sizeType:l}),d=function(){var y=QQ(n),b=_Q().type(y).size(eee(i,l,n));return b()},p=u.className,h=u.cx,f=u.cy,x=Pt(u,!0);return h===+h&&f===+f&&i===+i?H.createElement("path",H0({},x,{className:fn("recharts-symbols",p),transform:"translate(".concat(h,", ").concat(f,")"),d:d()})):null};rj.registerSymbol=tee;function Tu(e){"@babel/helpers - typeof";return Tu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Tu(e)}function W0(){return W0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},W0.apply(this,arguments)}function X2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function nee(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?X2(Object(r),!0).forEach(function(n){zp(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):X2(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function ree(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function see(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,VO(n.key),n)}}function aee(e,t,r){return t&&see(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function iee(e,t,r){return t=Wm(t),oee(e,WO()?Reflect.construct(t,r||[],Wm(e).constructor):t.apply(e,r))}function oee(e,t){if(t&&(Tu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return lee(e)}function lee(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function WO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(WO=function(){return!!e})()}function Wm(e){return Wm=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Wm(e)}function cee(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&V0(e,t)}function V0(e,t){return V0=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},V0(e,t)}function zp(e,t,r){return t=VO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function VO(e){var t=uee(e,"string");return Tu(t)=="symbol"?t:t+""}function uee(e,t){if(Tu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Tu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Aa=32,sj=function(e){function t(){return ree(this,t),iee(this,t,arguments)}return cee(t,e),aee(t,[{key:"renderIcon",value:function(n){var s=this.props.inactiveColor,i=Aa/2,o=Aa/6,l=Aa/3,c=n.inactive?s:n.color;if(n.type==="plainline")return H.createElement("line",{strokeWidth:4,fill:"none",stroke:c,strokeDasharray:n.payload.strokeDasharray,x1:0,y1:i,x2:Aa,y2:i,className:"recharts-legend-icon"});if(n.type==="line")return H.createElement("path",{strokeWidth:4,fill:"none",stroke:c,d:"M0,".concat(i,"h").concat(l,`
6940            A`).concat(o,",").concat(o,",0,1,1,").concat(2*l,",").concat(i,`
6941            H`).concat(Aa,"M").concat(2*l,",").concat(i,`
6942            A`).concat(o,",").concat(o,",0,1,1,").concat(l,",").concat(i),className:"recharts-legend-icon"});if(n.type==="rect")return H.createElement("path",{stroke:"none",fill:c,d:"M0,".concat(Aa/8,"h").concat(Aa,"v").concat(Aa*3/4,"h").concat(-Aa,"z"),className:"recharts-legend-icon"});if(H.isValidElement(n.legendIcon)){var u=nee({},n);return delete u.legendIcon,H.cloneElement(n.legendIcon,u)}return H.createElement(rj,{fill:c,cx:i,cy:i,size:Aa,sizeType:"diameter",type:n.type})}},{key:"renderItems",value:function(){var n=this,s=this.props,i=s.payload,o=s.iconSize,l=s.layout,c=s.formatter,u=s.inactiveColor,d={x:0,y:0,width:Aa,height:Aa}
6942,p={display:l==="horizontal"?"inline-block":"block",marginRight:10},h={display:"inline-block",verticalAlign:"middle",marginRight:4};return i.map(function(f,x){var g=f.formatter||c,y=fn(zp(zp({"recharts-legend-item":!0},"legend-item-".concat(x),!0),"inactive",f.inactive));if(f.type==="none")return null;var b=Kt(f.value)?null:f.value;li(!Kt(f.value),`The name property is also required when using a function for the dataKey of a chart's cartesian components. Ex: <Bar name="Name of my Data"/>`);var v=f.inactive?u:f.color;return H.createElement("li",W0({className:y,style:p,key:"legend-item-".concat(x)},gc(n.props,f,x)),H.createElement($0,{width:o,height:o,viewBox:d,style:h},n.renderIcon(f)),H.createElement("span",{className:"recharts-legend-item-text",style:{color:v}},g?g(b,f,x):b))})}},{key:"render",value:function(){var n=this.props,s=n.payload,i=n.layout,o=n.align;if(!s||!s.length)return null;var l={padding:0,margin:0,textAlign:i==="horizontal"?o:"left"};return H.createElement("ul",{className:"recharts-default-legend",style:l},this.renderItems())}}])}(m.PureComponent);zp(sj,"displayName","Legend");zp(sj,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});function dee(e,t,r){for(var n=-1,s=e==null?0:e.length;++n<s;)if(r(t,e[n]))return!0;return!1}var pee=dee,ob=GL,hee=KL,fee=W_,mee=1/0,gee=ob&&1/fee(new ob([,-0]))[1]==mee?function(e){return new ob(e)}:hee,xee=gee,yee=YL,bee=JL,vee=pee,wee=XL,jee=xee,Nee=W_,kee=200;function See(e,t,r){var n=-1,s=bee,i=e.length,o=!0,l=[],c=l;if(r)o=!1,s=vee;else if(i>=kee){var u=t?null:jee(e);if(u)return Nee(u);o=!1,s=wee,c=new yee}else c=t?[]:l;e:for(;++n<i;){var d=e[n],p=t?t(d):d;if(d=r||d!==0?d:0,o&&p===p){for(var h=c.length;h--;)if(c[h]===p)continue e;t&&c.push(p),l.push(d)}else s(c,p,r)||(c!==l&&c.push(p),l.push(d))}return l}var Cee=See,Pee=jc,Aee=Cee;function _ee(e,t){return e&&e.length?Aee(e,Pee(t)):[]}var Tee=_ee;const Z2=zs(Tee);function GO(e,t,r){return t===!0?Z2(e,r):Kt(t)?Z2(e,t):e}function Eu(e){"@babel/helpers - typeof";return Eu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Eu(e)}var Eee=["ref"];function Q2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Xi(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Q2(Object(r),!0).forEach(function(n){Ex(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Q2(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Iee(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function eC(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,YO(n.key),n)}}function Oee(e,t,r){return t&&eC(e.prototype,t),r&&eC(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ree(e,t,r){return t=Vm(t),Dee(e,KO()?Reflect.construct(t,r||[],Vm(e).constructor):t.apply(e,r))}function Dee(e,t){if(t&&(Eu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Mee(e)}function Mee(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function KO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(KO=function(){return!!e})()}function Vm(e){return Vm=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Vm(e)}function Lee(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&G0(e,t)}
6942function G0(e,t){return G0=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},G0(e,t)}function Ex(e,t,r){return t=YO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function YO(e){var t=$ee(e,"string");return Eu(t)=="symbol"?t:t+""}function $ee(e,t){if(Eu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Eu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Fee(e,t){if(e==null)return{};var r=Bee(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Bee(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Uee(e){return e.value}function zee(e,t){if(H.isValidElement(e))return H.cloneElement(e,t);if(typeof e=="function")return H.createElement(e,t);t.ref;var r=Fee(t,Eee);return H.createElement(sj,r)}var tC=1,uo=function(e){function t(){var r;Iee(this,t);for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];return r=Ree(this,t,[].concat(s)),Ex(r,"lastBoundingBox",{width:-1,height:-1}),r}return Lee(t,e),Oee(t,[{key:"componentDidMount",value:function(){this.updateBBox()}},{key:"componentDidUpdate",value:function(){this.updateBBox()}},{key:"getBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();return n.height=this.wrapperNode.offsetHeight,n.width=this.wrapperNode.offsetWidth,n}return null}},{key:"updateBBox",value:function(){var n=this.props.onBBoxUpdate,s=this.getBBox();s?(Math.abs(s.width-this.lastBoundingBox.width)>tC||Math.abs(s.height-this.lastBoundingBox.height)>tC)&&(this.lastBoundingBox.width=s.width,this.lastBoundingBox.height=s.height,n&&n(s)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?Xi({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var s=this.props,i=s.layout,o=s.align,l=s.verticalAlign,c=s.margin,u=s.chartWidth,d=s.chartHeight,p,h;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(o==="center"&&i==="vertical"){var f=this.getBBoxSnapshot();p={left:((u||0)-f.width)/2}}else p=o==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(l==="middle"){var x=this.getBBoxSnapshot();h={top:((d||0)-x.height)/2}}else h=l==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return Xi(Xi({},p),h)}},{key:"render",value:function(){var n=this,s=this.props,i=s.content,o=s.width,l=s.height,c=s.wrapperStyle,u=s.payloadUniqBy,d=s.payload,p=Xi(Xi({position:"absolute",width:o||"auto",height:l||"auto"},this.getDefaultPosition(c)),c);return H.createElement("div",{className:"recharts-legend-wrapper",style:p,ref:function(f){n.wrapperNode=f}},zee(i,Xi(Xi({},this.props),{},{payload:GO(d,u,Uee)})))}}],[{key:"getWithHeight",value:function(n,s){var i=Xi(Xi({},this.defaultProps),n.props),o=i.layout;return o==="vertical"&&Oe(n.props.height)?{height:n.props.height}:o==="horizontal"?{width:n.props.width||s}:null}}])}(m.PureComponent);Ex(uo,"displayName","Legend");Ex(uo,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var qee=V_,Hee=ZL;function Wee(e,t){var r=-1,n=Hee(e)?Array(e.length):[];return qee(e,function(s,i,o){n[++r]=t(s,i,o)}),n}var JO=Wee;function Vee(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}var Gee=Vee,nC=G_;function Kee(e,t){if(e!==t){var r=e!==void 0,n=e===null,s=e===e,i=nC(e),o=t!==void 0,l=t===null,c=t===t,u=nC(t);if(!l&&!u&&!i&&e>t||i&&o&&c&&!l&&!u||n&&o&&c||!r&&c||!s)return 1;if(!n&&!i&&!u&&e<t||u&&r&&s&&!n&&!i||l&&r&&s||!o&&s||!c)return-1}return 0}var Yee=Kee,Jee=Yee;function Xee(e,t,r){for(var n=-1,s=e.criteria,i=t.criteria,o=s.length,l=r.length;++n<o;){var c=Jee(s[n],i[n]);if(c){if(n>=l)return c;var u=r[n];return c*(u=="desc"?-1:1)}}return e.index-t.index}var Zee=Xee,lb=K_,Qee=QL,ete=jc,tte=JO,nte=Gee,rte=e$,ste=Zee,ate=vw,ite=ww;function ote(e,t,r){t.length?t=lb(t,function(i){return ite(i)?function(o){return Qee(o,i.length===1?i[0]:i)}:i}):t=[ate];var n=-1;t=lb(t,rte(ete));var s=tte(e,function(i,o,l){var c=lb(t,function(u){return u(i)});return{criteria:c,index:++n,value:i}});return nte(s,function(i,o){return ste(i,o,r)})}var lte=ote,cte=Y_,ute=lte,dte=t$,rC=jw,pte=dte(function(e,t){if(e==null)return[];var r=t.length;return r>1&&rC(e,t[0],t[1])?t=[]:r>2&&rC(t[0],t[1],t[2])&&(t=[t[0]]),ute(e,cte(t,1),[])}),hte=pte;const aj=zs(hte);function qp(e){"@babel/helpers - typeof";return qp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qp(e)}function K0(){return K0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];
vendor: 8,297 bytes, lines 6942-6943
6942for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},K0.apply(this,arguments)}function fte(e,t){return yte(e)||xte(e,t)||gte(e,t)||mte()}function mte(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6943In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gte(e,t){if(e){if(typeof e=="string")return sC(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return sC(e,t)}}function sC(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function xte(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function yte(e){if(Array.isArray(e))return e}function aC(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function cb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?aC(Object(r),!0).forEach(function(n){bte(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):aC(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bte(e,t,r){return t=vte(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function vte(e){var t=wte(e,"string");return qp(t)=="symbol"?t:t+""}function wte(e,t){if(qp(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(qp(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function jte(e){return Array.isArray(e)&&xs(e[0])&&xs(e[1])?e.join(" ~ "):e}var Nte=function(t){var r=t.separator,n=r===void 0?" : ":r,s=t.contentStyle,i=s===void 0?{}:s,o=t.itemStyle,l=o===void 0?{}:o,c=t.labelStyle,u=c===void 0?{}:c,d=t.payload,p=t.formatter,h=t.itemSorter,f=t.wrapperClassName,x=t.labelClassName,g=t.label,y=t.labelFormatter,b=t.accessibilityLayer,v=b===void 0?!1:b,k=function(){if(d&&d.length){var E={padding:0,margin:0},_=(h?aj(d,h):d).map(function(I,D){if(I.type==="none")return null;var M=cb({display:"block",paddingTop:4,paddingBottom:4,color:I.color||"#000"},l),B=I.formatter||p||jte,$=I.value,K=I.name,R=$,Y=K;if(B&&R!=null&&Y!=null){var Z=B($,K,I,D,d);if(Array.isArray(Z)){var O=fte(Z,2);R=O[0],Y=O[1]}else R=Z}return H.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(D),style:M},xs(Y)?H.createElement("span",{className:"recharts-tooltip-item-name"},Y):null,xs(Y)?H.createElement("span",{className:"recharts-tooltip-item-separator"},n):null,H.createElement("span",{className:"recharts-tooltip-item-value"},R),H.createElement("span",{className:"recharts-tooltip-item-unit"},I.unit||""))});return H.createElement("ul",{className:"recharts-tooltip-item-list",style:E},_)}return null},N=cb({margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},i),j=cb({margin:0},u),w=!an(g),S=w?g:"",T=fn("recharts-default-tooltip",f),C=fn("recharts-tooltip-label",x);w&&y&&d!==void 0&&d!==null&&(S=y(g,d));var A=v?{role:"status","aria-live":"assertive"}:{};return H.createElement("div",K0({className:T,style:N},A),H.createElement("p",{className:C,style:j},H.isValidElement(S)?S:"".concat(S)),k())};function Hp(e){"@babel/helpers - typeof";return Hp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hp(e)}function Ef(e,t,r){return t=kte(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function kte(e){var t=Ste(e,"string");return Hp(t)=="symbol"?t:t+""}function Ste(e,t){if(Hp(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Hp(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var zd="recharts-tooltip-wrapper",Cte={visibility:"hidden"};function Pte(e){var t=e.coordinate,r=e.translateX,n=e.translateY;return fn(zd,Ef(Ef(Ef(Ef({},"".concat(zd,"-right"),Oe(r)&&t&&Oe(t.x)&&r>=t.x),"".concat(zd,"-left"),Oe(r)&&t&&Oe(t.x)&&r<t.x),"".concat(zd,"-bottom"),Oe(n)&&t&&Oe(t.y)&&n>=t.y),"".concat(zd,"-top"),Oe(n)&&t&&Oe(t.y)&&n<t.y))}function iC(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.key,s=e.offsetTopLeft,i=e.position,o=e.reverseDirection,l=e.tooltipDimension,c=e.viewBox,u=e.viewBoxDimension;if(i&&Oe(i[n]))return i[n];var d=r[n]-l-s,p=r[n]+s;if(t[n])return o[n]?d:p;if(o[n]){var h=d,f=c[n];return h<f?Math.max(p,c[n]):Math.max(d,c[n])}var x=p+l,g=c[n]+u;return x>g?Math.max(d,c[n]):Math.max(p,c[n])}function Ate(e){var t=e.translateX,r=e.translateY,n=e.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function _te(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.offsetTopLeft,s=e.position,i=e.reverseDirection,o=e.tooltipBox,l=e.useTranslate3d,c=e.viewBox,u,d,p;return o.height>0&&o.width>0&&r?(d=iC({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:s,reverseDirection:i,tooltipDimension:o.width,viewBox:c,viewBoxDimension:c.width}),p=iC({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:s,reverseDirection:i,tooltipDimension:o.height,viewBox:c,viewBoxDimension:c.height}),u=Ate({translateX:d,translateY:p,useTranslate3d:l})):u=Cte,{cssProperties:u,cssClasses:Pte({translateX:d,translateY:p,coordinate:r})}}function Iu(e){"@babel/helpers - typeof";return Iu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Iu(e)}function oC(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function lC(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?oC(Object(r),!0).forEach(function(n){J0(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):oC(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Tte(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ete(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ZO(n.key),n)}}function Ite(e,t,r){return t&&Ete(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ote(e,t,r){return t=Gm(t),Rte(e,XO()?Reflect.construct(t,r||[],Gm(e).constructor):t.apply(e,r))}function Rte(e,t){if(t&&(Iu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Dte(e)}function Dte(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function XO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(XO=function(){return!!e})()}function Gm(e){return Gm=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Gm(e)}function Mte(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Y0(e,t)}
6943function Y0(e,t){return Y0=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Y0(e,t)}function J0(e,t,r){return t=ZO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ZO(e){var t=Lte(e,"string");return Iu(t)=="symbol"?t:t+""}function Lte(e,t){if(Iu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Iu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var cC=1,$te=function(e){function t(){var r;Tte(this,t);for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];return r=Ote(this,t,[].concat(s)),J0(r,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0},lastBoundingBox:{width:-1,height:-1}}),J0(r,"handleKeyDown",function(o){if(o.key==="Escape"){var l,c,u,d;r.setState({dismissed:!0,dismissedAtCoordinate:{x:(l=(c=r.props.coordinate)===null||c===void 0?void 0:c.x)!==null&&l!==void 0?l:0,y:(u=(d=r.props.coordinate)===null||d===void 0?void 0:d.y)!==null&&u!==void 0?u:0}})}}),r}return Mte(t,e),Ite(t,[{key:"updateBBox",value:function(){if(this.wrapperNode&&this.wrapperNode.getBoundingClientRect){var n=this.wrapperNode.getBoundingClientRect();(Math.abs(n.width-this.state.lastBoundingBox.width)>cC||Math.abs(n.height-this.state.lastBoundingBox.height)>cC)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,s;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,s=this.props,i=s.active,o=s.allowEscapeViewBox,l=s.animationDuration,c=s.animationEasing,u=s.children,d=s.coordinate,p=s.hasPayload,h=s.isAnimationActive,f=s.offset,x=s.position,g=s.reverseDirection,y=s.useTranslate3d,b=s.viewBox,v=s.wrapperStyle,k=_te({allowEscapeViewBox:o,coordinate:d,offsetTopLeft:f,position:x,reverseDirection:g,tooltipBox:this.state.lastBoundingBox,useTranslate3d:y,viewBox:b}),N=k.cssClasses,j=k.cssProperties,w=lC(lC({transition:h&&i?"transform ".concat(l,"ms ").concat(c):void 0},j),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&p?"visible":"hidden",position:"absolute",top:0,left:0},v);return H.createElement("div",{tabIndex:-1,className:N,style:w,ref:function(T){n.wrapperNode=T}},u)}}])}(m.PureComponent),Fte=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},ci={isSsr:Fte(),get:function(t){return ci[t]},set:function(t,r){if(typeof t=="string")ci[t]=r;else{var n=Object.keys(t);n&&n.length&&n.forEach(function(s){ci[s]=t[s]})}}};function Ou(e){"@babel/helpers - typeof";return Ou=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ou(e)}function uC(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function dC(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?uC(Object(r),!0).forEach(function(n){ij(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):uC(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Bte(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ute(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,e4(n.key),n)}}function zte(e,t,r){return t&&Ute(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function qte(e,t,r){return t=Km(t),Hte(e,QO()?Reflect.construct(t,r||[],Km(e).constructor):t.apply(e,r))}function Hte(e,t){if(t&&(Ou(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Wte(e)}function Wte(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function QO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(QO=function(){return!!e})()}function Km(e){return Km=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Km(e)}function Vte(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&X0(e,t)}
6943function X0(e,t){return X0=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},X0(e,t)}function ij(e,t,r){return t=e4(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function e4(e){var t=Gte(e,"string");return Ou(t)=="symbol"?t:t+""}function Gte(e,t){if(Ou(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Ou(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Kte(e){return e.dataKey}function Yte(e,t){return H.isValidElement(e)?H.cloneElement(e,t):typeof e=="function"?H.createElement(e,t):H.createElement(Nte,t)}var ga=function(e){function t(){return Bte(this,t),qte(this,t,arguments)}return Vte(t,e),zte(t,[{key:"render",value:function(){var n=this,s=this.props,i=s.active,o=s.allowEscapeViewBox,l=s.animationDuration,c=s.animationEasing,u=s.content,d=s.coordinate,p=s.filterNull,h=s.isAnimationActive,f=s.offset,x=s.payload,g=s.payloadUniqBy,y=s.position,b=s.reverseDirection,v=s.useTranslate3d,k=s.viewBox,N=s.wrapperStyle,j=x??[];p&&j.length&&(j=GO(x.filter(function(S){return S.value!=null&&(S.hide!==!0||n.props.includeHidden)}),g,Kte));var w=j.length>0;return H.createElement($te,{allowEscapeViewBox:o,animationDuration:l,animationEasing:c,isAnimationActive:h,active:i,coordinate:d,hasPayload:w,offset:f,position:y,reverseDirection:b,useTranslate3d:v,viewBox:k,wrapperStyle:N},Yte(u,dC(dC({},this.props),{},{payload:j})))}}])}(m.PureComponent);ij(ga,"displayName","Tooltip");ij(ga,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!ci.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var Jte=n$,Xte=r$,Zte="Expected a function";function Qte(e,t,r){var n=!0,s=!0;if(typeof e!="function")throw new TypeError(Zte);return Xte(r)&&(n="leading"in r?!!r.leading:n,s="trailing"in r?!!r.trailing:s),Jte(e,t,{leading:n,maxWait:t,trailing:s})}var ene=Qte;const t4=zs(ene);function Wp(e){"@babel/helpers - typeof";return Wp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wp(e)}function pC(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function If(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pC(Object(r),!0).forEach(function(n){tne(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pC(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function tne(e,t,r){return t=nne(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function nne(e){var t=rne(e,"string");return Wp(t)=="symbol"?t:t+""}function rne(e,t){if(Wp(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Wp(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function sne(e,t){return lne(e)||one(e,t)||ine(e,t)||ane()}function ane(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6944In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ine(e,t){if(e){if(typeof e=="string")return hC(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return hC(e,t)}}function hC(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function one(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}
vendor: 9,385 bytes, lines 6944-6949
6944finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function lne(e){if(Array.isArray(e))return e}var dm=m.forwardRef(function(e,t){var r=e.aspect,n=e.initialDimension,s=n===void 0?{width:-1,height:-1}:n,i=e.width,o=i===void 0?"100%":i,l=e.height,c=l===void 0?"100%":l,u=e.minWidth,d=u===void 0?0:u,p=e.minHeight,h=e.maxHeight,f=e.children,x=e.debounce,g=x===void 0?0:x,y=e.id,b=e.className,v=e.onResize,k=e.style,N=k===void 0?{}:k,j=m.useRef(null),w=m.useRef();w.current=v,m.useImperativeHandle(t,function(){return Object.defineProperty(j.current,"current",{get:function(){return console.warn("The usage of ref.current.current is deprecated and will no longer be supported."),j.current},configurable:!0})});var S=m.useState({containerWidth:s.width,containerHeight:s.height}),T=sne(S,2),C=T[0],A=T[1],P=m.useCallback(function(_,I){A(function(D){var M=Math.round(_),B=Math.round(I);return D.containerWidth===M&&D.containerHeight===B?D:{containerWidth:M,containerHeight:B}})},[]);m.useEffect(function(){var _=function(K){var R,Y=K[0].contentRect,Z=Y.width,O=Y.height;P(Z,O),(R=w.current)===null||R===void 0||R.call(w,Z,O)};g>0&&(_=t4(_,g,{trailing:!0,leading:!1}));var I=new ResizeObserver(_),D=j.current.getBoundingClientRect(),M=D.width,B=D.height;return P(M,B),I.observe(j.current),function(){I.disconnect()}},[P,g]);var E=m.useMemo(function(){var _=C.containerWidth,I=C.containerHeight;if(_<0||I<0)return null;li(zl(o)||zl(c),`The width(%s) and height(%s) are both fixed numbers,
6945       maybe you don't need to use a ResponsiveContainer.`,o,c),li(!r||r>0,"The aspect(%s) must be greater than zero.",r);var D=zl(o)?_:o,M=zl(c)?I:c;r&&r>0&&(D?M=D/r:M&&(D=M*r),h&&M>h&&(M=h)),li(D>0||M>0,`The width(%s) and height(%s) of chart should be greater than 0,
6946       please check the style of container, or the props width(%s) and height(%s),
6947       or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
6948       height and width.`,D,M,o,c,d,p,r);var B=!Array.isArray(f)&&co(f.type).endsWith("Chart");return H.Children.map(f,function($){return H.isValidElement($)?m.cloneElement($,If({width:D,height:M},B?{style:If({height:"100%",width:"100%",maxHeight:M,maxWidth:D},$.props.style)}:{})):$})},[r,f,c,h,p,d,C,o]);return H.createElement("div",{id:y?"".concat(y):void 0,className:fn("recharts-responsive-container",b),style:If(If({},N),{},{width:o,height:c,minWidth:d,minHeight:p,maxHeight:h}),ref:j},E)}),Ix=function(t){return null};Ix.displayName="Cell";function Vp(e){"@babel/helpers - typeof";return Vp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vp(e)}function fC(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Z0(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?fC(Object(r),!0).forEach(function(n){cne(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fC(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cne(e,t,r){return t=une(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function une(e){var t=dne(e,"string");return Vp(t)=="symbol"?t:t+""}function dne(e,t){if(Vp(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Vp(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Gc={widthCache:{},cacheCount:0},pne=2e3,hne={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},mC="recharts_measurement_span";function fne(e){var t=Z0({},e);return Object.keys(t).forEach(function(r){t[r]||delete t[r]}),t}var jp=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||ci.isSsr)return{width:0,height:0};var n=fne(r),s=JSON.stringify({text:t,copyStyle:n});if(Gc.widthCache[s])return Gc.widthCache[s];try{var i=document.getElementById(mC);i||(i=document.createElement("span"),i.setAttribute("id",mC),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var o=Z0(Z0({},hne),n);Object.assign(i.style,o),i.textContent="".concat(t);var l=i.getBoundingClientRect(),c={width:l.width,height:l.height};return Gc.widthCache[s]=c,++Gc.cacheCount>pne&&(Gc.cacheCount=0,Gc.widthCache={}),c}catch{return{width:0,height:0}}},mne=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function Gp(e){"@babel/helpers - typeof";return Gp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gp(e)}function Ym(e,t){return bne(e)||yne(e,t)||xne(e,t)||gne()}function gne(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6949In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xne(e,t){if(e){if(typeof e=="string")return gC(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return gC(e,t)}}function gC(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function yne(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function bne(e){if(Array.isArray(e))return e}function vne(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function xC(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,jne(n.key),n)}}function wne(e,t,r){return t&&xC(e.prototype,t),r&&xC(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function jne(e){var t=Nne(e,"string");return Gp(t)=="symbol"?t:t+""}function Nne(e,t){if(Gp(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(Gp(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var yC=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,bC=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,kne=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,Sne=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,n4={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},Cne=Object.keys(n4),ou="NaN";function Pne(e,t){return e*n4[t]}var Of=function(){function e(t,r){vne(this,e),this.num=t,this.unit=r,this.num=t,this.unit=r,Number.isNaN(t)&&(this.unit=""),r!==""&&!kne.test(r)&&(this.num=NaN,this.unit=""),Cne.includes(r)&&(this.num=Pne(t,r),this.unit="px")}return wne(e,[{key:"add",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num+r.num,this.unit)}},{key:"subtract",value:function(r){return this.unit!==r.unit?new e(NaN,""):new e(this.num-r.num,this.unit)}},{key:"multiply",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num*r.num,this.unit||r.unit)}},{key:"divide",value:function(r){return this.unit!==""&&r.unit!==""&&this.unit!==r.unit?new e(NaN,""):new e(this.num/r.num,this.unit||r.unit)}},{key:"toString",value:function(){return"".concat(this.num).concat(this.unit)}},{key:"isNaN",value:function(){return Number.isNaN(this.num)}}],[{key:"parse",value:function(r){var n,s=(n=Sne.exec(r))!==null&&n!==void 0?n:[],i=Ym(s,3),o=i[1],l=i[2];return new e(parseFloat(o),l??"")}}])}();function r4(e){if(e.includes(ou))return ou;for(var t=e;t.includes("*")||t.includes("/");){var r,n=(r=yC.exec(t))!==null&&r!==void 0?r:[],s=Ym(n,4),i=s[1],o=s[2],l=s[3],c=Of.parse(i??""),u=Of.parse(l??""),d=o==="*"?c.multiply(u):c.divide(u);if(d.isNaN())return ou;t=t.replace(yC,d.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var p,h=(p=bC.exec(t))!==null&&p!==void 0?p:[],f=Ym(h,4),x=f[1],g=f[2],y=f[3],b=Of.parse(x??""),v=Of.parse(y??""),k=g==="+"?b.add(v):b.subtract(v);if(k.isNaN())return ou;t=t.replace(bC,k.toString())}return t}var vC=/\(([^()]*)\)/;function Ane(e){for(var t=e;t.includes("(");){var r=vC.exec(t),n=Ym(r,2),s=n[1];t=t.replace(vC,r4(s))}return t}function _ne(e){var t=e.replace(/\s+/g,"");return t=Ane(t),t=r4(t),t}function Tne(e){try{return _ne(e)}catch{return ou}}function ub(e){var t=Tne(e.slice(5,-1));return t===ou?"":t}var Ene=["x","y","lineHeight","capHeight","scaleToFit","textAnchor","verticalAnchor","fill"],Ine=["dx","dy","angle","className","breakAll"];function Q0(){return Q0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];
6949for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Q0.apply(this,arguments)}function wC(e,t){if(e==null)return{};var r=One(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function One(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function jC(e,t){return Lne(e)||Mne(e,t)||Dne(e,t)||Rne()}function Rne(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6950In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Dne(e,t){if(e){if(typeof e=="string")return NC(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return NC(e,t)}}function NC(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Mne(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function Lne(e){if(Array.isArray(e))return e}var s4=/[ \f\n\r\t\v\u2028\u2029]+/,a4=function(t){var r=t.children,n=t.breakAll,s=t.style;try{var i=[];an(r)||(n?i=r.toString().split(""):i=r.toString().split(s4));var o=i.map(function(c){return{word:c,width:jp(c,s).width}}),l=n?0:jp(" ",s).width;return{wordsWithComputedWidth:o,spaceWidth:l}}catch{return null}},$ne=function(t,r,n,s,i){var o=t.maxLines,l=t.children,c=t.style,u=t.breakAll,d=Oe(o),p=l,h=function(){var D=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return D.reduce(function(M,B){var $=B.word,K=B.width,R=M[M.length-1];if(R&&(s==null||i||R.width+K+n<Number(s)))R.words.push($),R.width+=K+n;else{var Y={words:[$],width:K};M.push(Y)}return M},[])},f=h(r),x=function(D){return D.reduce(function(M,B){return M.width>B.width?M:B})};if(!d)return f;for(var g="…",y=function(D){var M=p.slice(0,D),B=a4({breakAll:u,style:c,children:M+g}).wordsWithComputedWidth,$=h(B),K=$.length>o||x($).width>Number(s);return[K,$]},b=0,v=p.length-1,k=0,N;b<=v&&k<=p.length-1;){var j=Math.floor((b+v)/2),w=j-1,S=y(w),T=jC(S,2),C=T[0],A=T[1],P=y(j),E=jC(P,1),_=E[0];if(!C&&!_&&(b=j+1),C&&_&&(v=j-1),!C&&_){N=A;break}k++}return N||f},kC=function(t){var r=an(t)?[]:t.toString().split(s4);return[{words:r}]},Fne=function(t){var r=t.width,n=t.scaleToFit,s=t.children,i=t.style,o=t.breakAll,l=t.maxLines;if((r||n)&&!ci.isSsr){var c,u,d=a4({breakAll:o,children:s,style:i});if(d){var p=d.wordsWithComputedWidth,h=d.spaceWidth;c=p,u=h}else return kC(s);return $ne({breakAll:o,children:s,maxLines:l,style:i},c,u,r,n)}return kC(s)},SC="#808080",xc=function(t){var r=t.x,n=r===void 0?0:r,s=t.y,i=s===void 0?0:s,o=t.lineHeight,l=o===void 0?"1em":o,c=t.capHeight,u=c===void 0?"0.71em":c,d=t.scaleToFit,p=d===void 0?!1:d,h=t.textAnchor,f=h===void 0?"start":h,x=t.verticalAnchor,g=x===void 0?"end":x,y=t.fill,b=y===void 0?SC:y,v=wC(t,Ene),k=m.useMemo(function(){return Fne({breakAll:v.breakAll,children:v.children,maxLines:v.maxLines,scaleToFit:p,style:v.style,width:v.width})},[v.breakAll,v.children,v.maxLines,p,v.style,v.width]),N=v.dx,j=v.dy,w=v.angle,S=v.className,T=v.breakAll,C=wC(v,Ine);if(!xs(n)||!xs(i))return null;var A=n+(Oe(N)?N:0),P=i+(Oe(j)?j:0),E;switch(g){case"start":E=ub("calc(".concat(u,")"));break;case"middle":E=ub("calc(".concat((k.length-1)/2," * -").concat(l," + (").concat(u," / 2))"));break;default:E=ub("calc(".concat(k.length-1," * -").concat(l,")"));break}var _=[];if(p){var I=k[0].width,D=v.width;_.push("scale(".concat((Oe(D)?D/I:1)/I,")"))}return w&&_.push("rotate(".concat(w,", ").concat(A,", ").concat(P,")")),_.length&&(C.transform=_.join(" ")),H.createElement("text",Q0({},Pt(C,!0),{x:A,y:P,className:fn("recharts-text",S),textAnchor:f,fill:b.includes("url")?SC:b}),k.map(function(M,B){var $=M.words.join(T?"":" ");return H.createElement("tspan",{x:A,dy:B===0?E:l,key:"".concat($,"-").concat(B)},$)}))};function Zo(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function Bne(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function oj(e){let t,r,n;e.length!==2?(t=Zo,r=(l,c)=>Zo(e(l),c),n=(l,c)=>e(l)-c):(t=e===Zo||e===Bne?e:Une,r=e,n=e);function s(l,c,u=0,d=l.length){if(u<d){if(t(c,c)!==0)return d;do{const p=u+d>>>1;r(l[p],c)<0?u=p+1:d=p}while(u<d)}return u}function i(l,c,u=0,d=l.length){if(u<d){if(t(c,c)!==0)return d;do{const p=u+d>>>1;r(l[p],c)<=0?u=p+1:d=p}while(u<d)}return u}function o(l,c,u=0,d=l.length){const p=s(l,c,u,d-1);return p>u&&n(l[p-1],c)>-n(l[p],c)?p-1:p}return{left:s,center:o,right:i}}function Une(){return 0}function i4(e){return e===null?NaN:+e}function*zne(e,t){for(let r of e)r!=null&&(r=+r)>=r&&(yield r)}const qne=oj(Zo),Mh=qne.right;oj(i4).center;class CC extends Map{constructor(t,r=Vne){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,s]of t)this.set(n,s)}get(t){return super.get(PC(this,t))}has(t){return super.has(PC(this,t))}set(t,r){return super.set(Hne(this,t),r)}delete(t){return super.delete(Wne(this,t))}}function PC({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):r}function Hne({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function Wne({_intern:e,_key:t},r){const n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function Vne(e){return e!==null&&typeof e=="object"?e.valueOf():e}function Gne(e=Zo){if(e===Zo)return o4;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=e(t,r);return n||n===0?n:(e(r,r)===0)-(e(t,t)===0)}}function o4(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(e<t?-1:e>t?1:0)}const Kne=Math.sqrt(50),Yne=Math.sqrt(10),Jne=Math.sqrt(2);function Jm(e,t,r){const n=(t-e)/Math.max(0,r),s=Math.floor(Math.log10(n)),i=n/Math.pow(10,s),o=i>=Kne?10:i>=Yne?5:i>=Jne?2:1;let l,c,u;return s<0?(u=Math.pow(10,-s)/o,l=Math.round(e*u),c=Math.round(t*u),l/u<e&&++l,c/u>t&&--c,u=-u):(u=Math.pow(10,s)*o,l=Math.round(e/u),c=Math.round(t/u),l*u<e&&++l,c*u>t&&--c),c<l&&.5<=r&&r<2?Jm(e,t,r*2):[l,c,u]}function ev(e,t,r){if(t=+t,e=+e,r=+r,!(r>0))return[];if(e===t)return[e];const n=t<e,[s,i,o]=n?Jm(t,e,r):Jm(e,t,r);if(!(i>=s))return[];const l=i-s+1,c=new Array(l);if(n)if(o<0)for(let u=0;u<l;++u)c[u]=(i-u)/-o;else for(let u=0;u<l;++u)c[u]=(i-u)*o;else if(o<0)for(let u=0;u<l;++u)c[u]=(s+u)/-o;else for(let u=0;u<l;++u)c[u]=(s+u)*o;return c}function tv(e,t,r){return t=+t,e=+e,r=+r,Jm(e,t,r)[2]}function nv(e,t,r){t=+t,e=+e,r=+r;const n=t<e,s=n?tv(t,e,r):tv(e,t,r);return(n?-1:1)*(s<0?1/-s:s)}function AC(e,t){let r;for(const n of e)n!=null&&(r<n||r===void 0&&n>=n)&&(r=n);return r}function _C(e,t){let r;for(const n of e)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function l4(e,t,r=0,n=1/0,s){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(e.length-1,n)),!(r<=t&&t<=n))return e;for(s=s===void 0?o4:Gne(s);n>r;){if(n-r>600){const c=n-r+1,u=t-r+1,d=Math.log(c),p=.5*Math.exp(2*d/3),h=.5*Math.sqrt(d*p*(c-p)/c)*(u-c/2<0?-1:1),f=Math.max(r,Math.floor(t-u*p/c+h)),x=Math.min(n,Math.floor(t+(c-u)*p/c+h));l4(e,t,f,x,s)}const i=e[t];let o=r,l=n;for(qd(e,r,t),s(e[n],i)>0&&qd(e,r,n);o<l;){for(qd(e,o,l),++o,--l;s(e[o],i)<0;)++o;for(;s(e[l],i)>0;)--l}s(e[r],i)===0?qd(e,r,l):(++l,qd(e,l,n)),l<=t&&(r=l+1),t<=l&&(n=l-1)}return e}function qd(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function Xne(e,t,r){if(e=Float64Array.from(zne(e)),!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return _C(e);if(t>=1)return AC(e);var n,s=(n-1)*t,i=Math.floor(s),o=AC(l4(e,i).subarray(0,i+1)),l=_C(e.subarray(i+1));return o+(l-o)*(s-i)}}function Zne(e,t,r=i4){if(!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(e[0],0,e);if(t>=1)return+r(e[n-1],n-1,e);var n,s=(n-1)*t,i=Math.floor(s),o=+r(e[i],i,e),l=+r(e[i+1],i+1,e);return o+(l-o)*(s-i)}}function Qne(e,t,r){e=+e,t=+t,r=(s=arguments.length)<2?(t=e,e=0,1):s<3?1:+r;for(var n=-1,s=Math.max(0,Math.ceil((t-e)/r))|0,i=new Array(s);++n<s;)i[n]=e+n*r;return i}function za(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}function vo(e,t){switch(arguments.length){case 0:break;case 1:{typeof e=="function"?this.interpolator(e):this.range(e);break}default:{this.domain(e),typeof t=="function"?this.interpolator(t):this.range(t);break}}return this}
vendor: 6,190 bytes, line 6950
6950const rv=Symbol("implicit");function lj(){var e=new CC,t=[],r=[],n=rv;function s(i){let o=e.get(i);if(o===void 0){if(n!==rv)return n;e.set(i,o=t.push(i)-1)}return r[o%r.length]}return s.domain=function(i){if(!arguments.length)return t.slice();t=[],e=new CC;for(const o of i)e.has(o)||e.set(o,t.push(o)-1);return s},s.range=function(i){return arguments.length?(r=Array.from(i),s):r.slice()},s.unknown=function(i){return arguments.length?(n=i,s):n},s.copy=function(){return lj(t,r).unknown(n)},za.apply(s,arguments),s}function Kp(){var e=lj().unknown(void 0),t=e.domain,r=e.range,n=0,s=1,i,o,l=!1,c=0,u=0,d=.5;delete e.unknown;function p(){var h=t().length,f=s<n,x=f?s:n,g=f?n:s;i=(g-x)/Math.max(1,h-c+u*2),l&&(i=Math.floor(i)),x+=(g-x-i*(h-c))*d,o=i*(1-c),l&&(x=Math.round(x),o=Math.round(o));var y=Qne(h).map(function(b){return x+i*b});return r(f?y.reverse():y)}return e.domain=function(h){return arguments.length?(t(h),p()):t()},e.range=function(h){return arguments.length?([n,s]=h,n=+n,s=+s,p()):[n,s]},e.rangeRound=function(h){return[n,s]=h,n=+n,s=+s,l=!0,p()},e.bandwidth=function(){return o},e.step=function(){return i},e.round=function(h){return arguments.length?(l=!!h,p()):l},e.padding=function(h){return arguments.length?(c=Math.min(1,u=+h),p()):c},e.paddingInner=function(h){return arguments.length?(c=Math.min(1,h),p()):c},e.paddingOuter=function(h){return arguments.length?(u=+h,p()):u},e.align=function(h){return arguments.length?(d=Math.max(0,Math.min(1,h)),p()):d},e.copy=function(){return Kp(t(),[n,s]).round(l).paddingInner(c).paddingOuter(u).align(d)},za.apply(p(),arguments)}function c4(e){var t=e.copy;return e.padding=e.paddingOuter,delete e.paddingInner,delete e.paddingOuter,e.copy=function(){return c4(t())},e}function Np(){return c4(Kp.apply(null,arguments).paddingInner(1))}function cj(e,t,r){e.prototype=t.prototype=r,r.constructor=e}function u4(e,t){var r=Object.create(e.prototype);for(var n in t)r[n]=t[n];return r}function Lh(){}var Yp=.7,Xm=1/Yp,yu="\\s*([+-]?\\d+)\\s*",Jp="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",_i="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",ere=/^#([0-9a-f]{3,8})$/,tre=new RegExp(`^rgb\\(${yu},${yu},${yu}\\)$`),nre=new RegExp(`^rgb\\(${_i},${_i},${_i}\\)$`),rre=new RegExp(`^rgba\\(${yu},${yu},${yu},${Jp}\\)$`),sre=new RegExp(`^rgba\\(${_i},${_i},${_i},${Jp}\\)$`),are=new RegExp(`^hsl\\(${Jp},${_i},${_i}\\)$`),ire=new RegExp(`^hsla\\(${Jp},${_i},${_i},${Jp}\\)$`),TC={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};cj(Lh,Xp,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:EC,formatHex:EC,formatHex8:ore,formatHsl:lre,formatRgb:IC,toString:IC});function EC(){return this.rgb().formatHex()}function ore(){return this.rgb().formatHex8()}function lre(){return d4(this).formatHsl()}function IC(){return this.rgb().formatRgb()}function Xp(e){var t,r;return e=(e+"").trim().toLowerCase(),(t=ere.exec(e))?(r=t[1].length,t=parseInt(t[1],16),r===6?OC(t):r===3?new na(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?Rf(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?Rf(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=tre.exec(e))?new na(t[1],t[2],t[3],1):(t=nre.exec(e))?new na(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=rre.exec(e))?Rf(t[1],t[2],t[3],t[4]):(t=sre.exec(e))?Rf(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=are.exec(e))?MC(t[1],t[2]/100,t[3]/100,1):(t=ire.exec(e))?MC(t[1],t[2]/100,t[3]/100,t[4]):TC.hasOwnProperty(e)?OC(TC[e]):e==="transparent"?new n
vendor: 14,943 bytes, line 6950
6950a(NaN,NaN,NaN,0):null}function OC(e){return new na(e>>16&255,e>>8&255,e&255,1)}function Rf(e,t,r,n){return n<=0&&(e=t=r=NaN),new na(e,t,r,n)}function cre(e){return e instanceof Lh||(e=Xp(e)),e?(e=e.rgb(),new na(e.r,e.g,e.b,e.opacity)):new na}function sv(e,t,r,n){return arguments.length===1?cre(e):new na(e,t,r,n??1)}function na(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}cj(na,sv,u4(Lh,{brighter(e){return e=e==null?Xm:Math.pow(Xm,e),new na(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Yp:Math.pow(Yp,e),new na(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new na(tc(this.r),tc(this.g),tc(this.b),Zm(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:RC,formatHex:RC,formatHex8:ure,formatRgb:DC,toString:DC}));function RC(){return`#${ql(this.r)}${ql(this.g)}${ql(this.b)}`}function ure(){return`#${ql(this.r)}${ql(this.g)}${ql(this.b)}${ql((isNaN(this.opacity)?1:this.opacity)*255)}`}function DC(){const e=Zm(this.opacity);return`${e===1?"rgb(":"rgba("}${tc(this.r)}, ${tc(this.g)}, ${tc(this.b)}${e===1?")":`, ${e})`}`}function Zm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function tc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function ql(e){return e=tc(e),(e<16?"0":"")+e.toString(16)}function MC(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new Qa(e,t,r,n)}function d4(e){if(e instanceof Qa)return new Qa(e.h,e.s,e.l,e.opacity);if(e instanceof Lh||(e=Xp(e)),!e)return new Qa;if(e instanceof Qa)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,s=Math.min(t,r,n),i=Math.max(t,r,n),o=NaN,l=i-s,c=(i+s)/2;return l?(t===i?o=(r-n)/l+(r<n)*6:r===i?o=(n-t)/l+2:o=(t-r)/l+4,l/=c<.5?i+s:2-i-s,o*=60):l=c>0&&c<1?0:o,new Qa(o,l,c,e.opacity)}function dre(e,t,r,n){return arguments.length===1?d4(e):new Qa(e,t,r,n??1)}function Qa(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}cj(Qa,dre,u4(Lh,{brighter(e){return e=e==null?Xm:Math.pow(Xm,e),new Qa(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Yp:Math.pow(Yp,e),new Qa(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,s=2*r-n;return new na(db(e>=240?e-240:e+120,s,n),db(e,s,n),db(e<120?e+240:e-120,s,n),this.opacity)},clamp(){return new Qa(LC(this.h),Df(this.s),Df(this.l),Zm(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Zm(this.opacity);return`${e===1?"hsl(":"hsla("}${LC(this.h)}, ${Df(this.s)*100}%, ${Df(this.l)*100}%${e===1?")":`, ${e})`}`}}));function LC(e){return e=(e||0)%360,e<0?e+360:e}function Df(e){return Math.max(0,Math.min(1,e||0))}function db(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}const uj=e=>()=>e;function pre(e,t){return function(r){return e+r*t}}function hre(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function fre(e){return(e=+e)==1?p4:function(t,r){return r-t?hre(t,r,e):uj(isNaN(t)?r:t)}}function p4(e,t){var r=t-e;return r?pre(e,r):uj(isNaN(e)?t:e)}const $C=function e(t){var r=fre(t);function n(s,i){var o=r((s=sv(s)).r,(i=sv(i)).r),l=r(s.g,i.g),c=r(s.b,i.b),u=p4(s.opacity,i.opacity);return function(d){return s.r=o(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return n.gamma=e,n}(1);function mre(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),s;return function(i){for(s=0;s<r;++s)n[s]=e[s]*(1-i)+t[s]*i;return n}}function gre(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function xre(e,t){var r=t?t.length:0,n=e?Math.min(r,e.length):0,s=new Array(n),i=new Array(r),o;for(o=0;o<n;++o)s[o]=pd(e[o],t[o]);for(;o<r;++o)i[o]=t[o];return function(l){for(o=0;o<n;++o)i[o]=s[o](l);return i}}function yre(e,t){var r=new Date;return e=+e,t=+t,function(n){return r.setTime(e*(1-n)+t*n),r}}function Qm(e,t){return e=+e,t=+t,function(r){return e*(1-r)+t*r}}function bre(e,t){var r={},n={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?r[s]=pd(e[s],t[s]):n[s]=t[s];return function(i){for(s in r)n[s]=r[s](i);return n}}var av=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,pb=new RegExp(av.source,"g");function vre(e){return function(){return e}}function wre(e){return function(t){return e(t)+""}}function jre(e,t){var r=av.lastIndex=pb.lastIndex=0,n,s,i,o=-1,l=[],c=[];for(e=e+"",t=t+"";(n=av.exec(e))&&(s=pb.exec(t));)(i=s.index)>r&&(i=t.slice(r,i),l[o]?l[o]+=i:l[++o]=i),(n=n[0])===(s=s[0])?l[o]?l[o]+=s:l[++o]=s:(l[++o]=null,c.push({i:o,x:Qm(n,s)})),r=pb.lastIndex;return r<t.length&&(i=t.slice(r),l[o]?l[o]+=i:l[++o]=i),l.length<2?c[0]?wre(c[0].x):vre(t):(t=c.length,function(u){for(var d=0,p;d<t;++d)l[(p=c[d]).i]=p.x(u);return l.join("")})}function pd(e,t){var r=typeof t,n;return t==null||r==="boolean"?uj(t):(r==="number"?Qm:r==="string"?(n=Xp(t))?(t=n,$C):jre:t instanceof Xp?$C:t instanceof Date?yre:gre(t)?mre:Array.isArray(t)?xre:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?bre:Qm)(e,t)}function dj(e,t){return e=+e,t=+t,function(r){return Math.round(e*(1-r)+t*r)}}function Nre(e,t){t===void 0&&(t=e,e=pd);for(var r=0,n=t.length-1,s=t[0],i=new Array(n<0?0:n);r<n;)i[r]=e(s,s=t[++r]);return function(o){var l=Math.max(0,Math.min(n-1,Math.floor(o*=n)));return i[l](o-l)}}function kre(e){return function(){return e}}function eg(e){return+e}var FC=[0,1];function Zs(e){return e}function iv(e,t){return(t-=e=+e)?function(r){return(r-e)/t}:kre(isNaN(t)?NaN:.5)}function Sre(e,t){var r;return e>t&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function Cre(e,t,r){var n=e[0],s=e[1],i=t[0],o=t[1];return s<n?(n=iv(s,n),i=r(o,i)):(n=iv(n,s),i=r(i,o)),function(l){return i(n(l))}}function Pre(e,t,r){var n=Math.min(e.length,t.length)-1,s=new Array(n),i=new Array(n),o=-1;for(e[n]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++o<n;)s[o]=iv(e[o],e[o+1]),i[o]=r(t[o],t[o+1]);return function(l){var c=Mh(e,l,1,n)-1;return i[c](s[c](l))}}function $h(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function Ox(){var e=FC,t=FC,r=pd,n,s,i,o=Zs,l,c,u;function d(){var h=Math.min(e.length,t.length);return o!==Zs&&(o=Sre(e[0],e[h-1])),l=h>2?Pre:Cre,c=u=null,p}function p(h){return h==null||isNaN(h=+h)?i:(c||(c=l(e.map(n),t,r)))(n(o(h)))}return p.invert=function(h){return o(s((u||(u=l(t,e.map(n),Qm)))(h)))},p.domain=function(h){return arguments.length?(e=Array.from(h,eg),d()):e.slice()},p.range=function(h){return arguments.length?(t=Array.from(h),d()):t.slice()},p.rangeRound=function(h){return t=Array.from(h),r=dj,d()},p.clamp=function(h){return arguments.length?(o=h?!0:Zs,d()):o!==Zs},p.interpolate=function(h){return arguments.length?(r=h,d()):r},p.unknown=function(h){return arguments.length?(i=h,p):i},function(h,f){return n=h,s=f,d()}}function pj(){return Ox()(Zs,Zs)}function Are(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function tg(e,t){if((r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"))<0)return null;var r,n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function Ru(e){return e=tg(Math.abs(e)),e?e[1]:NaN}function _re(e,t){return function(r,n){for(var s=r.length,i=[],o=0,l=e[0],c=0;s>0&&l>0&&(c+l+1>n&&(l=Math.max(1,n-c)),i.push(r.substring(s-=l,s+l)),!((c+=l+1)>n));)l=e[o=(o+1)%e.length];return i.reverse().join(t)}}function Tre(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}var Ere=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Zp(e){if(!(t=Ere.exec(e)))throw new Error("invalid format: "+e);var t;return new hj({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Zp.prototype=hj.prototype;function hj(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}hj.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function Ire(e){e:for(var t=e.length,r=1,n=-1,s;r<t;++r)switch(e[r]){case".":n=s=r;break;case"0":n===0&&(n=r),s=r;break;default:if(!+e[r])break e;n>0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(s+1):e}var h4;function Ore(e,t){var r=tg(e,t);if(!r)return e+"";var n=r[0],s=r[1],i=s-(h4=Math.max(-8,Math.min(8,Math.floor(s/3)))*3)+1,o=n.length;return i===o?n:i>o?n+new Array(i-o+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+tg(e,Math.max(0,t+i-1))[0]}function BC(e,t){var r=tg(e,t);if(!r)return e+"";var n=r[0],s=r[1];return s<0?"0."+new Array(-s).join("0")+n:n.length>s+1?n.slice(0,s+1)+"."+n.slice(s+1):n+new Array(s-n.length+2).join("0")}const UC={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:Are,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>BC(e*100,t),r:BC,s:Ore,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function zC(e){return e}var qC=Array.prototype.map,HC=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Rre(e){var t=e.grouping===void 0||e.thousands===void 0?zC:_re(qC.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",s=e.decimal===void 0?".":e.decimal+"",i=e.numerals===void 0?zC:Tre(qC.call(e.numerals,String)),o=e.percent===void 0?"%":e.percent+"",l=e.minus===void 0?"−":e.minus+"",c=e.nan===void 0?"NaN":e.nan+"";function u(p){p=Zp(p);var h=p.fill,f=p.align,x=p.sign,g=p.symbol,y=p.zero,b=p.width,v=p.comma,k=p.precision,N=p.trim,j=p.type;j==="n"?(v=!0,j="g"):UC[j]||(k===void 0&&(k=12),N=!0,j="g"),(y||h==="0"&&f==="=")&&(y=!0,h="0",f="=");var w=g==="$"?r:g==="#"&&/[boxX]/.test(j)?"0"+j.toLowerCase():"",S=g==="$"?n:/[%p]/.test(j)?o:"",T=UC[j],C=/[defgprs%]/.test(j);k=k===void 0?6:/[gprs]/.test(j)?Math.max(1,Math.min(21,k)):Math.max(0,Math.min(20,k));function A(P){var E=w,_=S,I,D,M;if(j==="c")_=T(P)+_,P="";else{P=+P;var B=P<0||1/P<0;if(P=isNaN(P)?c:T(Math.abs(P),k),N&&(P=Ire(P)),B&&+P==0&&x!=="+"&&(B=!1),E=(B?x==="("?x:l:x==="-"||x==="("?"":x)+E,_=(j==="s"?HC[8+h4/3]:"")+_+(B&&x==="("?")":""),C){for(I=-1,D=P.length;++I<D;)if(M=P.charCodeAt(I),48>M||M>57){_=(M===46?s+P.slice(I+1):P.slice(I))+_,P=P.slice(0,I);break}}}v&&!y&&(P=t(P,1/0));var $=E.length+P.length+_.length,K=$<b?new Array(b-$+1).join(h):"";switch(v&&y&&(P=t(K+P,K.length?b-_.length:1/0),K=""),f){case"<":P=E+P+_+K;break;case"=":P=E+K+P+_;break;case"^":P=K.slice(0,$=K.length>>1)+E+P+_+K.slice($);break;default:P=K+E+P+_;break}return i(P)}return A.toString=function(){return p+""},A}function d(p,h){var f=u((p=Zp(p),p.type="f",p)),x=Math.max(-8,Math.min(8,Math.floor(Ru(h)/3)))*3,g=Math.pow(10,-x),y=HC[8+x/3];return function(b){return f(g*b)+y}}return{format:u,formatPrefix:d}}var Mf,fj,f4;Dre({thousands:",",grouping:[3],currency:["$",""]});function Dre(e){return Mf=Rre(e),fj=Mf.format,f4=Mf.formatPrefix,Mf}function Mre(e){return Math.max(0,-Ru(Math.abs(e)))}function Lre(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Ru(t)/3)))*3-Ru(Math.abs(e)))}function $re(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Ru(t)-Ru(e))+1}function m4(e,t,r,n){var s=nv(e,t,r),i;switch(n=Zp(n??",f"),n.type){case"s":{var o=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(i=Lre(s,o))&&(n.precision=i),f4(n,o)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(i=$re(s,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=i-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(i=Mre(s))&&(n.precision=i-(n.type==="%")*2);break}}return fj(n)}function pl(e){var t=e.domain;return e.ticks=function(r){var n=t();return ev(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var s=t();return m4(s[0],s[s.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),s=0,i=n.length-1,o=n[s],l=n[i],c,u,d=10;for(l<o&&(u=o,o=l,l=u,u=s,s=i,i=u);d-- >0;){if(u=tv(o,l,r),u===c)return n[s]=o,n[i]=l,t(n);if(u>0)o=Math.floor(o/u)*u,l=Math.ceil(l/u)*u;else if(u<0)o=Math.ceil(o*u)/u,l=Math.floor(l*u)/u;else break;c=u}return e},e}function ng(){var e=pj();return e.copy=function(){return $h(e,ng())},za.apply(e,arguments),pl(e)}function g4(e){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(e=Array.from(n,eg),r):e.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return g4(e).unknown(t)},e=arguments.length?Array.from(e,eg):[0,1],pl(r)}function x4(e,t){e=e.slice();var r=0,n=e.length-1,s=e[r],i=e[n],o;return i<s&&(o=r,r=n,n=o,o=s,s=i,i=o),e[r]=t.floor(s),e[n]=t.ceil(i),e}function WC(e){return Math.log(e)}function VC(e){return Math.exp(e)}function Fre(e){return-Math.log(-e)}function Bre(e){return-Math.exp(-e)}function Ure(e){return isFinite(e)?+("1e"+e):e<0?0:e}function zre(e){return e===10?Ure:e===Math.E?Math.exp:t=>Math.pow(e,t)}function qre(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function GC(e){return(t,r)=>-e(-t,r)}function mj(e){const t=e(WC,VC),r=t.domain;let n=10,s,i;function o(){return s=qre(n),i=zre(n),r()[0]<0?(s=GC(s),i=GC(i),e(Fre,Bre)):e(WC,VC),t}return t.base=function(l){return arguments.length?(n=+l,o()):n},t.domain=function(l){return arguments.length?(r(l),o()):r()},t.ticks=l=>{const c=r();let u=c[0],d=c[c.length-1];const p=d<u;p&&([u,d]=[d,u]);let h=s(u),f=s(d),x,g;const y=l==null?10:+l;let b=[];if(!(n%1)&&f-h<y){if(h=Math.floor(h),f=Math.ceil(f),u>0){for(;h<=f;++h)for(x=1;x<n;++x)if(g=h<0?x/i(-h):x*i(h),!(g<u)){if(g>d)break;b.push(g)}}else for(;h<=f;++h)for(x=n-1;x>=1;--x)if(g=h>0?x/i(-h):x*i(h),!(g<u)){if(g>d)break;b.push(g)}b.length*2<y&&(b=ev(u,d,y))}else b=ev(h,f,Math.min(f-h,y)).map(i);return p?b.reverse():b},t.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=Zp(c)).precision==null&&(c.trim=!0),c=fj(c)),l===1/0)return c;const u=Math.max(1,n*l/t.ticks().length);return d=>{let p=d/i(Math.round(s(d)));return p*n<n-.5&&(p*=n),p<=u?c(d):""}},t.nice=()=>r(x4(r(),{floor:l=>i(Math.floor(s(l))),ceil:l=>i(Math.ceil(s(l)))})),t}function y4(){const e=mj(Ox()).domain([1,10]);return e.copy=()=>$h(e,y4()).base(e.base()),za.apply(e,arguments),e}
6950function KC(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function YC(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function gj(e){var t=1,r=e(KC(t),YC(t));return r.constant=function(n){return arguments.length?e(KC(t=+n),YC(t)):t},pl(r)}function b4(){var e=gj(Ox());return e.copy=function(){return $h(e,b4()).constant(e.constant())},za.apply(e,arguments)}function JC(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function Hre(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function Wre(e){return e<0?-e*e:e*e}function xj(e){var t=e(Zs,Zs),r=1;function n(){return r===1?e(Zs,Zs):r===.5?e(Hre,Wre):e(JC(r),JC(1/r))}return t.exponent=function(s){return arguments.length?(r=+s,n()):r},pl(t)}function yj(){var e=xj(Ox());return e.copy=function(){return $h(e,yj()).exponent(e.exponent())},za.apply(e,arguments),e}function Vre(){return yj.apply(null,arguments).exponent(.5)}function XC(e){return Math.sign(e)*e*e}function Gre(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function v4(){var e=pj(),t=[0,1],r=!1,n;function s(i){var o=Gre(e(i));return isNaN(o)?n:r?Math.round(o):o}return s.invert=function(i){return e.invert(XC(i))},s.domain=function(i){return arguments.length?(e.domain(i),s):e.domain()},s.range=function(i){return arguments.length?(e.range((t=Array.from(i,eg)).map(XC)),s):t.slice()},s.rangeRound=function(i){return s.range(i).round(!0)},s.round=function(i){return arguments.length?(r=!!i,s):r},s.clamp=function(i){return arguments.length?(e.clamp(i),s):e.clamp()},s.unknown=function(i){return arguments.length?(n=i,s):n},s.copy=function(){return v4(e.domain(),t).round(r).clamp(e.clamp()).unknown(n)},za.apply(s,arguments),pl(s)}function w4(){var e=[],t=[],r=[],n;function s(){var o=0,l=Math.max(1,t.length);for(r=new Array(l-1);++o<l;)r[o-1]=Zne(e,o/l);return i}function i(o){return o==null||isNaN(o=+o)?n:t[Mh(r,o)]}return i.invertExtent=function(o){var l=t.indexOf(o);return l<0?[NaN,NaN]:[l>0?r[l-1]:e[0],l<r.length?r[l]:e[e.length-1]]},i.domain=function(o){if(!arguments.length)return e.slice();e=[];for(let l of o)l!=null&&!isNaN(l=+l)&&e.push(l);return e.sort(Zo),s()},i.range=function(o){return arguments.length?(t=Array.from(o),s()):t.slice()},i.unknown=function(o){return arguments.length?(n=o,i):n},i.quantiles=function(){return r.slice()},i.copy=function(){return w4().domain(e).range(t).unknown(n)},za.apply(i,arguments)}function j4(){var e=0,t=1,r=1,n=[.5],s=[0,1],i;function o(c){return c!=null&&c<=c?s[Mh(n,c,0,r)]:i}function l(){var c=-1;for(n=new Array(r);++c<r;)n[c]=((c+1)*t-(c-r)*e)/(r+1);return o}return o.domain=function(c){return arguments.length?([e,t]=c,e=+e,t=+t,l()):[e,t]},o.range=function(c){return arguments.length?(r=(s=Array.from(c)).length-1,l()):s.slice()},o.invertExtent=function(c){var u=s.indexOf(c);return u<0?[NaN,NaN]:u<1?[e,n[0]]:u>=r?[n[r-1],t]:[n[u-1],n[u]]},o.unknown=function(c){return arguments.length&&(i=c),o},o.thresholds=function(){return n.slice()},o.copy=function(){return j4().domain([e,t]).range(s).unknown(i)},za.apply(pl(o),arguments)}function N4(){var e=[.5],t=[0,1],r,n=1;function s(i){return i!=null&&i<=i?t[Mh(e,i,0,n)]:r}return s.domain=function(i){return arguments.length?(e=Array.from(i),n=Math.min(e.length,t.length-1),s):e.slice()},s.range=function(i){return arguments.length?(t=Array.from(i),n=Math.min(e.length,t.length-1),s):t.slice()},s.invertExtent=function(i){var o=t.indexOf(i);return[e[o-1],e[o]]},s.unknown=function(i){return arguments.length?(r=i,s):r},s.copy=function(){return N4().domain(e).range(t).unknown(r)},za.apply(s,arguments)}const hb=new Date,fb=new Date;function bs(e,t,r,n){function s(i){return e(i=arguments.length===0?new Date:new Date(+i)),i}return s.floor=i=>(e(i=new Date(+i)),i),s.ceil=i=>(e(i=new Date(i-1)),t(i,1),e(i),i),s.round=i=>{const o=s(i),l=s.ceil(i);return i-o<l-i?o:l},s.offset=(i,o)=>(t(i=new Date(+i),o==null?1:Math.floor(o)),i),s.range=(i,o,l)=>{const c=[];if(i=s.ceil(i),l=l==null?1:Math.floor(l),!(i<o)||!(l>0))return c;let u;do c.push(u=new Date(+i)),t(i,l),e(i);while(u<i&&i<o);return c},s.filter=i=>bs(o=>{if(o>=o)for(;e(o),!i(o);)o.setTime(o-1)},(o,l)=>{if(o>=o)if(l<0)for(;++l<=0;)for(;t(o,-1),!i(o););else for(;--l>=0;)for(;t(o,1),!i(o););}),r&&(s.count=(i,o)=>(hb.setTime(+i),fb.setTime(+o),e(hb),e(fb),Math.floor(r(hb,fb))),s.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?s.filter(n?o=>n(o)%i===0:o=>s.count(0,o)%i===0):s)),s}const rg=bs(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);rg.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?bs(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):rg);rg.range;const ro=1e3,Da=ro*60,so=Da*60,mo=so*24,bj=mo*7,ZC=mo*30,mb=mo*365,Hl=bs(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*ro)},(e,t)=>(t-e)/ro,e=>e.getUTCSeconds());Hl.range;const vj=bs(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ro)},(e,t)=>{e.setTime(+e+t*Da)},(e,t)=>(t-e)/Da,e=>e.getMinutes());vj.range;const wj=bs(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Da)},(e,t)=>(t-e)/Da,e=>e.getUTCMinutes());wj.range;const jj=bs(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ro-e.getMinutes()*Da)},(e,t)=>{e.setTime(+e+t*so)},(e,t)=>(t-e)/so,e=>e.getHours());jj.range;const Nj=bs(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*so)},(e,t)=>(t-e)/so,e=>e.getUTCHours());Nj.range;const Fh=bs(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Da)/mo,e=>e.getDate()-1);Fh.range;const Rx=bs(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/mo,e=>e.getUTCDate()-1);Rx.range;
vendor: 4,320 bytes, line 6950
6950const k4=bs(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/mo,e=>Math.floor(e/mo));k4.range;function Cc(e){return bs(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*Da)/bj)}const Dx=Cc(0),sg=Cc(1),Kre=Cc(2),Yre=Cc(3),Du=Cc(4),Jre=Cc(5),Xre=Cc(6);Dx.range;sg.range;Kre.range;Yre.range;Du.range;Jre.range;Xre.range;function Pc(e){return bs(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/bj)}const Mx=Pc(0),ag=Pc(1),Zre=Pc(2),Qre=Pc(3),Mu=Pc(4),ese=Pc(5),tse=Pc(6);Mx.range;ag.range;Zre.range;Qre.range;Mu.range;ese.range;tse.range;const kj=bs(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());kj.range;const Sj=bs(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());Sj.range;const go=bs(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());go.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:bs(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});go.range;const xo=bs(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());xo.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:bs(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});xo.range;function S4(e,t,r,n,s,i){const o=[[Hl,1,ro],[Hl,5,5*ro],[Hl,15,15*ro],[Hl,30,30*ro],[i,1,Da],[i,5,5*Da],[i,15,15*Da],[i,30,30*Da],[s,1,so],[s,3,3*so],[s,6,6*so],[s,12,12*so],[n,1,mo],[n,2,2*mo],[r,1,bj],[t,1,ZC],[t,3,3*ZC],[e,1,mb]];function l(u,d,p){const h=d<u;h&&([u,d]=[d,u]);const f=p&&typeof p.range=="function"?p:c(u,d,p),x=f?f.range(u,+d+1):[];return h?x.reverse():x}function c(u,d,p){const h=Math.abs(d-u)/p,f=oj(([,,y])=>y).right(o,h);if(f===o.length)return e.every(nv(u/mb,d/mb,p));if(f===0)return rg.every(Math.max(nv(u,d,p),1));const[x,g]=o[h/o[f-1][2]<o[f][2]/h?f-1:f];return x.every(g)}return[l,c]}const[nse,rse]=S4(xo,Sj,Mx,k4,Nj,wj),[sse,ase]=S4(go,kj,Dx,Fh,jj,vj);function gb(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function xb(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function Hd(e,t,r){return{y:e,m:t,d:r,H:0,M:0,S:0,L:0}}function ise(e){var t=e.dateTime,r=e.date,n=e.time,s=e.periods,i=e.days,o=e.shortDays,l=e.months,c=e.shortMonths,u=Wd(s),d=Vd(s),p=Wd(i),h=Vd(i),f=Wd(o),x=Vd(o),g=Wd(l),y=Vd(l),b=Wd(c),v=Vd(c),k={a:B,A:$,b:K,B:R,c:null,d:sP,e:sP,f:_se,g:Fse,G:Use,H:Cse,I:Pse,j:Ase,L:C4,m:Tse,M:Ese,p:Y,q:Z,Q:oP,s:lP,S:Ise,u:Ose,U:Rse,V:Dse,w:Mse,W:Lse,x:null,X:null,y:$se,Y:Bse,Z:zse,"%":iP},N={a:O,A:ne,b:oe,B:he,c:null,d:aP,e:aP,f:Vse,g:nae,G:sae,H:qse,I:Hse,j:Wse,L:A4,m:Gse,M:Kse,p:ae,q:ve,Q:oP,s:lP,S:Yse,u:Jse,U:Xse,V:Zse,w:Qse,W:eae,x:null,X:null,y:tae,Y:rae,Z:aae,"%":iP},j={a:A,A:P,b:E,B:_,c:I,d:nP,e:nP,f:jse,g:tP,G:eP,H:rP,I:rP,j:yse,L:wse,m:xse,M:bse,p:C,q:gse,Q:kse,s:Sse,S:vse,u:dse,U:pse,V:hse,w:use,W:fse,x:D,X:M,y:tP,Y:eP,Z:mse,"%":Nse};k.x=w(r,k),k.X=w(n,k),k.c=w(t,k),N.x=w(r,N),N.X=w(n,N),N.c=w(t,N);function w(re,se){return function(le){var te=[],We=-1,Me=0,Te=re.length,Ee,st,xt;for(le instanceof Date||(le=new Date(+le));++We<Te;)re.charCodeAt(We)===37&&(te.push(re.slice(Me,We)),(st=QC[Ee=re.charAt(++We)])!=null?Ee=re.charAt(++We):st=Ee==="e"?" ":"0",(xt=se[Ee])&&(Ee=xt(le,st)),te.push(Ee),Me=We+1);return te.push(re.slice(Me,We)),te.join("")}}function S(re,se){return function(le){var te=Hd(1900,void 0,1),We=T(te,re,le+="",0),Me,Te;if(We!=le.length)return null;if("Q"in te)return new Date(te.Q);if("s"in te)return new Date(te.s*1e3+("L"in te?te.L:0));
vendor: 7,303 bytes, line 6950
6950if(se&&!("Z"in te)&&(te.Z=0),"p"in te&&(te.H=te.H%12+te.p*12),te.m===void 0&&(te.m="q"in te?te.q:0),"V"in te){if(te.V<1||te.V>53)return null;"w"in te||(te.w=1),"Z"in te?(Me=xb(Hd(te.y,0,1)),Te=Me.getUTCDay(),Me=Te>4||Te===0?ag.ceil(Me):ag(Me),Me=Rx.offset(Me,(te.V-1)*7),te.y=Me.getUTCFullYear(),te.m=Me.getUTCMonth(),te.d=Me.getUTCDate()+(te.w+6)%7):(Me=gb(Hd(te.y,0,1)),Te=Me.getDay(),Me=Te>4||Te===0?sg.ceil(Me):sg(Me),Me=Fh.offset(Me,(te.V-1)*7),te.y=Me.getFullYear(),te.m=Me.getMonth(),te.d=Me.getDate()+(te.w+6)%7)}else("W"in te||"U"in te)&&("w"in te||(te.w="u"in te?te.u%7:"W"in te?1:0),Te="Z"in te?xb(Hd(te.y,0,1)).getUTCDay():gb(Hd(te.y,0,1)).getDay(),te.m=0,te.d="W"in te?(te.w+6)%7+te.W*7-(Te+5)%7:te.w+te.U*7-(Te+6)%7);return"Z"in te?(te.H+=te.Z/100|0,te.M+=te.Z%100,xb(te)):gb(te)}}function T(re,se,le,te){for(var We=0,Me=se.length,Te=le.length,Ee,st;We<Me;){if(te>=Te)return-1;if(Ee=se.charCodeAt(We++),Ee===37){if(Ee=se.charAt(We++),st=j[Ee in QC?se.charAt(We++):Ee],!st||(te=st(re,le,te))<0)return-1}else if(Ee!=le.charCodeAt(te++))return-1}return te}function C(re,se,le){var te=u.exec(se.slice(le));return te?(re.p=d.get(te[0].toLowerCase()),le+te[0].length):-1}function A(re,se,le){var te=f.exec(se.slice(le));return te?(re.w=x.get(te[0].toLowerCase()),le+te[0].length):-1}function P(re,se,le){var te=p.exec(se.slice(le));return te?(re.w=h.get(te[0].toLowerCase()),le+te[0].length):-1}function E(re,se,le){var te=b.exec(se.slice(le));return te?(re.m=v.get(te[0].toLowerCase()),le+te[0].length):-1}function _(re,se,le){var te=g.exec(se.slice(le));return te?(re.m=y.get(te[0].toLowerCase()),le+te[0].length):-1}function I(re,se,le){return T(re,t,se,le)}function D(re,se,le){return T(re,r,se,le)}function M(re,se,le){return T(re,n,se,le)}function B(re){return o[re.getDay()]}function $(re){return i[re.getDay()]}function K(re){return c[re.getMonth()]}function R(re){return l[re.getMonth()]}function Y(re){return s[+(re.getHours()>=12)]}function Z(re){return 1+~~(re.getMonth()/3)}function O(re){return o[re.getUTCDay()]}function ne(re){return i[re.getUTCDay()]}function oe(re){return c[re.getUTCMonth()]}function he(re){return l[re.getUTCMonth()]}function ae(re){return s[+(re.getUTCHours()>=12)]}function ve(re){return 1+~~(re.getUTCMonth()/3)}return{format:function(re){var se=w(re+="",k);return se.toString=function(){return re},se},parse:function(re){var se=S(re+="",!1);return se.toString=function(){return re},se},utcFormat:function(re){var se=w(re+="",N);return se.toString=function(){return re},se},utcParse:function(re){var se=S(re+="",!0);return se.toString=function(){return re},se}}}var QC={"-":"",_:" ",0:"0"},Cs=/^\s*\d+/,ose=/^%/,lse=/[\\^$*+?|[\]().{}]/g;function Jn(e,t,r){var n=e<0?"-":"",s=(n?-e:e)+"",i=s.length;return n+(i<r?new Array(r-i+1).join(t)+s:s)}function cse(e){return e.replace(lse,"\\$&")}function Wd(e){return new RegExp("^(?:"+e.map(cse).join("|")+")","i")}function Vd(e){return new Map(e.map((t,r)=>[t.toLowerCase(),r]))}function use(e,t,r){var n=Cs.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function dse(e,t,r){var n=Cs.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function pse(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function hse(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function fse(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function eP(e,t,r){var n=Cs.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function tP(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function mse(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function gse(e,t,r){var n=Cs.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function xse(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function nP(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function yse(e,t,r){var n=Cs.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function rP(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function bse(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function vse(e,t,r){var n=Cs.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function wse(e,t,r){var n=Cs.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function jse(e,t,r){var n=Cs.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function Nse(e,t,r){var n=ose.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function kse(e,t,r){var n=Cs.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function Sse(e,t,r){var n=Cs.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function sP(e,t){return Jn(e.getDate(),t,2)}function Cse(e,t){return Jn(e.getHours(),t,2)}function Pse(e,t){return Jn(e.getHours()%12||12,t,2)}function Ase(e,t){return Jn(1+Fh.count(go(e),e),t,3)}function C4(e,t){return Jn(e.getMilliseconds(),t,3)}function _se(e,t){return C4(e,t)+"000"}function Tse(e,t){return Jn(e.getMonth()+1,t,2)}function Ese(e,t){return Jn(e.getMinutes(),t,2)}function Ise(e,t){return Jn(e.getSeconds(),t,2)}function Ose(e){var t=e.getDay();return t===0?7:t}function Rse(e,t){return Jn(Dx.count(go(e)-1,e),t,2)}function P4(e){var t=e.getDay();return t>=4||t===0?Du(e):Du.ceil(e)}function Dse(e,t){return e=P4(e),Jn(Du.count(go(e),e)+(go(e).getDay()===4),t,2)}function Mse(e){return e.getDay()}function Lse(e,t){return Jn(sg.count(go(e)-1,e),t,2)}function $se(e,t){return Jn(e.getFullYear()%100,t,2)}function Fse(e,t){return e=P4(e),Jn(e.getFullYear()%100,t,2)}function Bse(e,t){return Jn(e.getFullYear()%1e4,t,4)}function Use(e,t){var r=e.getDay();return e=r>=4||r===0?Du(e):Du.ceil(e),Jn(e.getFullYear()%1e4,t,4)}function zse(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Jn(t/60|0,"0",2)+Jn(t%60,"0",2)}function aP(e,t){return Jn(e.getUTCDate(),t,2)}function qse(e,t){return Jn(e.getUTCHours(),t,2)}function Hse(e,t){return Jn(e.getUTCHours()%12||12,t,2)}function Wse(e,t){return Jn(1+Rx.count(xo(e),e),t,3)}function A4(e,t){return Jn(e.getUTCMilliseconds(),t,3)}function Vse(e,t){return A4(e,t)+"000"}function Gse(e,t){return Jn(e.getUTCMonth()+1,t,2)}function Kse(e,t){return Jn(e.getUTCMinutes(),t,2)}function Yse(e,t){return Jn(e.getUTCSeconds(),t,2)}function Jse(e){var t=e.getUTCDay();return t===0?7:t}function Xse(e,t){return Jn(Mx.count(xo(e)-1,e),t,2)}function _4(e){var t=e.getUTCDay();return t>=4||t===0?Mu(e):Mu.ceil(e)}function Zse(e,t){return e=_4(e),Jn(Mu.count(xo(e),e)+(xo(e).getUTCDay()===4),t,2)}function Qse(e){return e.getUTCDay()}function eae(e,t){return Jn(ag.count(xo(e)-1,e),t,2)}function tae(e,t){return Jn(e.getUTCFullYear()%100,t,2)}function nae(e,t){return e=_4(e),Jn(e.getUTCFullYear()%100,t,2)}function rae(e,t){return Jn(e.getUTCFullYear()%1e4,t,4)}function sae(e,t){var r=e.getUTCDay();return e=r>=4||r===0?Mu(e):Mu.ceil(e),Jn(e.getUTCFullYear()%1e4,t,4)}function aae(){return"+0000"}function iP(){return"%"}function oP(e){return+e}function lP(e){return Math.floor(+e/1e3)}var Kc,T4,E4;iae({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
6950ay","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function iae(e){return Kc=ise(e),T4=Kc.format,Kc.parse,E4=Kc.utcFormat,Kc.utcParse,Kc}function oae(e){return new Date(e)}function lae(e){return e instanceof Date?+e:+new Date(+e)}function Cj(e,t,r,n,s,i,o,l,c,u){var d=pj(),p=d.invert,h=d.domain,f=u(".%L"),x=u(":%S"),g=u("%I:%M"),y=u("%I %p"),b=u("%a %d"),v=u("%b %d"),k=u("%B"),N=u("%Y");function j(w){return(c(w)<w?f:l(w)<w?x:o(w)<w?g:i(w)<w?y:n(w)<w?s(w)<w?b:v:r(w)<w?k:N)(w)}return d.invert=function(w){return new Date(p(w))},d.domain=function(w){return arguments.length?h(Array.from(w,lae)):h().map(oae)},d.ticks=function(w){var S=h();return e(S[0],S[S.length-1],w??10)},d.tickFormat=function(w,S){return S==null?j:u(S)},d.nice=function(w){var S=h();return(!w||typeof w.range!="function")&&(w=t(S[0],S[S.length-1],w??10)),w?h(x4(S,w)):d},d.copy=function(){return $h(d,Cj(e,t,r,n,s,i,o,l,c,u))},d}function cae(){return za.apply(Cj(sse,ase,go,kj,Dx,Fh,jj,vj,Hl,T4).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function uae(){return za.apply(Cj(nse,rse,xo,Sj,Mx,Rx,Nj,wj,Hl,E4).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function Lx(){var e=0,t=1,r,n,s,i,o=Zs,l=!1,c;function u(p){return p==null||isNaN(p=+p)?c:o(s===0?.5:(p=(i(p)-r)*s,l?Math.max(0,Math.min(1,p)):p))}u.domain=function(p){return arguments.length?([e,t]=p,r=i(e=+e),n=i(t=+t),s=r===n?0:1/(n-r),u):[e,t]},u.clamp=function(p){return arguments.length?(l=!!p,u):l},u.interpolator=function(p){return arguments.length?(o=p,u):o};function d(p){return function(h){var f,x;return arguments.length?([f,x]=h,o=p(f,x),u):[o(0),o(1)]}}return u.range=d(pd),u.rangeRound=d(dj),u.unknown=function(p){return arguments.length?(c=p,u):c},function(p){return i=p,r=p(e),n=p(t),s=r===n?0:1/(n-r),u}}function hl(e,t){return t.domain(e.domain()).interpolator(e.interpolator()).clamp(e.clamp()).unknown(e.unknown())}function I4(){var e=pl(Lx()(Zs));return e.copy=function(){return hl(e,I4())},vo.apply(e,arguments)}function O4(){var e=mj(Lx()).domain([1,10]);return e.copy=function(){return hl(e,O4()).base(e.base())},vo.apply(e,arguments)}function R4(){var e=gj(Lx());return e.copy=function(){return hl(e,R4()).constant(e.constant())},vo.apply(e,arguments)}function Pj(){var e=xj(Lx());return e.copy=function(){return hl(e,Pj()).exponent(e.exponent())},vo.apply(e,arguments)}function dae(){return Pj.apply(null,arguments).exponent(.5)}function D4(){var e=[],t=Zs;function r(n){if(n!=null&&!isNaN(n=+n))return t((Mh(e,n,1)-1)/(e.length-1))}return r.domain=function(n){if(!arguments.length)return e.slice();e=[];for(let s of n)s!=null&&!isNaN(s=+s)&&e.push(s);return e.sort(Zo),r},r.interpolator=function(n){return arguments.length?(t=n,r):t},r.range=function(){return e.map((n,s)=>t(s/(e.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(s,i)=>Xne(e,i/n))},r.copy=function(){return D4(t).domain(e)},vo.apply(r,arguments)}function $x(){var e=0,t=.5,r=1,n=1,s,i,o,l,c,u=Zs,d,p=!1,h;function f(g){return isNaN(g=+g)?h:(g=.5+((g=+d(g))-i)*(n*g<n*i?l:c),u(p?Math.max(0,Math.min(1,g)):g))}f.domain=function(g){return arguments.length?([e,t,r]=g,s=d(e=+e),i=d(t=+t),o=d(r=+r),l=s===i?0:.5/(i-s),c=i===o?0:.5/(o-i),n=i<s?-1:1,f):[e,t,r]},f.clamp=function(g){return arguments.length?(p=!!g,f):p},f.interpolator=function(g){return arguments.length?(u=g,f):u};function x(g){return function(y){var b,v,k;return arguments.length?([b,v,k]=y,u=Nre(g,[b,v,k]),f):[u(0),u(.5),u(1)]}}return f.range=x(pd),f.rangeRound=x(dj),f.unknown=function(g){return arguments.length?(h=g,f):h},function(g){return d=g,s=g(e),i=g(t),o=g(r),l=s===i?0:.5/(i-s),c=i===o?0:.5/(o-i),n=i<s?-1:1,f}}function M4(){var e=pl($x()(Zs));return e.copy=function(){return hl(e,M4())},vo.apply(e,arguments)}function L4(){var e=mj($x()).domain([.1,1,10]);return e.copy=function(){return hl(e,L4()).base(e.base())},vo.apply(e,arguments)}function $4(){var e=gj($x());return e.copy=function(){return hl(e,$4()).constant(e.constant())},vo.apply(e,arguments)}function Aj(){var e=xj($x());return e.copy=function(){return hl(e,Aj()).exponent(e.exponent())},vo.apply(e,arguments)}function pae(){return Aj.apply(null,arguments).exponent(.5)}const cP=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:Kp,scaleDiverging:M4,scaleDivergingLog:L4,scaleDivergingPow:Aj,scaleDivergingSqrt:pae,scaleDivergingSymlog:$4,scaleIdentity:g4,scaleImplicit:rv,scaleLinear:ng,scaleLog:y4,scaleOrdinal:lj,scalePoint:Np,scalePow:yj,scaleQuantile:w4,scaleQuantize:j4,scaleRadial:v4,scaleSequential:I4,scaleSequentialLog:O4,scaleSequentialPow:Pj,scaleSequentialQuantile:D4,scaleSequentialSqrt:dae,scaleSequentialSymlog:R4,scaleSqrt:Vre,scaleSymlog:b4,scaleThreshold:N4,scaleTime:cae,scaleUtc:uae,tickFormat:m4},Symbol.toStringTag,{value:"Module"}));var hae=G_;function fae(e,t,r){for(var n=-1,s=e.length;++n<s;){var i=e[n],o=t(i);if(o!=null&&(l===void 0?o===o&&!hae(o):r(o,l)))var l=o,c=i}return c}var Fx=fae;function mae(e,t){return e>t}
vendor: 63,254 bytes, lines 6950-6977
6950var F4=mae,gae=Fx,xae=F4,yae=vw;function bae(e){return e&&e.length?gae(e,yae,xae):void 0}var vae=bae;const Go=zs(vae);function wae(e,t){return e<t}var B4=wae,jae=Fx,Nae=B4,kae=vw;function Sae(e){return e&&e.length?jae(e,kae,Nae):void 0}var Cae=Sae;const Bx=zs(Cae);var Pae=K_,Aae=jc,_ae=JO,Tae=ww;function Eae(e,t){var r=Tae(e)?Pae:_ae;return r(e,Aae(t))}var Iae=Eae,Oae=Y_,Rae=Iae;function Dae(e,t){return Oae(Rae(e,t),1)}var Mae=Dae;const Lae=zs(Mae);var hd=1e9,$ae={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},Tj,Fr=!0,$a="[DecimalError] ",nc=$a+"Invalid argument: ",_j=$a+"Exponent out of range: ",fd=Math.floor,Ml=Math.pow,Fae=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,xa,js=1e7,Mr=7,U4=9007199254740991,ig=fd(U4/Mr),ft={};ft.absoluteValue=ft.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};ft.comparedTo=ft.cmp=function(e){var t,r,n,s,i=this;if(e=new i.constructor(e),i.s!==e.s)return i.s||-e.s;if(i.e!==e.e)return i.e>e.e^i.s<0?1:-1;for(n=i.d.length,s=e.d.length,t=0,r=n<s?n:s;t<r;++t)if(i.d[t]!==e.d[t])return i.d[t]>e.d[t]^i.s<0?1:-1;return n===s?0:n>s^i.s<0?1:-1};ft.decimalPlaces=ft.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*Mr;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};ft.dividedBy=ft.div=function(e){return po(this,new this.constructor(e))};ft.dividedToIntegerBy=ft.idiv=function(e){var t=this,r=t.constructor;return yr(po(t,new r(e),0,1),r.precision)};ft.equals=ft.eq=function(e){return!this.cmp(e)};ft.exponent=function(){return ls(this)};ft.greaterThan=ft.gt=function(e){return this.cmp(e)>0};ft.greaterThanOrEqualTo=ft.gte=function(e){return this.cmp(e)>=0};ft.isInteger=ft.isint=function(){return this.e>this.d.length-2};ft.isNegative=ft.isneg=function(){return this.s<0};ft.isPositive=ft.ispos=function(){return this.s>0};ft.isZero=function(){return this.s===0};ft.lessThan=ft.lt=function(e){return this.cmp(e)<0};ft.lessThanOrEqualTo=ft.lte=function(e){return this.cmp(e)<1};ft.logarithm=ft.log=function(e){var t,r=this,n=r.constructor,s=n.precision,i=s+5;if(e===void 0)e=new n(10);else if(e=new n(e),e.s<1||e.eq(xa))throw Error($a+"NaN");if(r.s<1)throw Error($a+(r.s?"NaN":"-Infinity"));return r.eq(xa)?new n(0):(Fr=!1,t=po(Qp(r,i),Qp(e,i),i),Fr=!0,yr(t,s))};ft.minus=ft.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?H4(t,e):z4(t,(e.s=-e.s,e))};ft.modulo=ft.mod=function(e){var t,r=this,n=r.constructor,s=n.precision;if(e=new n(e),!e.s)throw Error($a+"NaN");return r.s?(Fr=!1,t=po(r,e,0,1).times(e),Fr=!0,r.minus(t)):yr(new n(r),s)};ft.naturalExponential=ft.exp=function(){return q4(this)};ft.naturalLogarithm=ft.ln=function(){return Qp(this)};ft.negated=ft.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};ft.plus=ft.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?z4(t,e):H4(t,(e.s=-e.s,e))};ft.precision=ft.sd=function(e){var t,r,n,s=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(nc+e);if(t=ls(s)+1,n=s.d.length-1,r=n*Mr+1,n=s.d[n],n){for(;n%10==0;n/=10)r--;for(n=s.d[0];n>=10;n/=10)r++}return e&&t>r?t:r};ft.squareRoot=ft.sqrt=function(){var e,t,r,n,s,i,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error($a+"NaN")}for(e=ls(l),Fr=!1,s=Math.sqrt(+l),s==0||s==1/0?(t=Ci(l.d),(t.length+e)%2==0&&(t+="0"),s=Math.sqrt(t),e=fd((e+1)/2)-(e<0||e%2),s==1/0?t="5e"+e:(t=s.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new c(t)):n=new c(s.toString()),r=c.precision,s=o=r+3;;)if(i=n,n=i.plus(po(l,i,o+2)).times(.5),Ci(i.d).slice(0,o)===(t=Ci(n.d)).slice(0,o)){if(t=t.slice(o-3,o+1),s==o&&t=="4999"){if(yr(i,r+1,0),i.times(i).eq(l)){n=i;break}}else if(t!="9999")break;o+=4}return Fr=!0,yr(n,r)};ft.times=ft.mul=function(e){var t,r,n,s,i,o,l,c,u,d=this,p=d.constructor,h=d.d,f=(e=new p(e)).d;if(!d.s||!e.s)return new p(0);for(e.s*=d.s,r=d.e+e.e,c=h.length,u=f.length,c<u&&(i=h,h=f,f=i,o=c,c=u,u=o),i=[],o=c+u,n=o;n--;)i.push(0);for(n=u;--n>=0;){for(t=0,s=c+n;s>n;)l=i[s]+f[n]*h[s-n-1]+t,i[s--]=l%js|0,t=l/js|0;i[s]=(i[s]+t)%js|0}for(;!i[--o];)i.pop();return t?++r:i.shift(),e.d=i,e.e=r,Fr?yr(e,p.precision):e};ft.toDecimalPlaces=ft.todp=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(Mi(e,0,hd),t===void 0?t=n.rounding:Mi(t,0,8),yr(r,e+ls(r)+1,t))};ft.toExponential=function(e,t){var r,n=this,s=n.constructor;return e===void 0?r=yc(n,!0):(Mi(e,0,hd),t===void 0?t=s.rounding:Mi(t,0,8),n=yr(new s(n),e+1,t),r=yc(n,!0,e+1)),r};ft.toFixed=function(e,t){var r,n,s=this,i=s.constructor;return e===void 0?yc(s):(Mi(e,0,hd),t===void 0?t=i.rounding:Mi(t,0,8),n=yr(new i(s),e+ls(s)+1,t),r=yc(n.abs(),!1,e+ls(n)+1),s.isneg()&&!s.isZero()?"-"+r:r)};ft.toInteger=ft.toint=function(){var e=this,t=e.constructor;return yr(new t(e),ls(e)+1,t.rounding)};ft.toNumber=function(){return+this};ft.toPower=ft.pow=function(e){var t,r,n,s,i,o,l=this,c=l.constructor,u=12,d=+(e=new c(e));if(!e.s)return new c(xa);if(l=new c(l),!l.s){if(e.s<1)throw Error($a+"Infinity");return l}if(l.eq(xa))return l;if(n=c.precision,e.eq(xa))return yr(l,n);if(t=e.e,r=e.d.length-1,o=t>=r,i=l.s,o){if((r=d<0?-d:d)<=U4){for(s=new c(xa),t=Math.ceil(n/Mr+4),Fr=!1;r%2&&(s=s.times(l),dP(s.d,t)),r=fd(r/2),r!==0;)l=l.times(l),dP(l.d,t);return Fr=!0,e.s<0?new c(xa).div(s):yr(s,n)}}else if(i<0)throw Error($a+"NaN");return i=i<0&&e.d[Math.max(t,r)]&1?-1:1,l.s=1,Fr=!1,s=e.times(Qp(l,n+u)),Fr=!0,s=q4(s),s.s=i,s};ft.toPrecision=function(e,t){var r,n,s=this,i=s.constructor;return e===void 0?(r=ls(s),n=yc(s,r<=i.toExpNeg||r>=i.toExpPos)):(Mi(e,1,hd),t===void 0?t=i.rounding:Mi(t,0,8),s=yr(new i(s),e,t),r=ls(s),n=yc(s,e<=r||r<=i.toExpNeg,e)),n};ft.toSignificantDigits=ft.tosd=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(Mi(e,1,hd),t===void 0?t=n.rounding:Mi(t,0,8)),yr(new n(r),e,t)};ft.toString=ft.valueOf=ft.val=ft.toJSON=ft[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=ls(e),r=e.constructor;return yc(e,t<=r.toExpNeg||t>=r.toExpPos)};function z4(e,t){var r,n,s,i,o,l,c,u,d=e.constructor,p=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),Fr?yr(t,p):t;if(c=e.d,u=t.d,o=e.e,s=t.e,c=c.slice(),i=o-s,i){for(i<0?(n=c,i=-i,l=u.length):(n=u,s=o,l=c.length),o=Math.ceil(p/Mr),l=o>l?o+1:l+1,i>l&&(i=l,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(l=c.length,i=u.length,l-i<0&&(i=l,n=u,u=c,c=n),r=0;i;)r=(c[--i]=c[i]+u[i]+r)/js|0,c[i]%=js;for(r&&(c.unshift(r),++s),l=c.length;c[--l]==0;)c.pop();return t.d=c,t.e=s,Fr?yr(t,p):t}function Mi(e,t,r){if(e!==~~e||e<t||e>r)throw Error(nc+e)}function Ci(e){var t,r,n,s=e.length-1,i="",o=e[0];if(s>0){for(i+=o,t=1;t<s;t++)n=e[t]+"",r=Mr-n.length,r&&(i+=Bo(r)),i+=n;o=e[t],n=o+"",r=Mr-n.length,r&&(i+=Bo(r))}else if(o===0)return"0";for(;o%10===0;)o/=10;return i+o}var po=function(){function e(n,s){var i,o=0,l=n.length;for(n=n.slice();l--;)i=n[l]*s+o,n[l]=i%js|0,o=i/js|0;return o&&n.unshift(o),n}function t(n,s,i,o){var l,c;if(i!=o)c=i>o?1:-1;else for(l=c=0;l<i;l++)if(n[l]!=s[l]){c=n[l]>s[l]?1:-1;break}return c}function r(n,s,i){for(var o=0;i--;)n[i]-=o,o=n[i]<s[i]?1:0,n[i]=o*js+n[i]-s[i];for(;!n[0]&&n.length>1;)n.shift()}return function(n,s,i,o){var l,c,u,d,p,h,f,x,g,y,b,v,k,N,j,w,S,T,C=n.constructor,A=n.s==s.s?1:-1,P=n.d,E=s.d;if(!n.s)return new C(n);if(!s.s)throw Error($a+"Division by zero");for(c=n.e-s.e,S=E.length,j=P.length,f=new C(A),x=f.d=[],u=0;E[u]==(P[u]||0);)++u;if(E[u]>(P[u]||0)&&--c,i==null?v=i=C.precision:o?v=i+(ls(n)-ls(s))+1:v=i,v<0)return new C(0);if(v=v/Mr+2|0,u=0,S==1)for(d=0,E=E[0],v++;(u<j||d)&&v--;u++)k=d*js+(P[u]||0),x[u]=k/E|0,d=k%E|0;else{for(d=js/(E[0]+1)|0,d>1&&(E=e(E,d),P=e(P,d),S=E.length,j=P.length),N=S,g=P.slice(0,S),y=g.length;y<S;)g[y++]=0;T=E.slice(),T.unshift(0),w=E[0],E[1]>=js/2&&++w;do d=0,l=t(E,g,S,y),l<0?(b=g[0],S!=y&&(b=b*js+(g[1]||0)),d=b/w|0,d>1?(d>=js&&(d=js-1),p=e(E,d),h=p.length,y=g.length,l=t(p,g,h,y),l==1&&(d--,r(p,S<h?T:E,h))):(d==0&&(l=d=1),p=E.slice()),h=p.length,h<y&&p.unshift(0),r(g,p,y),l==-1&&(y=g.length,l=t(E,g,S,y),l<1&&(d++,r(g,S<y?T:E,y))),y=g.length):l===0&&(d++,g=[0]),x[u++]=d,l&&g[0]?g[y++]=P[N]||0:(g=[P[N]],y=1);while((N++<j||g[0]!==void 0)&&v--)}return x[0]||x.shift(),f.e=c,yr(f,o?i+ls(f)+1:i)}}();function q4(e,t){var r,n,s,i,o,l,c=0,u=0,d=e.constructor,p=d.precision;if(ls(e)>16)throw Error(_j+ls(e));if(!e.s)return new d(xa);for(t==null?(Fr=!1,l=p):l=t,o=new d(.03125);e.abs().gte(.1);)e=e.times(o),u+=5;for(n=Math.log(Ml(2,u))/Math.LN10*2+5|0,l+=n,r=s=i=new d(xa),d.precision=l;;){if(s=yr(s.times(e),l),r=r.times(++c),o=i.plus(po(s,r,l)),Ci(o.d).slice(0,l)===Ci(i.d).slice(0,l)){for(;u--;)i=yr(i.times(i),l);return d.precision=p,t==null?(Fr=!0,yr(i,p)):i}i=o}}function ls(e){for(var t=e.e*Mr,r=e.d[0];r>=10;r/=10)t++;return t}function yb(e,t,r){if(t>e.LN10.sd())throw Fr=!0,r&&(e.precision=r),Error($a+"LN10 precision limit exceeded");return yr(new e(e.LN10),t)}function Bo(e){for(var t="";e--;)t+="0";return t}function Qp(e,t){var r,n,s,i,o,l,c,u,d,p=1,h=10,f=e,x=f.d,g=f.constructor,y=g.precision;if(f.s<1)throw Error($a+(f.s?"NaN":"-Infinity"));if(f.eq(xa))return new g(0);if(t==null?(Fr=!1,u=y):u=t,f.eq(10))return t==null&&(Fr=!0),yb(g,u);if(u+=h,g.precision=u,r=Ci(x),n=r.charAt(0),i=ls(f),Math.abs(i)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)f=f.times(e),r=Ci(f.d),n=r.charAt(0),p++;i=ls(f),n>1?(f=new g("0."+r),i++):f=new g(n+"."+r.slice(1))}else return c=yb(g,u+2,y).times(i+""),f=Qp(new g(n+"."+r.slice(1)),u-h).plus(c),g.precision=y,t==null?(Fr=!0,yr(f,y)):f;for(l=o=f=po(f.minus(xa),f.plus(xa),u),d=yr(f.times(f),u),s=3;;){if(o=yr(o.times(d),u),c=l.plus(po(o,new g(s),u)),Ci(c.d).slice(0,u)===Ci(l.d).slice(0,u))return l=l.times(2),i!==0&&(l=l.plus(yb(g,u+2,y).times(i+""))),l=po(l,new g(p),u),g.precision=y,t==null?(Fr=!0,yr(l,y)):l;l=c,s+=2}}function uP(e,t){var r,n,s;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(s=t.length;t.charCodeAt(s-1)===48;)--s;if(t=t.slice(n,s),t){if(s-=n,r=r-n-1,e.e=fd(r/Mr),e.d=[],n=(r+1)%Mr,r<0&&(n+=Mr),n<s){for(n&&e.d.push(+t.slice(0,n)),s-=Mr;n<s;)e.d.push(+t.slice(n,n+=Mr));t=t.slice(n),n=Mr-t.length}else n-=s;for(;n--;)t+="0";if(e.d.push(+t),Fr&&(e.e>ig||e.e<-ig))throw Error(_j+r)}else e.s=0,e.e=0,e.d=[0];return e}function yr(e,t,r){var n,s,i,o,l,c,u,d,p=e.d;for(o=1,i=p[0];i>=10;i/=10)o++;if(n=t-o,n<0)n+=Mr,s=t,u=p[d=0];else{if(d=Math.ceil((n+1)/Mr),i=p.length,d>=i)return e;for(u=i=p[d],o=1;i>=10;i/=10)o++;n%=Mr,s=n-Mr+o}if(r!==void 0&&(i=Ml(10,o-s-1),l=u/i%10|0,c=t<0||p[d+1]!==void 0||u%i,c=r<4?(l||c)&&(r==0||r==(e.s<0?3:2)):l>5||l==5&&(r==4||c||r==6&&(n>0?s>0?u/Ml(10,o-s):0:p[d-1])%10&1||r==(e.s<0?8:7))),t<1||!p[0])return c?(i=ls(e),p.length=1,t=t-i-1,p[0]=Ml(10,(Mr-t%Mr)%Mr),e.e=fd(-t/Mr)||0):(p.length=1,p[0]=e.e=e.s=0),e;if(n==0?(p.length=d,i=1,d--):(p.length=d+1,i=Ml(10,Mr-n),p[d]=s>0?(u/Ml(10,o-s)%Ml(10,s)|0)*i:0),c)for(;;)if(d==0){(p[0]+=i)==js&&(p[0]=1,++e.e);break}else{if(p[d]+=i,p[d]!=js)break;p[d--]=0,i=1}for(n=p.length;p[--n]===0;)p.pop();if(Fr&&(e.e>ig||e.e<-ig))throw Error(_j+ls(e));return e}function H4(e,t){var r,n,s,i,o,l,c,u,d,p,h=e.constructor,f=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),Fr?yr(t,f):t;if(c=e.d,p=t.d,n=t.e,u=e.e,c=c.slice(),o=u-n,o){for(d=o<0,d?(r=c,o=-o,l=p.length):(r=p,n=u,l=c.length),s=Math.max(Math.ceil(f/Mr),l)+2,o>s&&(o=s,r.length=1),r.reverse(),s=o;s--;)r.push(0);r.reverse()}else{for(s=c.length,l=p.length,d=s<l,d&&(l=s),s=0;s<l;s++)if(c[s]!=p[s]){d=c[s]<p[s];break}o=0}for(d&&(r=c,c=p,p=r,t.s=-t.s),l=c.length,s=p.length-l;s>0;--s)c[l++]=0;for(s=p.length;s>o;){if(c[--s]<p[s]){for(i=s;i&&c[--i]===0;)c[i]=js-1;--c[i],c[s]+=js}c[s]-=p[s]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--n;return c[0]?(t.d=c,t.e=n,Fr?yr(t,f):t):new h(0)}function yc(e,t,r){var n,s=ls(e),i=Ci(e.d),o=i.length;return t?(r&&(n=r-o)>0?i=i.charAt(0)+"."+i.slice(1)+Bo(n):o>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(s<0?"e":"e+")+s):s<0?(i="0."+Bo(-s-1)+i,r&&(n=r-o)>0&&(i+=Bo(n))):s>=o?(i+=Bo(s+1-o),r&&(n=r-s-1)>0&&(i=i+"."+Bo(n))):((n=s+1)<o&&(i=i.slice(0,n)+"."+i.slice(n)),r&&(n=r-o)>0&&(s+1===o&&(i+="."),i+=Bo(n))),e.s<0?"-"+i:i}function dP(e,t){if(e.length>t)return e.length=t,!0}function W4(e){var t,r,n;function s(i){var o=this;if(!(o instanceof s))return new s(i);if(o.constructor=s,i instanceof s){o.s=i.s,o.e=i.e,o.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(nc+i);if(i>0)o.s=1;else if(i<0)i=-i,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(i===~~i&&i<1e7){o.e=0,o.d=[i];return}return uP(o,i.toString())}else if(typeof i!="string")throw Error(nc+i);if(i.charCodeAt(0)===45?(i=i.slice(1),o.s=-1):o.s=1,Fae.test(i))uP(o,i);else throw Error(nc+i)}if(s.prototype=ft,s.ROUND_UP=0,s.ROUND_DOWN=1,s.ROUND_CEIL=2,s.ROUND_FLOOR=3,s.ROUND_HALF_UP=4,s.ROUND_HALF_DOWN=5,s.ROUND_HALF_EVEN=6,s.ROUND_HALF_CEIL=7,s.ROUND_HALF_FLOOR=8,s.clone=W4,s.config=s.set=Bae,e===void 0&&(e={}),e)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t<n.length;)e.hasOwnProperty(r=n[t++])||(e[r]=this[r]);return s.config(e),s}function Bae(e){if(!e||typeof e!="object")throw Error($a+"Object expected");var t,r,n,s=["precision",1,hd,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(t=0;t<s.length;t+=3)if((n=e[r=s[t]])!==void 0)if(fd(n)===n&&n>=s[t+1]&&n<=s[t+2])this[r]=n;else throw Error(nc+r+": "+n);if((n=e[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(nc+r+": "+n);return this}var Tj=W4($ae);xa=new Tj(1);const pr=Tj;function Uae(e){return Wae(e)||Hae(e)||qae(e)||zae()}function zae(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6951In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qae(e,t){if(e){if(typeof e=="string")return ov(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ov(e,t)}}function Hae(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function Wae(e){if(Array.isArray(e))return ov(e)}function ov(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var Vae=function(t){return t},V4={"@@functional/placeholder":!0},G4=function(t){return t===V4},pP=function(t){return function r(){return arguments.length===0||arguments.length===1&&G4(arguments.length<=0?void 0:arguments[0])?r:t.apply(void 0,arguments)}},Gae=function e(t,r){return t===1?r:pP(function(){for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];var o=s.filter(function(l){return l!==V4}).length;return o>=t?r.apply(void 0,s):e(t-o,pP(function(){for(var l=arguments.length,c=new Array(l),u=0;u<l;u++)c[u]=arguments[u];var d=s.map(function(p){return G4(p)?c.shift():p});return r.apply(void 0,Uae(d).concat(c))}))})},Ux=function(t){return Gae(t.length,t)},lv=function(t,r){for(var n=[],s=t;s<r;++s)n[s-t]=s;return n},Kae=Ux(function(e,t){return Array.isArray(t)?t.map(e):Object.keys(t).map(function(r){return t[r]}).map(e)}),Yae=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(!r.length)return Vae;var s=r.reverse(),i=s[0],o=s.slice(1);return function(){return o.reduce(function(l,c){return c(l)},i.apply(void 0,arguments))}},cv=function(t){return Array.isArray(t)?t.reverse():t.split("").reverse.join("")},K4=function(t){var r=null,n=null;return function(){for(var s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];return r&&i.every(function(l,c){return l===r[c]})||(r=i,n=t.apply(void 0,i)),n}};function Jae(e){var t;return e===0?t=1:t=Math.floor(new pr(e).abs().log(10).toNumber())+1,t}function Xae(e,t,r){for(var n=new pr(e),s=0,i=[];n.lt(t)&&s<1e5;)i.push(n.toNumber()),n=n.add(r),s++;return i}var Zae=Ux(function(e,t,r){var n=+e,s=+t;return n+r*(s-n)}),Qae=Ux(function(e,t,r){var n=t-+e;return n=n||1/0,(r-e)/n}),eie=Ux(function(e,t,r){var n=t-+e;return n=n||1/0,Math.max(0,Math.min(1,(r-e)/n))});const zx={rangeStep:Xae,getDigitCount:Jae,interpolateNumber:Zae,uninterpolateNumber:Qae,uninterpolateTruncation:eie};function uv(e){return rie(e)||nie(e)||Y4(e)||tie()}function tie(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6952In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function nie(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function rie(e){if(Array.isArray(e))return dv(e)}function eh(e,t){return iie(e)||aie(e,t)||Y4(e,t)||sie()}function sie(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6953In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Y4(e,t){if(e){if(typeof e=="string")return dv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return dv(e,t)}}function dv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function aie(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var r=[],n=!0,s=!1,i=void 0;try{for(var o=e[Symbol.iterator](),l;!(n=(l=o.next()).done)&&(r.push(l.value),!(t&&r.length===t));n=!0);}catch(c){s=!0,i=c}finally{try{!n&&o.return!=null&&o.return()}finally{if(s)throw i}}return r}}function iie(e){if(Array.isArray(e))return e}function J4(e){var t=eh(e,2),r=t[0],n=t[1],s=r,i=n;return r>n&&(s=n,i=r),[s,i]}function X4(e,t,r){if(e.lte(0))return new pr(0);var n=zx.getDigitCount(e.toNumber()),s=new pr(10).pow(n),i=e.div(s),o=n!==1?.05:.1,l=new pr(Math.ceil(i.div(o).toNumber())).add(r).mul(o),c=l.mul(s);return t?c:new pr(Math.ceil(c))}function oie(e,t,r){var n=1,s=new pr(e);if(!s.isint()&&r){var i=Math.abs(e);i<1?(n=new pr(10).pow(zx.getDigitCount(e)-1),s=new pr(Math.floor(s.div(n).toNumber())).mul(n)):i>1&&(s=new pr(Math.floor(e)))}else e===0?s=new pr(Math.floor((t-1)/2)):r||(s=new pr(Math.floor(e)));var o=Math.floor((t-1)/2),l=Yae(Kae(function(c){return s.add(new pr(c-o).mul(n)).toNumber()}),lv);return l(0,t)}function Z4(e,t,r,n){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-e)/(r-1)))return{step:new pr(0),tickMin:new pr(0),tickMax:new pr(0)};var i=X4(new pr(t).sub(e).div(r-1),n,s),o;e<=0&&t>=0?o=new pr(0):(o=new pr(e).add(t).div(2),o=o.sub(new pr(o).mod(i)));var l=Math.ceil(o.sub(e).div(i).toNumber()),c=Math.ceil(new pr(t).sub(o).div(i).toNumber()),u=l+c+1;return u>r?Z4(e,t,r,n,s+1):(u<r&&(c=t>0?c+(r-u):c,l=t>0?l:l+(r-u)),{step:i,tickMin:o.sub(new pr(l).mul(i)),tickMax:o.add(new pr(c).mul(i))})}function lie(e){var t=eh(e,2),r=t[0],n=t[1],s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(s,2),l=J4([r,n]),c=eh(l,2),u=c[0],d=c[1];if(u===-1/0||d===1/0){var p=d===1/0?[u].concat(uv(lv(0,s-1).map(function(){return 1/0}))):[].concat(uv(lv(0,s-1).map(function(){return-1/0})),[d]);return r>n?cv(p):p}if(u===d)return oie(u,s,i);var h=Z4(u,d,o,i),f=h.step,x=h.tickMin,g=h.tickMax,y=zx.rangeStep(x,g.add(new pr(.1).mul(f)),f);return r>n?cv(y):y}function cie(e,t){var r=eh(e,2),n=r[0],s=r[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=J4([n,s]),l=eh(o,2),c=l[0],u=l[1];if(c===-1/0||u===1/0)return[n,s];if(c===u)return[c];var d=Math.max(t,2),p=X4(new pr(u).sub(c).div(d-1),i,0),h=[].concat(uv(zx.rangeStep(new pr(c),new pr(u).sub(new pr(.99).mul(p)),p)),[u]);return n>s?cv(h):h}var uie=K4(lie),die=K4(cie),pie="Invariant failed";function bc(e,t){throw new Error(pie)}var hie=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function Lu(e){"@babel/helpers - typeof";return Lu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lu(e)}function og(){return og=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},og.apply(this,arguments)}function fie(e,t){return yie(e)||xie(e,t)||gie(e,t)||mie()}function mie(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6954In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gie(e,t){if(e){if(typeof e=="string")return hP(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return hP(e,t)}}function hP(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function xie(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function yie(e){if(Array.isArray(e))return e}function bie(e,t){if(e==null)return{};var r=vie(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function vie(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function wie(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function jie(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,tR(n.key),n)}}function Nie(e,t,r){return t&&jie(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function kie(e,t,r){return t=lg(t),Sie(e,Q4()?Reflect.construct(t,r||[],lg(e).constructor):t.apply(e,r))}function Sie(e,t){if(t&&(Lu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Cie(e)}function Cie(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Q4(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Q4=function(){return!!e})()}function lg(e){return lg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},lg(e)}function Pie(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&pv(e,t)}function pv(e,t){return pv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},pv(e,t)}function eR(e,t,r){return t=tR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function tR(e){var t=Aie(e,"string");return Lu(t)=="symbol"?t:t+""}function Aie(e,t){if(Lu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Lu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Bh=function(e){function t(){return wie(this,t),kie(this,t,arguments)}return Pie(t,e),Nie(t,[{key:"render",value:function(){var n=this.props,s=n.offset,i=n.layout,o=n.width,l=n.dataKey,c=n.data,u=n.dataPointFormatter,d=n.xAxis,p=n.yAxis,h=bie(n,hie),f=Pt(h,!1);this.props.direction==="x"&&d.type!=="number"&&bc();var x=c.map(function(g){var y=u(g,l),b=y.x,v=y.y,k=y.value,N=y.errorVal;if(!N)return null;var j=[],w,S;if(Array.isArray(N)){var T=fie(N,2);w=T[0],S=T[1]}else w=S=N;if(i==="vertical"){var C=d.scale,A=v+s,P=A+o,E=A-o,_=C(k-w),I=C(k+S);j.push({x1:I,y1:P,x2:I,y2:E}),j.push({x1:_,y1:A,x2:I,y2:A}),j.push({x1:_,y1:P,x2:_,y2:E})}else if(i==="horizontal"){var D=p.scale,M=b+s,B=M-o,$=M+o,K=D(k-w),R=D(k+S);j.push({x1:B,y1:R,x2:$,y2:R}),j.push({x1:M,y1:K,x2:M,y2:R}),j.push({x1:B,y1:K,x2:$,y2:K})}return H.createElement(Tn,og({className:"recharts-errorBar",key:"bar-".concat(j.map(function(Y){return"".concat(Y.x1,"-").concat(Y.x2,"-").concat(Y.y1,"-").concat(Y.y2)}))},f),j.map(function(Y){return H.createElement("line",og({},Y,{key:"line-".concat(Y.x1,"-").concat(Y.x2,"-").concat(Y.y1,"-").concat(Y.y2)}))}))});return H.createElement(Tn,{className:"recharts-errorBars"},x)}}])}(H.Component);eR(Bh,"defaultProps",{stroke:"black",strokeWidth:1.5,width:5,offset:0,layout:"horizontal"});eR(Bh,"displayName","ErrorBar");function th(e){"@babel/helpers - typeof";return th=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},th(e)}function fP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Al(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?fP(Object(r),!0).forEach(function(n){_ie(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function _ie(e,t,r){return t=Tie(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Tie(e){var t=Eie(e,"string");return th(t)=="symbol"?t:t+""}function Eie(e,t){if(th(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(th(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var nR=function(t){var r=t.children,n=t.formattedGraphicalItems,s=t.legendWidth,i=t.legendContent,o=fa(r,uo);if(!o)return null;var l=uo.defaultProps,c=l!==void 0?Al(Al({},l),o.props):{},u;return o.props&&o.props.payload?u=o.props&&o.props.payload:i==="children"?u=(n||[]).reduce(function(d,p){var h=p.item,f=p.props,x=f.sectors||f.data||[];return d.concat(x.map(function(g){return{type:o.props.iconType||h.props.legendType,value:g.name,color:g.fill,payload:g}}))},[]):u=(n||[]).map(function(d){var p=d.item,h=p.type.defaultProps,f=h!==void 0?Al(Al({},h),p.props):{},x=f.dataKey,g=f.name,y=f.legendType,b=f.hide;return{inactive:b,dataKey:x,type:c.iconType||y||"square",color:Ej(p),value:g||x,payload:f}}),Al(Al(Al({},c),uo.getWithHeight(o,s)),{},{payload:u,item:o})};function nh(e){"@babel/helpers - typeof";return nh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nh(e)}function mP(e){return Die(e)||Rie(e)||Oie(e)||Iie()}function Iie(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6955In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Oie(e,t){if(e){if(typeof e=="string")return hv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return hv(e,t)}}function Rie(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Die(e){if(Array.isArray(e))return hv(e)}function hv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function gP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Vr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?gP(Object(r),!0).forEach(function(n){bu(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):gP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bu(e,t,r){return t=Mie(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Mie(e){var t=Lie(e,"string");return nh(t)=="symbol"?t:t+""}function Lie(e,t){if(nh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(nh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function es(e,t,r){return an(e)||an(t)?r:xs(t)?ba(e,t,r):Kt(t)?t(e):r}function kp(e,t,r,n){var s=Lae(e,function(l){return es(l,t)});if(r==="number"){var i=s.filter(function(l){return Oe(l)||parseFloat(l)});return i.length?[Bx(i),Go(i)]:[1/0,-1/0]}var o=n?s.filter(function(l){return!an(l)}):s;return o.map(function(l){return xs(l)||l instanceof Date?l:""})}var $ie=function(t){var r,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],s=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o=-1,l=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(l<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,u=0;u<l;u++){var d=u>0?s[u-1].coordinate:s[l-1].coordinate,p=s[u].coordinate,h=u>=l-1?s[0].coordinate:s[u+1].coordinate,f=void 0;if(Js(p-d)!==Js(h-p)){var x=[];if(Js(h-p)===Js(c[1]-c[0])){f=h;var g=p+c[1]-c[0];x[0]=Math.min(g,(g+d)/2),x[1]=Math.max(g,(g+d)/2)}else{f=d;var y=h+c[1]-c[0];x[0]=Math.min(p,(y+p)/2),x[1]=Math.max(p,(y+p)/2)}var b=[Math.min(p,(f+p)/2),Math.max(p,(f+p)/2)];if(t>b[0]&&t<=b[1]||t>=x[0]&&t<=x[1]){o=s[u].index;break}}else{var v=Math.min(d,h),k=Math.max(d,h);if(t>(v+p)/2&&t<=(k+p)/2){o=s[u].index;break}}}else for(var N=0;N<l;N++)if(N===0&&t<=(n[N].coordinate+n[N+1].coordinate)/2||N>0&&N<l-1&&t>(n[N].coordinate+n[N-1].coordinate)/2&&t<=(n[N].coordinate+n[N+1].coordinate)/2||N===l-1&&t>(n[N].coordinate+n[N-1].coordinate)/2){o=n[N].index;break}return o},Ej=function(t){var r,n=t,s=n.type.displayName,i=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Vr(Vr({},t.type.defaultProps),t.props):t.props,o=i.stroke,l=i.fill,c;switch(s){case"Line":c=o;break;case"Area":case"Radar":c=o&&o!=="none"?o:l;break;default:c=l;break}return c},Fie=function(t){var r=t.barSize,n=t.totalSize,s=t.stackGroups,i=s===void 0?{}:s;if(!i)return{};for(var o={},l=Object.keys(i),c=0,u=l.length;c<u;c++)for(var d=i[l[c]].stackGroups,p=Object.keys(d),h=0,f=p.length;h<f;h++){var x=d[p[h]],g=x.items,y=x.cateAxisId,b=g.filter(function(S){return co(S.type).indexOf("Bar")>=0});if(b&&b.length){var v=b[0].type.defaultProps,k=v!==void 0?Vr(Vr({},v),b[0].props):b[0].props,N=k.barSize,j=k[y];o[j]||(o[j]=[]);var w=an(N)?r:N;o[j].push({item:b[0],stackList:b.slice(1),barSize:an(w)?void 0:Xs(w,n,0)})}}return o},Bie=function(t){var r=t.barGap,n=t.barCategoryGap,s=t.bandSize,i=t.sizeList,o=i===void 0?[]:i,l=t.maxBarSize,c=o.length;if(c<1)return null;var u=Xs(r,s,0,!0),d,p=[];if(o[0].barSize===+o[0].barSize){var h=!1,f=s/c,x=o.reduce(function(N,j){return N+j.barSize||0},0);x+=(c-1)*u,x>=s&&(x-=(c-1)*u,u=0),x>=s&&f>0&&(h=!0,f*=.9,x=c*f);var g=(s-x)/2>>0,y={offset:g-u,size:0};d=o.reduce(function(N,j){var w={item:j.item,position:{offset:y.offset+y.size+u,size:h?f:j.barSize}},S=[].concat(mP(N),[w]);return y=S[S.length-1].position,j.stackList&&j.stackList.length&&j.stackList.forEach(function(T){S.push({item:T,position:y})}),S},p)}else{var b=Xs(n,s,0,!0);s-2*b-(c-1)*u<=0&&(u=0);var v=(s-2*b-(c-1)*u)/c;v>1&&(v>>=0);var k=l===+l?Math.min(v,l):v;d=o.reduce(function(N,j,w){var S=[].concat(mP(N),[{item:j.item,position:{offset:b+(v+u)*w+(v-k)/2,size:k}}]);return j.stackList&&j.stackList.length&&j.stackList.forEach(function(T){S.push({item:T,position:S[S.length-1].position})}),S},p)}return d},Uie=function(t,r,n,s){var i=n.children,o=n.width,l=n.margin,c=o-(l.left||0)-(l.right||0),u=nR({children:i,legendWidth:c});if(u){var d=s||{},p=d.width,h=d.height,f=u.align,x=u.verticalAlign,g=u.layout;if((g==="vertical"||g==="horizontal"&&x==="middle")&&f!=="center"&&Oe(t[f]))return Vr(Vr({},t),{},bu({},f,t[f]+(p||0)));if((g==="horizontal"||g==="vertical"&&f==="center")&&x!=="middle"&&Oe(t[x]))return Vr(Vr({},t),{},bu({},x,t[x]+(h||0)))}return t},zie=function(t,r,n){return an(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},rR=function(t,r,n,s,i){var o=r.props.children,l=wa(o,Bh).filter(function(u){return zie(s,i,u.props.direction)});if(l&&l.length){var c=l.map(function(u){return u.props.dataKey});return t.reduce(function(u,d){var p=es(d,n);if(an(p))return u;var h=Array.isArray(p)?[Bx(p),Go(p)]:[p,p],f=c.reduce(function(x,g){var y=es(d,g,0),b=h[0]-Math.abs(Array.isArray(y)?y[0]:y),v=h[1]+Math.abs(Array.isArray(y)?y[1]:y);return[Math.min(b,x[0]),Math.max(v,x[1])]},[1/0,-1/0]);return[Math.min(f[0],u[0]),Math.max(f[1],u[1])]},[1/0,-1/0])}return null},qie=function(t,r,n,s,i){var o=r.map(function(l){return rR(t,l,n,i,s)}).filter(function(l){return!an(l)});return o&&o.length?o.reduce(function(l,c){return[Math.min(l[0],c[0]),Math.max(l[1],c[1])]},[1/0,-1/0]):null},sR=function(t,r,n,s,i){var o=r.map(function(c){var u=c.props.dataKey;return n==="number"&&u&&rR(t,c,u,s)||kp(t,u,n,i)});if(n==="number")return o.reduce(function(c,u){return[Math.min(c[0],u[0]),Math.max(c[1],u[1])]},[1/0,-1/0]);var l={};return o.reduce(function(c,u){for(var d=0,p=u.length;d<p;d++)l[u[d]]||(l[u[d]]=!0,c.push(u[d]));return c},[])},aR=function(t,r){return t==="horizontal"&&r==="xAxis"||t==="vertical"&&r==="yAxis"||t==="centric"&&r==="angleAxis"||t==="radial"&&r==="radiusAxis"},iR=function(t,r,n,s){if(s)return t.map(function(c){return c.coordinate});var i,o,l=t.map(function(c){return c.coordinate===r&&(i=!0),c.coordinate===n&&(o=!0),c.coordinate});return i||l.push(r),o||l.push(n),l},ao=function(t,r,n){if(!t)return null;var s=t.scale,i=t.duplicateDomain,o=t.type,l=t.range,c=t.realScaleType==="scaleBand"?s.bandwidth()/2:2,u=(r||n)&&o==="category"&&s.bandwidth?s.bandwidth()/c:0;if(u=t.axisType==="angleAxis"&&(l==null?void 0:l.length)>=2?Js(l[0]-l[1])*2*u:u,r&&(t.ticks||t.niceTicks)){var d=(t.ticks||t.niceTicks).map(function(p){var h=i?i.indexOf(p):p;return{coordinate:s(h)+u,value:p,offset:u}});return d.filter(function(p){return!dd(p.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(p,h){return{coordinate:s(p)+u,value:p,index:h,offset:u}}):s.ticks&&!n?s.ticks(t.tickCount).map(function(p){return{coordinate:s(p)+u,value:p,offset:u}}):s.domain().map(function(p,h){return{coordinate:s(p)+u,value:i?i[p]:p,index:h,offset:u}})},bb=new WeakMap,Lf=function(t,r){if(typeof r!="function")return t;bb.has(t)||bb.set(t,new WeakMap);var n=bb.get(t);if(n.has(r))return n.get(r);var s=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,s),s},oR=function(t,r,n){var s=t.scale,i=t.type,o=t.layout,l=t.axisType;if(s==="auto")return o==="radial"&&l==="radiusAxis"?{scale:Kp(),realScaleType:"band"}:o==="radial"&&l==="angleAxis"?{scale:ng(),realScaleType:"linear"}:i==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:Np(),realScaleType:"point"}:i==="category"?{scale:Kp(),realScaleType:"band"}:{scale:ng(),realScaleType:"linear"};if(ic(s)){var c="scale".concat(Hg(s));return{scale:(cP[c]||Np)(),realScaleType:cP[c]?c:"point"}}return Kt(s)?{scale:s}:{scale:Np(),realScaleType:"point"}},xP=1e-4,lR=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,s=t.range(),i=Math.min(s[0],s[1])-xP,o=Math.max(s[0],s[1])+xP,l=t(r[0]),c=t(r[n-1]);(l<i||l>o||c<i||c>o)&&t.domain([r[0],r[n-1]])}},Hie=function(t,r){if(!t)return null;for(var n=0,s=t.length;n<s;n++)if(t[n].item===r)return t[n].position;return null},Wie=function(t,r){if(!r||r.length!==2||!Oe(r[0])||!Oe(r[1]))return t;var n=Math.min(r[0],r[1]),s=Math.max(r[0],r[1]),i=[t[0],t[1]];return(!Oe(t[0])||t[0]<n)&&(i[0]=n),(!Oe(t[1])||t[1]>s)&&(i[1]=s),i[0]>s&&(i[0]=s),i[1]<n&&(i[1]=n),i},Vie=function(t){var r=t.length;if(!(r<=0))for(var n=0,s=t[0].length;n<s;++n)for(var i=0,o=0,l=0;l<r;++l){var c=dd(t[l][n][1])?t[l][n][0]:t[l][n][1];c>=0?(t[l][n][0]=i,t[l][n][1]=i+c,i=t[l][n][1]):(t[l][n][0]=o,t[l][n][1]=o+c,o=t[l][n][1])}},Gie=function(t){var r=t.length;if(!(r<=0))for(var n=0,s=t[0].length;n<s;++n)for(var i=0,o=0;o<r;++o){var l=dd(t[o][n][1])?t[o][n][0]:t[o][n][1];l>=0?(t[o][n][0]=i,t[o][n][1]=i+l,i=t[o][n][1]):(t[o][n][0]=0,t[o][n][1]=0)}},Kie={sign:Vie,expand:qQ,none:_u,silhouette:HQ,wiggle:WQ,positive:Gie},Yie=function(t,r,n){var s=r.map(function(l){return l.props.dataKey}),i=Kie[n],o=zQ().keys(s).value(function(l,c){return+es(l,c,0)}).order(q0).offset(i);return o(t)},Jie=function(t,r,n,s,i,o){if(!t)return null;var l=o?r.reverse():r,c={},u=l.reduce(function(p,h){var f,x=(f=h.type)!==null&&f!==void 0&&f.defaultProps?Vr(Vr({},h.type.defaultProps),h.props):h.props,g=x.stackId,y=x.hide;if(y)return p;var b=x[n],v=p[b]||{hasStack:!1,stackGroups:{}};if(xs(g)){var k=v.stackGroups[g]||{numericAxisId:n,cateAxisId:s,items:[]};k.items.push(h),v.hasStack=!0,v.stackGroups[g]=k}else v.stackGroups[Sc("_stackId_")]={numericAxisId:n,cateAxisId:s,items:[h]};return Vr(Vr({},p),{},bu({},b,v))},c),d={};return Object.keys(u).reduce(function(p,h){var f=u[h];if(f.hasStack){var x={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(g,y){var b=f.stackGroups[y];return Vr(Vr({},g),{},bu({},y,{numericAxisId:n,cateAxisId:s,items:b.items,stackedData:Yie(t,b.items,i)}))},x)}return Vr(Vr({},p),{},bu({},h,f))},d)},cR=function(t,r){var n=r.realScaleType,s=r.type,i=r.tickCount,o=r.originalDomain,l=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&s==="number"&&o&&(o[0]==="auto"||o[1]==="auto")){var u=t.domain();if(!u.length)return null;var d=uie(u,i,l);return t.domain([Bx(d),Go(d)]),{niceTicks:d}}if(i&&s==="number"){var p=t.domain(),h=die(p,i,l);return{niceTicks:h}}return null};function cg(e){var t=e.axis,r=e.ticks,n=e.bandSize,s=e.entry,i=e.index,o=e.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!an(s[t.dataKey])){var l=$m(r,"value",s[t.dataKey]);if(l)return l.coordinate+n/2}return r[i]?r[i].coordinate+n/2:null}var c=es(s,an(o)?t.dataKey:o);return an(c)?null:t.scale(c)}var yP=function(t){var r=t.axis,n=t.ticks,s=t.offset,i=t.bandSize,o=t.entry,l=t.index;if(r.type==="category")return n[l]?n[l].coordinate+s:null;var c=es(o,r.dataKey,r.domain[l]);return an(c)?null:r.scale(c)-i/2+s},Xie=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var s=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return s<=0&&i>=0?0:i<0?i:s}return n[0]},Zie=function(t,r){var n,s=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Vr(Vr({},t.type.defaultProps),t.props):t.props,i=s.stackId;if(xs(i)){var o=r[i];if(o){var l=o.items.indexOf(t);return l>=0?o.stackedData[l]:null}}return null},Qie=function(t){return t.reduce(function(r,n){return[Bx(n.concat([r[0]]).filter(Oe)),Go(n.concat([r[1]]).filter(Oe))]},[1/0,-1/0])},uR=function(t,r,n){return Object.keys(t).reduce(function(s,i){var o=t[i],l=o.stackedData,c=l.reduce(function(u,d){var p=Qie(d.slice(r,n+1));return[Math.min(u[0],p[0]),Math.max(u[1],p[1])]},[1/0,-1/0]);return[Math.min(c[0],s[0]),Math.max(c[1],s[1])]},[1/0,-1/0]).map(function(s){return s===1/0||s===-1/0?0:s})},bP=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,vP=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,fv=function(t,r,n){if(Kt(t))return t(r,n);if(!Array.isArray(t))return r;var s=[];if(Oe(t[0]))s[0]=n?t[0]:Math.min(t[0],r[0]);else if(bP.test(t[0])){var i=+bP.exec(t[0])[1];s[0]=r[0]-i}else Kt(t[0])?s[0]=t[0](r[0]):s[0]=r[0];if(Oe(t[1]))s[1]=n?t[1]:Math.max(t[1],r[1]);else if(vP.test(t[1])){var o=+vP.exec(t[1])[1];s[1]=r[1]+o}else Kt(t[1])?s[1]=t[1](r[1]):s[1]=r[1];return s},ug=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var s=t.scale.bandwidth();if(!n||s>0)return s}if(t&&r&&r.length>=2){for(var i=aj(r,function(p){return p.coordinate}),o=1/0,l=1,c=i.length;l<c;l++){var u=i[l],d=i[l-1];o=Math.min((u.coordinate||0)-(d.coordinate||0),o)}return o===1/0?0:o}return n?void 0:0},wP=function(t,r,n){return!t||!t.length||oc(t,ba(n,"type.defaultProps.domain"))?r:t},dR=function(t,r){var n=t.type.defaultProps?Vr(Vr({},t.type.defaultProps),t.props):t.props,s=n.dataKey,i=n.name,o=n.unit,l=n.formatter,c=n.tooltipType,u=n.chartType,d=n.hide;return Vr(Vr({},Pt(t,!1)),{},{dataKey:s,unit:o,formatter:l,name:i||s,color:Ej(t),value:es(r,s),type:c,payload:r,chartType:u,hide:d})};function rh(e){"@babel/helpers - typeof";return rh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rh(e)}function jP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Qi(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?jP(Object(r),!0).forEach(function(n){pR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function pR(e,t,r){return t=eoe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function eoe(e){var t=toe(e,"string");return rh(t)=="symbol"?t:t+""}function toe(e,t){if(rh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(rh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function noe(e,t){return ioe(e)||aoe(e,t)||soe(e,t)||roe()}function roe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6956In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function soe(e,t){if(e){if(typeof e=="string")return NP(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return NP(e,t)}}function NP(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function aoe(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function ioe(e){if(Array.isArray(e))return e}var dg=Math.PI/180,ooe=function(t){return t*180/Math.PI},_r=function(t,r,n,s){return{x:t+Math.cos(-dg*s)*n,y:r+Math.sin(-dg*s)*n}},hR=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},loe=function(t,r,n,s,i){var o=t.width,l=t.height,c=t.startAngle,u=t.endAngle,d=Xs(t.cx,o,o/2),p=Xs(t.cy,l,l/2),h=hR(o,l,n),f=Xs(t.innerRadius,h,0),x=Xs(t.outerRadius,h,h*.8),g=Object.keys(r);return g.reduce(function(y,b){var v=r[b],k=v.domain,N=v.reversed,j;if(an(v.range))s==="angleAxis"?j=[c,u]:s==="radiusAxis"&&(j=[f,x]),N&&(j=[j[1],j[0]]);else{j=v.range;var w=j,S=noe(w,2);c=S[0],u=S[1]}var T=oR(v,i),C=T.realScaleType,A=T.scale;A.domain(k).range(j),lR(A);var P=cR(A,Qi(Qi({},v),{},{realScaleType:C})),E=Qi(Qi(Qi({},v),P),{},{range:j,radius:x,realScaleType:C,scale:A,cx:d,cy:p,innerRadius:f,outerRadius:x,startAngle:c,endAngle:u});return Qi(Qi({},y),{},pR({},b,E))},{})},coe=function(t,r){var n=t.x,s=t.y,i=r.x,o=r.y;return Math.sqrt(Math.pow(n-i,2)+Math.pow(s-o,2))},uoe=function(t,r){var n=t.x,s=t.y,i=r.cx,o=r.cy,l=coe({x:n,y:s},{x:i,y:o});if(l<=0)return{radius:l};var c=(n-i)/l,u=Math.acos(c);return s>o&&(u=2*Math.PI-u),{radius:l,angle:ooe(u),angleInRadian:u}},doe=function(t){var r=t.startAngle,n=t.endAngle,s=Math.floor(r/360),i=Math.floor(n/360),o=Math.min(s,i);return{startAngle:r-o*360,endAngle:n-o*360}},poe=function(t,r){var n=r.startAngle,s=r.endAngle,i=Math.floor(n/360),o=Math.floor(s/360),l=Math.min(i,o);return t+l*360},kP=function(t,r){var n=t.x,s=t.y,i=uoe({x:n,y:s},r),o=i.radius,l=i.angle,c=r.innerRadius,u=r.outerRadius;if(o<c||o>u)return!1;if(o===0)return!0;var d=doe(r),p=d.startAngle,h=d.endAngle,f=l,x;if(p<=h){for(;f>h;)f-=360;for(;f<p;)f+=360;x=f>=p&&f<=h}else{for(;f>p;)f-=360;for(;f<h;)f+=360;x=f>=h&&f<=p}return x?Qi(Qi({},r),{},{radius:o,angle:poe(f,r)}):null},fR=function(t){return!m.isValidElement(t)&&!Kt(t)&&typeof t!="boolean"?t.className:""};function sh(e){"@babel/helpers - typeof";return sh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},sh(e)}var hoe=["offset"];function foe(e){return yoe(e)||xoe(e)||goe(e)||moe()}function moe(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6957In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function goe(e,t){if(e){if(typeof e=="string")return mv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return mv(e,t)}}function xoe(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function yoe(e){if(Array.isArray(e))return mv(e)}function mv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function boe(e,t){if(e==null)return{};var r=voe(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function voe(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function SP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function ps(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?SP(Object(r),!0).forEach(function(n){woe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):SP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function woe(e,t,r){return t=joe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function joe(e){var t=Noe(e,"string");return sh(t)=="symbol"?t:t+""}function Noe(e,t){if(sh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(sh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ah(){return ah=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ah.apply(this,arguments)}var koe=function(t){var r=t.value,n=t.formatter,s=an(t.children)?r:t.children;return Kt(n)?n(s):s},Soe=function(t,r){var n=Js(r-t),s=Math.min(Math.abs(r-t),360);return n*s},Coe=function(t,r,n){var s=t.position,i=t.viewBox,o=t.offset,l=t.className,c=i,u=c.cx,d=c.cy,p=c.innerRadius,h=c.outerRadius,f=c.startAngle,x=c.endAngle,g=c.clockWise,y=(p+h)/2,b=Soe(f,x),v=b>=0?1:-1,k,N;s==="insideStart"?(k=f+v*o,N=g):s==="insideEnd"?(k=x-v*o,N=!g):s==="end"&&(k=x+v*o,N=g),N=b<=0?N:!N;var j=_r(u,d,y,k),w=_r(u,d,y,k+(N?1:-1)*359),S="M".concat(j.x,",").concat(j.y,`
6958    A`).concat(y,",").concat(y,",0,1,").concat(N?0:1,`,
6959    `).concat(w.x,",").concat(w.y),T=an(t.id)?Sc("recharts-radial-line-"):t.id;return H.createElement("text",ah({},n,{dominantBaseline:"central",className:fn("recharts-radial-bar-label",l)}),H.createElement("defs",null,H.createElement("path",{id:T,d:S})),H.createElement("textPath",{xlinkHref:"#".concat(T)},r))},Poe=function(t){var r=t.viewBox,n=t.offset,s=t.position,i=r,o=i.cx,l=i.cy,c=i.innerRadius,u=i.outerRadius,d=i.startAngle,p=i.endAngle,h=(d+p)/2;if(s==="outside"){var f=_r(o,l,u+n,h),x=f.x,g=f.y;return{x,y:g,textAnchor:x>=o?"start":"end",verticalAnchor:"middle"}}if(s==="center")return{x:o,y:l,textAnchor:"middle",verticalAnchor:"middle"};if(s==="centerTop")return{x:o,y:l,textAnchor:"middle",verticalAnchor:"start"};if(s==="centerBottom")return{x:o,y:l,textAnchor:"middle",verticalAnchor:"end"};var y=(c+u)/2,b=_r(o,l,y,h),v=b.x,k=b.y;return{x:v,y:k,textAnchor:"middle",verticalAnchor:"middle"}},Aoe=function(t){var r=t.viewBox,n=t.parentViewBox,s=t.offset,i=t.position,o=r,l=o.x,c=o.y,u=o.width,d=o.height,p=d>=0?1:-1,h=p*s,f=p>0?"end":"start",x=p>0?"start":"end",g=u>=0?1:-1,y=g*s,b=g>0?"end":"start",v=g>0?"start":"end";if(i==="top"){var k={x:l+u/2,y:c-p*s,textAnchor:"middle",verticalAnchor:f};return ps(ps({},k),n?{height:Math.max(c-n.y,0),width:u}:{})}if(i==="bottom"){var N={x:l+u/2,y:c+d+h,textAnchor:"middle",verticalAnchor:x};return ps(ps({},N),n?{height:Math.max(n.y+n.height-(c+d),0),width:u}:{})}if(i==="left"){var j={x:l-y,y:c+d/2,textAnchor:b,verticalAnchor:"middle"};return ps(ps({},j),n?{width:Math.max(j.x-n.x,0),height:d}:{})}if(i==="right"){var w={x:l+u+y,y:c+d/2,textAnchor:v,verticalAnchor:"middle"};return ps(ps({},w),n?{width:Math.max(n.x+n.width-w.x,0),height:d}:{})}var S=n?{width:u,height:d}:{};return i==="insideLeft"?ps({x:l+y,y:c+d/2,textAnchor:v,verticalAnchor:"middle"},S):i==="insideRight"?ps({x:l+u-y,y:c+d/2,textAnchor:b,verticalAnchor:"middle"},S):i==="insideTop"?ps({x:l+u/2,y:c+h,textAnchor:"middle",verticalAnchor:x},S):i==="insideBottom"?ps({x:l+u/2,y:c+d-h,textAnchor:"middle",verticalAnchor:f},S):i==="insideTopLeft"?ps({x:l+y,y:c+h,textAnchor:v,verticalAnchor:x},S):i==="insideTopRight"?ps({x:l+u-y,y:c+h,textAnchor:b,verticalAnchor:x},S):i==="insideBottomLeft"?ps({x:l+y,y:c+d-h,textAnchor:v,verticalAnchor:f},S):i==="insideBottomRight"?ps({x:l+u-y,y:c+d-h,textAnchor:b,verticalAnchor:f},S):rd(i)&&(Oe(i.x)||zl(i.x))&&(Oe(i.y)||zl(i.y))?ps({x:l+Xs(i.x,u),y:c+Xs(i.y,d),textAnchor:"end",verticalAnchor:"end"},S):ps({x:l+u/2,y:c+d/2,textAnchor:"middle",verticalAnchor:"middle"},S)},_oe=function(t){return"cx"in t&&Oe(t.cx)};function Ss(e){var t=e.offset,r=t===void 0?5:t,n=boe(e,hoe),s=ps({offset:r},n),i=s.viewBox,o=s.position,l=s.value,c=s.children,u=s.content,d=s.className,p=d===void 0?"":d,h=s.textBreakAll;if(!i||an(l)&&an(c)&&!m.isValidElement(u)&&!Kt(u))return null;if(m.isValidElement(u))return m.cloneElement(u,s);var f;if(Kt(u)){if(f=m.createElement(u,s),m.isValidElement(f))return f}else f=koe(s);var x=_oe(i),g=Pt(s,!0);if(x&&(o==="insideStart"||o==="insideEnd"||o==="end"))return Coe(s,f,g);var y=x?Poe(s):Aoe(s);return H.createElement(xc,ah({className:fn("recharts-label",p)},g,y,{breakAll:h}),f)}Ss.displayName="Label";var mR=function(t){var r=t.cx,n=t.cy,s=t.angle,i=t.startAngle,o=t.endAngle,l=t.r,c=t.radius,u=t.innerRadius,d=t.outerRadius,p=t.x,h=t.y,f=t.top,x=t.left,g=t.width,y=t.height,b=t.clockWise,v=t.labelViewBox;if(v)return v;if(Oe(g)&&Oe(y)){if(Oe(p)&&Oe(h))return{x:p,y:h,width:g,height:y};if(Oe(f)&&Oe(x))return{x:f,y:x,width:g,height:y}}return Oe(p)&&Oe(h)?{x:p,y:h,width:0,height:0}:Oe(r)&&Oe(n)?{cx:r,cy:n,startAngle:i||s||0,endAngle:o||s||0,innerRadius:u||0,outerRadius:d||c||l||0,clockWise:b}:t.viewBox?t.viewBox:{}},Toe=function(t,r){return t?t===!0?H.createElement(Ss,{key:"label-implicit",viewBox:r}):xs(t)?H.createElement(Ss,{key:"label-implicit",viewBox:r,value:t}):m.isValidElement(t)?t.type===Ss?m.cloneElement(t,{key:"label-implicit",viewBox:r}):H.createElement(Ss,{key:"label-implicit",content:t,viewBox:r}):Kt(t)?H.createElement(Ss,{key:"label-implicit",content:t,viewBox:r}):rd(t)?H.createElement(Ss,ah({viewBox:r},t,{key:"label-implicit"})):null:null},Eoe=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var s=t.children,i=mR(t),o=wa(s,Ss).map(function(c,u){return m.cloneElement(c,{viewBox:r||i,key:"label-".concat(u)})});if(!n)return o;var l=Toe(t.label,r||i);return[l].concat(foe(o))};Ss.parseViewBox=mR;Ss.renderCallByParent=Eoe;function ih(e){"@babel/helpers - typeof";return ih=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ih(e)}var Ioe=["valueAccessor"],Ooe=["data","dataKey","clockWise","id","textBreakAll"];function Roe(e){return $oe(e)||Loe(e)||Moe(e)||Doe()}function Doe(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6960In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Moe(e,t){if(e){if(typeof e=="string")return gv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return gv(e,t)}}function Loe(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function $oe(e){if(Array.isArray(e))return gv(e)}function gv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function pg(){return pg=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},pg.apply(this,arguments)}function CP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function PP(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?CP(Object(r),!0).forEach(function(n){Foe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):CP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Foe(e,t,r){return t=Boe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Boe(e){var t=Uoe(e,"string");return ih(t)=="symbol"?t:t+""}function Uoe(e,t){if(ih(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ih(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function AP(e,t){if(e==null)return{};var r=zoe(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function zoe(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var qoe=function(t){return Array.isArray(t.value)?s$(t.value):t.value};function Ti(e){var t=e.valueAccessor,r=t===void 0?qoe:t,n=AP(e,Ioe),s=n.data,i=n.dataKey,o=n.clockWise,l=n.id,c=n.textBreakAll,u=AP(n,Ooe);return!s||!s.length?null:H.createElement(Tn,{className:"recharts-label-list"},s.map(function(d,p){var h=an(i)?r(d,p):es(d&&d.payload,i),f=an(l)?{}:{id:"".concat(l,"-").concat(p)};return H.createElement(Ss,pg({},Pt(d,!0),u,f,{parentViewBox:d.parentViewBox,value:h,textBreakAll:c,viewBox:Ss.parseViewBox(an(o)?d:PP(PP({},d),{},{clockWise:o})),key:"label-".concat(p),index:p}))}))}Ti.displayName="LabelList";function Hoe(e,t){return e?e===!0?H.createElement(Ti,{key:"labelList-implicit",data:t}):H.isValidElement(e)||Kt(e)?H.createElement(Ti,{key:"labelList-implicit",data:t,content:e}):rd(e)?H.createElement(Ti,pg({data:t},e,{key:"labelList-implicit"})):null:null}function Woe(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&r&&!e.label)return null;var n=e.children,s=wa(n,Ti).map(function(o,l){return m.cloneElement(o,{data:t,key:"labelList-".concat(l)})});if(!r)return s;var i=Hoe(e.label,t);return[i].concat(Roe(s))}Ti.renderCallByParent=Woe;function oh(e){"@babel/helpers - typeof";return oh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},oh(e)}function xv(){return xv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},xv.apply(this,arguments)}function _P(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function TP(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_P(Object(r),!0).forEach(function(n){Voe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_P(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Voe(e,t,r){return t=Goe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Goe(e){var t=Koe(e,"string");return oh(t)=="symbol"?t:t+""}function Koe(e,t){if(oh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(oh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Yoe=function(t,r){var n=Js(r-t),s=Math.min(Math.abs(r-t),359.999);return n*s},$f=function(t){var r=t.cx,n=t.cy,s=t.radius,i=t.angle,o=t.sign,l=t.isExternal,c=t.cornerRadius,u=t.cornerIsExternal,d=c*(l?1:-1)+s,p=Math.asin(c/d)/dg,h=u?i:i+o*p,f=_r(r,n,d,h),x=_r(r,n,s,h),g=u?i-o*p:i,y=_r(r,n,d*Math.cos(p*dg),g);return{center:f,circleTangency:x,lineTangency:y,theta:p}},gR=function(t){var r=t.cx,n=t.cy,s=t.innerRadius,i=t.outerRadius,o=t.startAngle,l=t.endAngle,c=Yoe(o,l),u=o+c,d=_r(r,n,i,o),p=_r(r,n,i,u),h="M ".concat(d.x,",").concat(d.y,`
6961    A `).concat(i,",").concat(i,`,0,
6962    `).concat(+(Math.abs(c)>180),",").concat(+(o>u),`,
6963    `).concat(p.x,",").concat(p.y,`
6964  `);if(s>0){var f=_r(r,n,s,o),x=_r(r,n,s,u);h+="L ".concat(x.x,",").concat(x.y,`
6965            A `).concat(s,",").concat(s,`,0,
6966            `).concat(+(Math.abs(c)>180),",").concat(+(o<=u),`,
6967            `).concat(f.x,",").concat(f.y," Z")}else h+="L ".concat(r,",").concat(n," Z");return h},Joe=function(t){var r=t.cx,n=t.cy,s=t.innerRadius,i=t.outerRadius,o=t.cornerRadius,l=t.forceCornerRadius,c=t.cornerIsExternal,u=t.startAngle,d=t.endAngle,p=Js(d-u),h=$f({cx:r,cy:n,radius:i,angle:u,sign:p,cornerRadius:o,cornerIsExternal:c}),f=h.circleTangency,x=h.lineTangency,g=h.theta,y=$f({cx:r,cy:n,radius:i,angle:d,sign:-p,cornerRadius:o,cornerIsExternal:c}),b=y.circleTangency,v=y.lineTangency,k=y.theta,N=c?Math.abs(u-d):Math.abs(u-d)-g-k;if(N<0)return l?"M ".concat(x.x,",").concat(x.y,`
6968        a`).concat(o,",").concat(o,",0,0,1,").concat(o*2,`,0
6969        a`).concat(o,",").concat(o,",0,0,1,").concat(-o*2,`,0
6970      `):gR({cx:r,cy:n,innerRadius:s,outerRadius:i,startAngle:u,endAngle:d});var j="M ".concat(x.x,",").concat(x.y,`
6971    A`).concat(o,",").concat(o,",0,0,").concat(+(p<0),",").concat(f.x,",").concat(f.y,`
6972    A`).concat(i,",").concat(i,",0,").concat(+(N>180),",").concat(+(p<0),",").concat(b.x,",").concat(b.y,`
6973    A`).concat(o,",").concat(o,",0,0,").concat(+(p<0),",").concat(v.x,",").concat(v.y,`
6974  `);if(s>0){var w=$f({cx:r,cy:n,radius:s,angle:u,sign:p,isExternal:!0,cornerRadius:o,cornerIsExternal:c}),S=w.circleTangency,T=w.lineTangency,C=w.theta,A=$f({cx:r,cy:n,radius:s,angle:d,sign:-p,isExternal:!0,cornerRadius:o,cornerIsExternal:c}),P=A.circleTangency,E=A.lineTangency,_=A.theta,I=c?Math.abs(u-d):Math.abs(u-d)-C-_;if(I<0&&o===0)return"".concat(j,"L").concat(r,",").concat(n,"Z");j+="L".concat(E.x,",").concat(E.y,`
6975      A`).concat(o,",").concat(o,",0,0,").concat(+(p<0),",").concat(P.x,",").concat(P.y,`
6976      A`).concat(s,",").concat(s,",0,").concat(+(I>180),",").concat(+(p>0),",").concat(S.x,",").concat(S.y,`
6977      A`).concat(o,",").concat(o,",0,0,").concat(+(p<0),",").concat(T.x,",").concat(T.y,"Z")}else j+="L".concat(r,",").concat(n,"Z");return j},Xoe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},xR=function(t){var r=TP(TP({},Xoe),t),n=r.cx,s=r.cy,i=r.innerRadius,o=r.outerRadius,l=r.cornerRadius,c=r.forceCornerRadius,u=r.cornerIsExternal,d=r.startAngle,p=r.endAngle,h=r.className;if(o<i||d===p)return null;var f=fn("recharts-sector",h),x=o-i,g=Xs(l,x,0,!0),y;return g>0&&Math.abs(d-p)<360?y=Joe({cx:n,cy:s,innerRadius:i,outerRadius:o,cornerRadius:Math.min(g,x/2),forceCornerRadius:c,cornerIsExternal:u,startAngle:d,endAngle:p}):y=gR({cx:n,cy:s,innerRadius:i,outerRadius:o,startAngle:d,endAngle:p}),H.createElement("path",xv({},Pt(r,!0),{className:f,d:y,role:"img"}))};function lh(e){"@babel/helpers - typeof";return lh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},lh(e)}function yv(){return yv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},yv.apply(this,arguments)}function EP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function IP(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?EP(Object(r),!0).forEach(function(n){Zoe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):EP(Object(r)).forEac
6977h(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Zoe(e,t,r){return t=Qoe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Qoe(e){var t=ele(e,"string");return lh(t)=="symbol"?t:t+""}function ele(e,t){if(lh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(lh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var OP={curveBasisClosed:EQ,curveBasisOpen:IQ,curveBasis:TQ,curveBumpX:gQ,curveBumpY:xQ,curveLinearClosed:OQ,curveLinear:_x,curveMonotoneX:RQ,curveMonotoneY:DQ,curveNatural:MQ,curveStep:LQ,curveStepAfter:FQ,curveStepBefore:$Q},Ff=function(t){return t.x===+t.x&&t.y===+t.y},Gd=function(t){return t.x},Kd=function(t){return t.y},tle=function(t,r){if(Kt(t))return t;var n="curve".concat(Hg(t));return(n==="curveMonotone"||n==="curveBump")&&r?OP["".concat(n).concat(r==="vertical"?"Y":"X")]:OP[n]||_x},nle=function(t){var r=t.type,n=r===void 0?"linear":r,s=t.points,i=s===void 0?[]:s,o=t.baseLine,l=t.layout,c=t.connectNulls,u=c===void 0?!1:c,d=tle(n,l),p=u?i.filter(function(g){return Ff(g)}):i,h;if(Array.isArray(o)){var f=u?o.filter(function(g){return Ff(g)}):o,x=p.map(function(g,y){return IP(IP({},g),{},{base:f[y]})});return l==="vertical"?h=Tf().y(Kd).x1(Gd).x0(function(g){return g.base.x}):h=Tf().x(Gd).y1(Kd).y0(function(g){return g.base.y}),h.defined(Ff).curve(d),h(x)}return l==="vertical"&&Oe(o)?h=Tf().y(Kd).x1(Gd).x0(o):Oe(o)?h=Tf().x(Gd).y1(Kd).y0(o):h=OO().x(Gd).y(Kd),h.defined(Ff).curve(d),h(p)},rc=function(t){var r=t.className,n=t.points,s=t.path,i=t.pathRef;if((!n||!n.length)&&!s)return null;var o=n&&n.length?nle(t):s;return m.createElement("path",yv({},Pt(t,!1),Fm(t),{className:fn("recharts-curve",r),d:o,ref:i}))},rle=Object.getOwnPropertyNames,sle=Object.getOwnPropertySymbols,ale=Object.prototype.hasOwnProperty;function RP(e,t){return function(n,s,i){return e(n,s,i)&&t(n,s,i)}}function Bf(e){return function(r,n,s){if(!r||!n||typeof r!="object"||typeof n!="object")return e(r,n,s);var i=s.cache,o=i.get(r),l=i.get(n);if(o&&l)return o===n&&l===r;i.set(r,n),i.set(n,r);var c=e(r,n,s);return i.delete(r),i.delete(n),c}}function DP(e){return rle(e).concat(sle(e))}var ile=Object.hasOwn||function(e,t){return ale.call(e,t)};function Ac(e,t){return e===t||!e&&!t&&e!==e&&t!==t}var ole="__v",lle="__o",cle="_owner",MP=Object.getOwnPropertyDescriptor,LP=Object.keys;function ule(e,t,r){var n=e.length;if(t.length!==n)return!1;for(;n-- >0;)if(!r.equals(e[n],t[n],n,n,e,t,r))return!1;return!0}function dle(e,t){return Ac(e.getTime(),t.getTime())}function ple(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function hle(e,t){return e===t}function $P(e,t,r){var n=e.size;if(n!==t.size)return!1;if(!n)return!0;for(var s=new Array(n),i=e.entries(),o,l,c=0;(o=i.next())&&!o.done;){for(var u=t.entries(),d=!1,p=0;(l=u.next())&&!l.done;){if(s[p]){p++;continue}var h=o.value,f=l.value;if(r.equals(h[0],f[0],c,p,e,t,r)&&r.equals(h[1],f[1],h[0],f[0],e,t,r)){d=s[p]=!0;break}p++}if(!d)return!1;c++}return!0}var fle=Ac;function mle(e,t,r){var n=LP(e),s=n.length;if(LP(t).length!==s)return!1;for(;s-- >0;)if(!yR(e,t,r,n[s]))return!1;return!0}function Yd(e,t,r){var n=DP(e),s=n.length;if(DP(t).length!==s)return!1;for(var i,o,l;s-- >0;)if(i=n[s],!yR(e,t,r,i)||(o=MP(e,i),l=MP(t,i),(o||l)&&(!o||!l||o.configurable!==l.configurable||o.enumerable!==l.enumerable||o.writable!==l.writable)))return!1;return!0}function gle(e,t){return Ac(e.valueOf(),t.valueOf())}function xle(e,t){return e.source===t.source&&e.flags===t.flags}function FP(e,t,r){var n=e.size;if(n!==t.size)return!1;if(!n)return!0;for(var s=new Array(n),i=e.values(),o,l;(o=i.next())&&!o.done;){for(var c=t.values(),u=!1,d=0;(l=c.next())&&!l.done;){if(!s[d]&&r.equals(o.value,l.value,o.value,l.value,e,t,r)){u=s[d]=!0;break}d++}if(!u)return!1}return!0}function yle(e,t){var r=e.length;if(t.length!==r)return!1;for(;r-- >0;)if(e[r]!==t[r])return!1;return!0}function ble(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function yR(e,t,r,n){return(n===cle||n===lle||n===ole)&&(e.$$typeof||t.$$typeof)?!0:ile(t,n)&&r.equals(e[n],t[n],n,n,e,t,r)}var vle="[object Arguments]",wle="[object Boolean]",jle="[object Date]",Nle="[object Error]",kle="[object Map]",Sle="[object Number]",Cle="[object Object]",Ple="[object RegExp]",Ale="[object Set]",_le="[object String]",Tle="[object URL]",Ele=Array.isArray,BP=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,UP=Object.assign,Ile=Object.prototype.toString.call.bind(Object.prototype.toString);function Ole(e){var t=e.areArraysEqual,r=e.areDatesEqual,n=e.areErrorsEqual,s=e.areFunctionsEqual,i=e.areMapsEqual,o=e.areNumbersEqual,l=e.areObjectsEqual,c=e.arePrimitiveWrappersEqual,u=e.areRegExpsEqual,d=e.areSetsEqual,p=e.areTypedArraysEqual,h=e.areUrlsEqual;return function(x,g,y){if(x===g)return!0;
6977if(x==null||g==null)return!1;var b=typeof x;if(b!==typeof g)return!1;if(b!=="object")return b==="number"?o(x,g,y):b==="function"?s(x,g,y):!1;var v=x.constructor;if(v!==g.constructor)return!1;if(v===Object)return l(x,g,y);if(Ele(x))return t(x,g,y);if(BP!=null&&BP(x))return p(x,g,y);if(v===Date)return r(x,g,y);if(v===RegExp)return u(x,g,y);if(v===Map)return i(x,g,y);if(v===Set)return d(x,g,y);var k=Ile(x);return k===jle?r(x,g,y):k===Ple?u(x,g,y):k===kle?i(x,g,y):k===Ale?d(x,g,y):k===Cle?typeof x.then!="function"&&typeof g.then!="function"&&l(x,g,y):k===Tle?h(x,g,y):k===Nle?n(x,g,y):k===vle?l(x,g,y):k===wle||k===Sle||k===_le?c(x,g,y):!1}}function Rle(e){var t=e.circular,r=e.createCustomConfig,n=e.strict,s={areArraysEqual:n?Yd:ule,areDatesEqual:dle,areErrorsEqual:ple,areFunctionsEqual:hle,areMapsEqual:n?RP($P,Yd):$P,areNumbersEqual:fle,areObjectsEqual:n?Yd:mle,arePrimitiveWrappersEqual:gle,areRegExpsEqual:xle,areSetsEqual:n?RP(FP,Yd):FP,areTypedArraysEqual:n?Yd:yle,areUrlsEqual:ble};if(r&&(s=UP({},s,r(s))),t){var i=Bf(s.areArraysEqual),o=Bf(s.areMapsEqual),l=Bf(s.areObjectsEqual),c=Bf(s.areSetsEqual);s=UP({},s,{areArraysEqual:i,areMapsEqual:o,areObjectsEqual:l,areSetsEqual:c})}return s}function Dle(e){return function(t,r,n,s,i,o,l){return e(t,r,l)}}function Mle(e){var t=e.circular,r=e.comparator,n=e.createState,s=e.equals,i=e.strict;if(n)return function(c,u){var d=n(),p=d.cache,h=p===void 0?t?new WeakMap:void 0:p,f=d.meta;return r(c,u,{cache:h,equals:s,meta:f,strict:i})};if(t)return function(c,u){return r(c,u,{cache:new WeakMap,equals:s,meta:void 0,strict:i})};var o={cache:void 0,equals:s,meta:void 0,strict:i};return function(c,u){return r(c,u,o)}}var Lle=fl();fl({strict:!0});fl({circular:!0});fl({circular:!0,strict:!0});fl({createInternalComparator:function(){return Ac}});fl({strict:!0,createInternalComparator:function(){return Ac}});fl({circular:!0,createInternalComparator:function(){return Ac}});fl({circular:!0,createInternalComparator:function(){return Ac},strict:!0});function fl(e){e===void 0&&(e={});var t=e.circular,r=t===void 0?!1:t,n=e.createInternalComparator,s=e.createState,i=e.strict,o=i===void 0?!1:i,l=Rle(e),c=Ole(l),u=n?n(c):Dle(c);return Mle({circular:r,comparator:c,createState:s,equals:u,strict:o})}function $le(e){typeof requestAnimationFrame<"u"&&requestAnimationFrame(e)}function zP(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function s(i){r<0&&(r=i),i-r>t?(e(i),r=-1):$le(s)};requestAnimationFrame(n)}function bv(e){"@babel/helpers - typeof";return bv=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},bv(e)}function Fle(e){return qle(e)||zle(e)||Ule(e)||Ble()}function Ble(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6978In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ule(e,t){if(e){if(typeof e=="string")return qP(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return qP(e,t)}}function qP(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function zle(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function qle(e){if(Array.isArray(e))return e}function Hle(){var e={},t=function(){return null},r=!1,n=function s(i){if(!r){if(Array.isArray(i)){if(!i.length)return;var o=i,l=Fle(o),c=l[0],u=l.slice(1);if(typeof c=="number"){zP(s.bind(null,u),c);return}s(c),zP(s.bind(null,u));return}bv(i)==="object"&&(e=i,t(e)),typeof i=="function"&&i()}};return{stop:function(){r=!0},start:function(i){r=!1,n(i)},subscribe:function(i){return t=i,function(){t=function(){return null}}}}}function ch(e){"@babel/helpers - typeof";return ch=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ch(e)}function HP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function WP(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};
vendor: 27,990 bytes, lines 6978-6995
6978t%2?HP(Object(r),!0).forEach(function(n){bR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):HP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function bR(e,t,r){return t=Wle(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Wle(e){var t=Vle(e,"string");return ch(t)==="symbol"?t:String(t)}function Vle(e,t){if(ch(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ch(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Gle=function(t,r){return[Object.keys(t),Object.keys(r)].reduce(function(n,s){return n.filter(function(i){return s.includes(i)})})},Kle=function(t){return t},Yle=function(t){return t.replace(/([A-Z])/g,function(r){return"-".concat(r.toLowerCase())})},Sp=function(t,r){return Object.keys(r).reduce(function(n,s){return WP(WP({},n),{},bR({},s,t(s,r[s])))},{})},VP=function(t,r,n){return t.map(function(s){return"".concat(Yle(s)," ").concat(r,"ms ").concat(n)}).join(",")};function Jle(e,t){return Qle(e)||Zle(e,t)||vR(e,t)||Xle()}function Xle(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6979In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zle(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function Qle(e){if(Array.isArray(e))return e}function ece(e){return rce(e)||nce(e)||vR(e)||tce()}function tce(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6980In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vR(e,t){if(e){if(typeof e=="string")return vv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return vv(e,t)}}function nce(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function rce(e){if(Array.isArray(e))return vv(e)}function vv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var hg=1e-4,wR=function(t,r){return[0,3*t,3*r-6*t,3*t-3*r+1]},jR=function(t,r){return t.map(function(n,s){return n*Math.pow(r,s)}).reduce(function(n,s){return n+s})},GP=function(t,r){return function(n){var s=wR(t,r);return jR(s,n)}},sce=function(t,r){return function(n){var s=wR(t,r),i=[].concat(ece(s.map(function(o,l){return o*l}).slice(1)),[0]);return jR(i,n)}},KP=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var s=r[0],i=r[1],o=r[2],l=r[3];if(r.length===1)switch(r[0]){case"linear":s=0,i=0,o=1,l=1;break;case"ease":s=.25,i=.1,o=.25,l=1;break;case"ease-in":s=.42,i=0,o=1,l=1;break;case"ease-out":s=.42,i=0,o=.58,l=1;break;case"ease-in-out":s=0,i=0,o=.58,l=1;break;default:{var c=r[0].split("(");if(c[0]==="cubic-bezier"&&c[1].split(")")[0].split(",").length===4){var u=c[1].split(")")[0].split(",").map(function(y){return parseFloat(y)}),d=Jle(u,4);s=d[0],i=d[1],o=d[2],l=d[3]}}}var p=GP(s,o),h=GP(i,l),f=sce(s,o),x=function(b){return b>1?1:b<0?0:b},g=function(b){for(var v=b>1?1:b,k=v,N=0;N<8;++N){var j=p(k)-v,w=f(k);if(Math.abs(j-v)<hg||w<hg)return h(k);k=x(k-j/w)}return h(k)};return g.isStepper=!1,g},ace=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,s=t.damping,i=s===void 0?8:s,o=t.dt,l=o===void 0?17:o,c=function(d,p,h){var f=-(d-p)*n,x=h*i,g=h+(f-x)*l/1e3,y=h*l/1e3+d;return Math.abs(y-p)<hg&&Math.abs(g)<hg?[p,0]:[y,g]};return c.isStepper=!0,c.dt=l,c},ice=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var s=r[0];if(typeof s=="string")switch(s){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return KP(s);case"spring":return ace();default:if(s.split("(")[0]==="cubic-bezier")return KP(s)}return typeof s=="function"?s:null};function uh(e){"@babel/helpers - typeof";return uh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},uh(e)}function YP(e){return cce(e)||lce(e)||NR(e)||oce()}function oce(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6981In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function lce(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function cce(e){if(Array.isArray(e))return jv(e)}function JP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function _s(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?JP(Object(r),!0).forEach(function(n){wv(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):JP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function wv(e,t,r){return t=uce(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function uce(e){var t=dce(e,"string");return uh(t)==="symbol"?t:String(t)}function dce(e,t){if(uh(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(uh(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function pce(e,t){return mce(e)||fce(e,t)||NR(e,t)||hce()}function hce(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6982In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NR(e,t){if(e){if(typeof e=="string")return jv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jv(e,t)}}function jv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function fce(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function mce(e){if(Array.isArray(e))return e}var fg=function(t,r,n){return t+(r-t)*n},Nv=function(t){var r=t.from,n=t.to;return r!==n},gce=function e(t,r,n){var s=Sp(function(i,o){if(Nv(o)){var l=t(o.from,o.to,o.velocity),c=pce(l,2),u=c[0],d=c[1];return _s(_s({},o),{},{from:u,velocity:d})}return o},r);return n<1?Sp(function(i,o){return Nv(o)?_s(_s({},o),{},{velocity:fg(o.velocity,s[i].velocity,n),from:fg(o.from,s[i].from,n)}):o},r):e(t,s,n-1)};const xce=function(e,t,r,n,s){var i=Gle(e,t),o=i.reduce(function(y,b){return _s(_s({},y),{},wv({},b,[e[b],t[b]]))},{}),l=i.reduce(function(y,b){return _s(_s({},y),{},wv({},b,{from:e[b],velocity:0,to:t[b]}))},{}),c=-1,u,d,p=function(){return null},h=function(){return Sp(function(b,v){return v.from},l)},f=function(){return!Object.values(l).filter(Nv).length},x=function(b){u||(u=b);var v=b-u,k=v/r.dt;l=gce(r,l,k),s(_s(_s(_s({},e),t),h())),u=b,f()||(c=requestAnimationFrame(p))},g=function(b){d||(d=b);var v=(b-d)/n,k=Sp(function(j,w){return fg.apply(void 0,YP(w).concat([r(v)]))},o);if(s(_s(_s(_s({},e),t),k)),v<1)c=requestAnimationFrame(p);else{var N=Sp(function(j,w){return fg.apply(void 0,YP(w).concat([r(1)]))},o);s(_s(_s(_s({},e),t),N))}};return p=r.isStepper?x:g,function(){return requestAnimationFrame(p),function(){cancelAnimationFrame(c)}}};function $u(e){"@babel/helpers - typeof";return $u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$u(e)}var yce=["children","begin","duration","attributeName","easing","isActive","steps","from","to","canBegin","onAnimationEnd","shouldReAnimate","onAnimationReStart"];function bce(e,t){if(e==null)return{};var r=vce(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function vce(e,t){if(e==null)return{};var r={},n=Object.keys(e),s,i;for(i=0;i<n.length;i++)s=n[i],!(t.indexOf(s)>=0)&&(r[s]=e[s]);return r}function vb(e){return kce(e)||Nce(e)||jce(e)||wce()}function wce(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6983In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jce(e,t){if(e){if(typeof e=="string")return kv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return kv(e,t)}}function Nce(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function kce(e){if(Array.isArray(e))return kv(e)}function kv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function XP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Ga(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?XP(Object(r),!0).forEach(function(n){ip(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):XP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function ip(e,t,r){return t=kR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Sce(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Cce(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,kR(n.key),n)}}function Pce(e,t,r){return t&&Cce(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function kR(e){var t=Ace(e,"string");return $u(t)==="symbol"?t:String(t)}function Ace(e,t){if($u(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if($u(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function _ce(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Sv(e,t)}function Sv(e,t){return Sv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Sv(e,t)}function Tce(e){var t=Ece();return function(){var n=mg(e),s;if(t){var i=mg(this).constructor;s=Reflect.construct(n,arguments,i)}else s=n.apply(this,arguments);return Cv(this,s)}}function Cv(e,t){if(t&&($u(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Pv(e)}function Pv(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ece(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function mg(e){return mg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},mg(e)}var di=function(e){_ce(r,e);var t=Tce(r);function r(n,s){var i;Sce(this,r),i=t.call(this,n,s);var o=i.props,l=o.isActive,c=o.attributeName,u=o.from,d=o.to,p=o.steps,h=o.children,f=o.duration;if(i.handleStyleChange=i.handleStyleChange.bind(Pv(i)),i.changeStyle=i.changeStyle.bind(Pv(i)),!l||f<=0)return i.state={style:{}},typeof h=="function"&&(i.state={style:d}),Cv(i);if(p&&p.length)i.state={style:p[0].style};else if(u){if(typeof h=="function")return i.state={style:u},Cv(i);i.state={style:c?ip({},c,u):u}}else i.state={style:{}};return i}return Pce(r,[{key:"componentDidMount",value:function(){var s=this.props,i=s.isActive,o=s.canBegin;this.mounted=!0,!(!i||!o)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(s){var i=this.props,o=i.isActive,l=i.canBegin,c=i.attributeName,u=i.shouldReAnimate,d=i.to,p=i.from,h=this.state.style;if(l){if(!o){var f={style:c?ip({},c,d):d};this.state&&h&&(c&&h[c]!==d||!c&&h!==d)&&this.setState(f);return}if(!(Lle(s.to,d)&&s.canBegin&&s.isActive)){var x=!s.canBegin||!s.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var g=x||u?p:s.to;if(this.state&&h){var y={style:c?ip({},c,g):g};(c&&h[c]!==g||!c&&h!==g)&&this.setState(y)}this.runAnimation(Ga(Ga({},this.props),{},{from:g,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var s=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),s&&s()}},{key:"handleStyleChange",value:function(s){this.changeStyle(s)}},{key:"changeStyle",value:function(s){this.mounted&&this.setState({style:s})}},{key:"runJSAnimation",value:function(s){var i=this,o=s.from,l=s.to,c=s.duration,u=s.easing,d=s.begin,p=s.onAnimationEnd,h=s.onAnimationStart,f=xce(o,l,ice(u),c,this.changeStyle),x=function(){i.stopJSAnimation=f()};this.manager.start([h,d,x,c,p])}},{key:"runStepAnimation",value:function(s){var i=this,o=s.steps,l=s.begin,c=s.onAnimationStart,u=o[0],d=u.style,p=u.duration,h=p===void 0?0:p,f=function(g,y,b){if(b===0)return g;var v=y.duration,k=y.easing,N=k===void 0?"ease":k,j=y.style,w=y.properties,S=y.onAnimationEnd,T=b>0?o[b-1]:y,C=w||Object.keys(j);if(typeof N=="function"||N==="spring")return[].concat(vb(g),[i.runJSAnimation.bind(i,{from:T.style,to:j,duration:v,easing:N}),v]);var A=VP(C,v,N),P=Ga(Ga(Ga({},T.style),j),{},{transition:A});return[].concat(vb(g),[P,v,S]).filter(Kle)};return this.manager.start([c].concat(vb(o.reduce(f,[d,Math.max(h,l)])),[s.onAnimationEnd]))}},{key:"runAnimation",value:function(s){this.manager||(this.manager=Hle());var i=s.begin,o=s.duration,l=s.attributeName,c=s.to,u=s.easing,d=s.onAnimationStart,p=s.onAnimationEnd,h=s.steps,f=s.children,x=this.manager;if(this.unSubscribe=x.subscribe(this.handleStyleChange),typeof u=="function"||typeof f=="function"||u==="spring"){this.runJSAnimation(s);return}if(h.length>1){this.runStepAnimation(s);return}var g=l?ip({},l,c):c,y=VP(Object.keys(g),o,u);x.start([d,i,Ga(Ga({},g),{},{transition:y}),o,p])}},{key:"render",value:function(){var s=this.props,i=s.children;s.begin;var o=s.duration;s.attributeName,s.easing;var l=s.isActive;s.steps,s.from,s.to,s.canBegin,s.onAnimationEnd,s.shouldReAnimate,s.onAnimationReStart;var c=bce(s,yce),u=m.Children.count(i),d=this.state.style;if(typeof i=="function")return i(d);if(!l||u===0||o<=0)return i;var p=function(f){var x=f.props,g=x.style,y=g===void 0?{}:g,b=x.className,v=m.cloneElement(f,Ga(Ga({},c),{},{style:Ga(Ga({},y),d),className:b}));return v};return u===1?p(m.Children.only(i)):H.createElement("div",null,m.Children.map(i,function(h){return p(h)}))}}]),r}(m.PureComponent);di.displayName="Animate";di.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};di.propTypes={from:rr.oneOfType([rr.object,rr.string]),to:rr.oneOfType([rr.object,rr.string]),attributeName:rr.string,duration:rr.number,begin:rr.number,easing:rr.oneOfType([rr.string,rr.func]),steps:rr.arrayOf(rr.shape({duration:rr.number.isRequired,style:rr.object.isRequired,easing:rr.oneOfType([rr.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),rr.func]),properties:rr.arrayOf("string"),onAnimationEnd:rr.func})),children:rr.oneOfType([rr.node,rr.func]),isActive:rr.bool,canBegin:rr.bool,onAnimationEnd:rr.func,shouldReAnimate:rr.bool,onAnimationStart:rr.func,onAnimationReStart:rr.func};function dh(e){"@babel/helpers - typeof";return dh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},dh(e)}function gg(){return gg=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},gg.apply(this,arguments)}function Ice(e,t){return Mce(e)||Dce(e,t)||Rce(e,t)||Oce()}function Oce(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6984In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Rce(e,t){if(e){if(typeof e=="string")return ZP(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ZP(e,t)}}function ZP(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Dce(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function Mce(e){if(Array.isArray(e))return e}function QP(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function eA(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?QP(Object(r),!0).forEach(function(n){Lce(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):QP(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Lce(e,t,r){return t=$ce(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function $ce(e){var t=Fce(e,"string");return dh(t)=="symbol"?t:t+""}function Fce(e,t){if(dh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(dh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var tA=function(t,r,n,s,i){var o=Math.min(Math.abs(n)/2,Math.abs(s)/2),l=s>=0?1:-1,c=n>=0?1:-1,u=s>=0&&n>=0||s<0&&n<0?1:0,d;if(o>0&&i instanceof Array){for(var p=[0,0,0,0],h=0,f=4;h<f;h++)p[h]=i[h]>o?o:i[h];d="M".concat(t,",").concat(r+l*p[0]),p[0]>0&&(d+="A ".concat(p[0],",").concat(p[0],",0,0,").concat(u,",").concat(t+c*p[0],",").concat(r)),d+="L ".concat(t+n-c*p[1],",").concat(r),p[1]>0&&(d+="A ".concat(p[1],",").concat(p[1],",0,0,").concat(u,`,
6985        `).concat(t+n,",").concat(r+l*p[1])),d+="L ".concat(t+n,",").concat(r+s-l*p[2]),p[2]>0&&(d+="A ".concat(p[2],",").concat(p[2],",0,0,").concat(u,`,
6986        `).concat(t+n-c*p[2],",").concat(r+s)),d+="L ".concat(t+c*p[3],",").concat(r+s),p[3]>0&&(d+="A ".concat(p[3],",").concat(p[3],",0,0,").concat(u,`,
6987        `).concat(t,",").concat(r+s-l*p[3])),d+="Z"}else if(o>0&&i===+i&&i>0){var x=Math.min(o,i);d="M ".concat(t,",").concat(r+l*x,`
6988            A `).concat(x,",").concat(x,",0,0,").concat(u,",").concat(t+c*x,",").concat(r,`
6989            L `).concat(t+n-c*x,",").concat(r,`
6990            A `).concat(x,",").concat(x,",0,0,").concat(u,",").concat(t+n,",").concat(r+l*x,`
6991            L `).concat(t+n,",").concat(r+s-l*x,`
6992            A `).concat(x,",").concat(x,",0,0,").concat(u,",").concat(t+n-c*x,",").concat(r+s,`
6993            L `).concat(t+c*x,",").concat(r+s,`
6994            A `).concat(x,",").concat(x,",0,0,").concat(u,",").concat(t,",").concat(r+s-l*x," Z")}else d="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(s," h ").concat(-n," Z");return d},Bce=function(t,r){if(!t||!r)return!1;var n=t.x,s=t.y,i=r.x,o=r.y,l=r.width,c=r.height;if(Math.abs(l)>0&&Math.abs(c)>0){var u=Math.min(i,i+l),d=Math.max(i,i+l),p=Math.min(o,o+c),h=Math.max(o,o+c);return n>=u&&n<=d&&s>=p&&s<=h}return!1},Uce={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Ij=function(t){var r=eA(eA({},Uce),t),n=m.useRef(),s=m.useState(-1),i=Ice(s,2),o=i[0],l=i[1];m.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var N=n.current.getTotalLength();N&&l(N)}catch{}},[]);var c=r.x,u=r.y,d=r.width,p=r.height,h=r.radius,f=r.className,x=r.animationEasing,g=r.animationDuration,y=r.animationBegin,b=r.isAnimationActive,v=r.isUpdateAnimationActive;if(c!==+c||u!==+u||d!==+d||p!==+p||d===0||p===0)return null;var k=fn("recharts-rectangle",f);return v?H.createElement(di,{canBegin:o>0,from:{width:d,height:p,x:c,y:u},to:{width:d,height:p,x:c,y:u},duration:g,animationEasing:x,isActive:v},function(N){var j=N.width,w=N.height,S=N.x,T=N.y;return H.createElement(di,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:g,isActive:b,easing:x},H.createElement("path",gg({},Pt(r,!0),{className:k,d:tA(S,T,j,w,h),ref:n})))}):H.createElement("path",gg({},Pt(r,!0),{className:k,d:tA(c,u,d,p,h)}))},zce=["points","className","baseLinePoints","connectNulls"];function lu(){return lu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},lu.apply(this,arguments)}function qce(e,t){if(e==null)return{};var r=Hce(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Hce(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function nA(e){return Kce(e)||Gce(e)||Vce(e)||Wce()}function Wce(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
6995In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Vce(e,t){if(e){if(typeof e=="string")return Av(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Av(e,t)}}function Gce(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Kce(e){if(Array.isArray(e))return Av(e)}function Av(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var rA=function(t){return t&&t.x===+t.x&&t.y===+t.y},Yce=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){rA(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),rA(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},Cp=function(t,r){var n=Yce(t);r&&(n=[n.reduce(function(i,o){return[].concat(nA(i),nA(o))},[])]);var s=n.map(function(i){return i.reduce(function(o,l,c){return"".concat(o).concat(c===0?"M":"L").concat(l.x,",").concat(l.y)},"")}).join("");return n.length===1?"".concat(s,"Z"):s},Jce=function(t,r,n){var s=Cp(t,n);return"".concat(s.slice(-1)==="Z"?s.slice(0,-1):s,"L").concat(Cp(r.reverse(),n).slice(1))},Xce=function(t){var r=t.points,n=t.className,s=t.baseLinePoints,i=t.connectNulls,o=qce(t,zce);if(!r||!r.length)return null;var l=fn("recharts-polygon",n);if(s&&s.length){var c=o.stroke&&o.stroke!=="none",u=Jce(r,s,i);return H.createElement("g",{className:l},H.createElement("path",lu({},Pt(o,!0),{fill:u.slice(-1)==="Z"?o.fill:"none",stroke:"none",d:u})),c?H.createElement("path",lu({},Pt(o,!0),{fill:"none",d:Cp(r,i)})):null,c?H.createElement("path",lu({},Pt(o,!0),{fill:"none",d:Cp(s,i)})):null)}var d=Cp(r,i);return H.createElement("path",lu({},Pt(o,!0),{fill:d.slice(-1)==="Z"?o.fill:"none",className:l,d}))};function _v(){return _v=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_v.apply(this,arguments)}var Uh=function(t){var r=t.cx,n=t.cy,s=t.r,i=t.className,o=fn("recharts-dot",i);return r===+r&&n===+n&&s===+s?m.createElement("circle",_v({},Pt(t,!1),Fm(t),{className:o,cx:r,cy:n,r:s})):null};function ph(e){"@babel/helpers - typeof";return ph=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ph(e)}var Zce=["x","y","top","left","width","height","className"];function Tv(){return Tv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Tv.apply(this,arguments)}function sA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Qce(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?sA(Object(r),!0).forEach(function(n){eue(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):sA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function eue(e,t,r){return t=tue(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function tue(e){var t=nue(e,"string");return ph(t)=="symbol"?t:t+""}function nue(e,t){if(ph(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ph(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function rue(e,t){if(e==null)return{};var r=sue(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function sue(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var aue=function(t,r,n,s,i,o){return"M".concat(t,",").concat(i,"v").concat(s,"M").concat(o,",").concat(r,"h").concat(n)},iue=function(t){var r=t.x,n=r===void 0?0:r,s=t.y,i=s===void 0?0:s,o=t.to
6995p,l=o===void 0?0:o,c=t.left,u=c===void 0?0:c,d=t.width,p=d===void 0?0:d,h=t.height,f=h===void 0?0:h,x=t.className,g=rue(t,Zce),y=Qce({x:n,y:i,top:l,left:u,width:p,height:f},g);return!Oe(n)||!Oe(i)||!Oe(p)||!Oe(f)||!Oe(l)||!Oe(u)?null:H.createElement("path",Tv({},Pt(y,!0),{className:fn("recharts-cross",x),d:aue(n,i,p,f,l,u)}))},oue=Fx,lue=F4,cue=jc;function uue(e,t){return e&&e.length?oue(e,cue(t),lue):void 0}var due=uue;const pue=zs(due);var hue=Fx,fue=jc,mue=B4;function gue(e,t){return e&&e.length?hue(e,fue(t),mue):void 0}var xue=gue;const yue=zs(xue);var bue=["cx","cy","angle","ticks","axisLine"],vue=["ticks","tick","angle","tickFormatter","stroke"];function Fu(e){"@babel/helpers - typeof";return Fu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fu(e)}function Pp(){return Pp=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Pp.apply(this,arguments)}function aA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function _l(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?aA(Object(r),!0).forEach(function(n){qx(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):aA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function iA(e,t){if(e==null)return{};var r=wue(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function wue(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function jue(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function oA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,CR(n.key),n)}}function Nue(e,t,r){return t&&oA(e.prototype,t),r&&oA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function kue(e,t,r){return t=xg(t),Sue(e,SR()?Reflect.construct(t,r||[],xg(e).constructor):t.apply(e,r))}function Sue(e,t){if(t&&(Fu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Cue(e)}function Cue(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function SR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(SR=function(){return!!e})()}function xg(e){return xg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},xg(e)}function Pue(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ev(e,t)}function Ev(e,t){return Ev=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Ev(e,t)}function qx(e,t,r){return t=CR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function CR(e){var t=Aue(e,"string");return Fu(t)=="symbol"?t:t+""}function Aue(e,t){if(Fu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Fu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Hx=function(e){function t(){return jue(this,t),kue(this,t,arguments)}return Pue(t,e),Nue(t,[{key:"getTickValueCoord",value:function(n){var s=n.coordinate,i=this.props,o=i.angle,l=i.cx,c=i.cy;return _r(l,c,s,o)}},{key:"getTickTextAnchor",value:function(){var n=this.props.orientation,s;switch(n){case"left":s="end";break;case"right":s="start";break;default:s="middle";break}return s}},{key:"getViewBox",value:function(){var n=this.props,s=n.cx,i=n.cy,o=n.angle,l=n.ticks,c=pue(l,function(d){return d.coordinate||0}),u=yue(l,function(d){return d.coordinate||0});return{cx:s,cy:i,startAngle:o,endAngle:o,innerRadius:u.coordinate||0,outerRadius:c.coordinate||0}}},{key:"renderAxisLine",value:function(){var n=this.props,s=n.cx,i=n.cy,o=n.angle,l=n.ticks,c=n.axisLine,u=iA(n,bue),d=l.reduce(function(x,g){return[Math.min(x[0],g.co
vendor: 25,269 bytes, lines 6995-6996
6995ordinate),Math.max(x[1],g.coordinate)]},[1/0,-1/0]),p=_r(s,i,d[0],o),h=_r(s,i,d[1],o),f=_l(_l(_l({},Pt(u,!1)),{},{fill:"none"},Pt(c,!1)),{},{x1:p.x,y1:p.y,x2:h.x,y2:h.y});return H.createElement("line",Pp({className:"recharts-polar-radius-axis-line"},f))}},{key:"renderTicks",value:function(){var n=this,s=this.props,i=s.ticks,o=s.tick,l=s.angle,c=s.tickFormatter,u=s.stroke,d=iA(s,vue),p=this.getTickTextAnchor(),h=Pt(d,!1),f=Pt(o,!1),x=i.map(function(g,y){var b=n.getTickValueCoord(g),v=_l(_l(_l(_l({textAnchor:p,transform:"rotate(".concat(90-l,", ").concat(b.x,", ").concat(b.y,")")},h),{},{stroke:"none",fill:u},f),{},{index:y},b),{},{payload:g});return H.createElement(Tn,Pp({className:fn("recharts-polar-radius-axis-tick",fR(o)),key:"tick-".concat(g.coordinate)},gc(n.props,g,y)),t.renderTickItem(o,v,c?c(g.value,y):g.value))});return H.createElement(Tn,{className:"recharts-polar-radius-axis-ticks"},x)}},{key:"render",value:function(){var n=this.props,s=n.ticks,i=n.axisLine,o=n.tick;return!s||!s.length?null:H.createElement(Tn,{className:fn("recharts-polar-radius-axis",this.props.className)},i&&this.renderAxisLine(),o&&this.renderTicks(),Ss.renderCallByParent(this.props,this.getViewBox()))}}],[{key:"renderTickItem",value:function(n,s,i){var o;return H.isValidElement(n)?o=H.cloneElement(n,s):Kt(n)?o=n(s):o=H.createElement(xc,Pp({},s,{className:"recharts-polar-radius-axis-tick-value"}),i),o}}])}(m.PureComponent);qx(Hx,"displayName","PolarRadiusAxis");qx(Hx,"axisType","radiusAxis");qx(Hx,"defaultProps",{type:"number",radiusAxisId:0,cx:0,cy:0,angle:0,orientation:"right",stroke:"#ccc",axisLine:!0,tick:!0,tickCount:5,allowDataOverflow:!1,scale:"auto",allowDuplicatedCategory:!0});function Bu(e){"@babel/helpers - typeof";return Bu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bu(e)}function Fl(){return Fl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Fl.apply(this,arguments)}function lA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Tl(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?lA(Object(r),!0).forEach(function(n){Wx(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):lA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function _ue(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function cA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,AR(n.key),n)}}function Tue(e,t,r){return t&&cA(e.prototype,t),r&&cA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Eue(e,t,r){return t=yg(t),Iue(e,PR()?Reflect.construct(t,r||[],yg(e).constructor):t.apply(e,r))}function Iue(e,t){if(t&&(Bu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Oue(e)}function Oue(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function PR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(PR=function(){return!!e})()}function yg(e){return yg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},yg(e)}function Rue(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Iv(e,t)}function Iv(e,t){return Iv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Iv(e,t)}function Wx(e,t,r){return t=AR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function AR(e){var t=Due(e,"string");return Bu(t)=="symbol"?t:t+""}function Due(e,t){if(Bu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Bu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Mue=Math.PI/180,uA=1e-5,Vx=function(e){function t(){return _ue(this,t),Eue(this,t,arguments)}return Rue(t,e),Tue(t,[{key:"getTickLineCoord",value:function(n){var s=this.props,i=s.cx,o=s.cy,l=s.radius,c=s.orientation,u=s.tickSize,d=u||8,p=_r(i,o,l,n.coordinate),h=_r(i,o,l+(c==="inner"?-1:1)*d,n.coordinate);return{x1:p.x,y1:p.y,x2:h.x,y2:h.y}}},{key:"getTickTextAnchor",value:function(n){var s=this.props.orientation,i=Math.cos(-n.coordinate*Mue),o;return i>uA?o=s==="outer"?"start":"end":i<-uA?o=s==="outer"?"end":"start":o="middle",o}},{key:"renderAxisLine",value:function(){var n=this.props,s=n.cx,i=n.cy,o=n.radius,l=n.axisLine,c=n.axisLineType,u=Tl(Tl({},Pt(this.props,!1)),{},{fill:"none"},Pt(l,!1));if(c==="circle")return H.createElement(Uh,Fl({className:"recharts-polar-angle-axis-line"},u,{cx:s,cy:i,r:o}));var d=this.props.ticks,p=d.map(function(h){return _r(s,i,o,h.coordinate)});return H.createElement(Xce,Fl({className:"recharts-polar-angle-axis-line"},u,{points:p}))}},{key:"renderTicks",value:function(){var n=this,s=this.props,i=s.ticks,o=s.tick,l=s.tickLine,c=s.tickFormatter,u=s.stroke,d=Pt(this.props,!1),p=Pt(o,!1),h=Tl(Tl({},d),{},{fill:"none"},Pt(l,!1)),f=i.map(function(x,g){var y=n.getTickLineCoord(x),b=n.getTickTextAnchor(x),v=Tl(Tl(Tl({textAnchor:b},d),{},{stroke:"none",fill:u},p),{},{index:g,payload:x,x:y.x2,y:y.y2});return H.createElement(Tn,Fl({className:fn("recharts-polar-angle-axis-tick",fR(o)),key:"tick-".concat(x.coordinate)},gc(n.props,x,g)),l&&H.createElement("line",Fl({className:"recharts-polar-angle-axis-tick-line"},h,y)),o&&t.renderTickItem(o,v,c?c(x.value,g):x.value))});return H.createElement(Tn,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var n=this.props,s=n.ticks,i=n.radius,o=n.axisLine;return i<=0||!s||!s.length?null:H.createElement(Tn,{className:fn("recharts-polar-angle-axis",this.props.className)},o&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,s,i){var o;return H.isValidElement(n)?o=H.cloneElement(n,s):Kt(n)?o=n(s):o=H.createElement(xc,Fl({},s,{className:"recharts-polar-angle-axis-tick-value"}),i),o}}])}(m.PureComponent);Wx(Vx,"displayName","PolarAngleAxis");Wx(Vx,"axisType","angleAxis");Wx(Vx,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});function hh(e){"@babel/helpers - typeof";return hh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hh(e)}function bg(){return bg=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},bg.apply(this,arguments)}function Lue(e,t){return Uue(e)||Bue(e,t)||Fue(e,t)||$ue()}function $ue(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6996In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Fue(e,t){if(e){if(typeof e=="string")return dA(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return dA(e,t)}}function dA(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Bue(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function Uue(e){if(Array.isArray(e))return e}function pA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function hA(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pA(Object(r),!0).forEach(function(n){zue(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function zue(e,t,r){return t=que(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function que(e){var t=Hue(e,"string");return hh(t)=="symbol"?t:t+""}function Hue(e,t){if(hh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(hh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var fA=function(t,r,n,s,i){var o=n-s,l;return l="M ".concat(t,",").concat(r),l+="L ".concat(t+n,",").concat(r),l+="L ".concat(t+n-o/2,",").concat(r+i),l+="L ".concat(t+n-o/2-s,",").concat(r+i),l+="L ".concat(t,",").concat(r," Z"),l},Wue={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Vue=function(t){var r=hA(hA({},Wue),t),n=m.useRef(),s=m.useState(-1),i=Lue(s,2),o=i[0],l=i[1];m.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var k=n.current.getTotalLength();k&&l(k)}catch{}},[]);var c=r.x,u=r.y,d=r.upperWidth,p=r.lowerWidth,h=r.height,f=r.className,x=r.animationEasing,g=r.animationDuration,y=r.animationBegin,b=r.isUpdateAnimationActive;if(c!==+c||u!==+u||d!==+d||p!==+p||h!==+h||d===0&&p===0||h===0)return null;var v=fn("recharts-trapezoid",f);return b?H.createElement(di,{canBegin:o>0,from:{upperWidth:0,lowerWidth:0,height:h,x:c,y:u},to:{upperWidth:d,lowerWidth:p,height:h,x:c,y:u},duration:g,animationEasing:x,isActive:b},function(k){var N=k.upperWidth,j=k.lowerWidth,w=k.height,S=k.x,T=k.y;return H.createElement(di,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:g,easing:x},H.createElement("path",bg({},Pt(r,!0),{className:v,d:fA(S,T,N,j,w),ref:n})))}):H.createElement("g",null,H.createElement("path",bg({},Pt(r,!0),{className:v,d:fA(c,u,d,p,h)})))},Gue=["option","shapeType","propTransformer","activeClassName","isActive"];function fh(e){"@babel/helpers - typeof";return fh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},fh(e)}function Kue(e,t){if(e==null)return{};var r=Yue(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Yue(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function mA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function vg(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?mA(Object(r),!0).forEach(function(n){Jue(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):mA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Jue(e,t,r){return t=Xue(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Xue(e){var t=Zue(e,"string");return fh(t)=="symbol"?t:t+""}function Zue(e,t){if(fh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(fh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Que(e,t){return vg(vg({},t),e)}function ede(e,t){return e==="symbols"}function gA(e){var t=e.shapeType,r=e.elementProps;switch(t){case"rectangle":return H.createElement(Ij,r);case"trapezoid":return H.createElement(Vue,r);case"sector":return H.createElement(xR,r);case"symbols":if(ede(t))return H.createElement(rj,r);break;default:return null}}function tde(e){return m.isValidElement(e)?e.props:e}function _R(e){var t=e.option,r=e.shapeType,n=e.propTransformer,s=n===void 0?Que:n,i=e.activeClassName,o=i===void 0?"recharts-active-shape":i,l=e.isActive,c=Kue(e,Gue),u;if(m.isValidElement(t))u=m.cloneElement(t,vg(vg({},c),tde(t)));else if(Kt(t))u=t(c);else if(a$(t)&&!i$(t)){var d=s(t,c);u=H.createElement(gA,{shapeType:r,elementProps:d})}else{var p=c;u=H.createElement(gA,{shapeType:r,elementProps:p})}return l?H.createElement(Tn,{className:o},u):u}function Gx(e,t){return t!=null&&"trapezoids"in e.props}function Kx(e,t){return t!=null&&"sectors"in e.props}function mh(e,t){return t!=null&&"points"in e.props}function nde(e,t){var r,n,s=e.x===(t==null||(r=t.labelViewBox)===null||r===void 0?void 0:r.x)||e.x===t.x,i=e.y===(t==null||(n=t.labelViewBox)===null||n===void 0?void 0:n.y)||e.y===t.y;return s&&i}function rde(e,t){var r=e.endAngle===t.endAngle,n=e.startAngle===t.startAngle;return r&&n}function sde(e,t){var r=e.x===t.x,n=e.y===t.y,s=e.z===t.z;return r&&n&&s}function ade(e,t){var r;return Gx(e,t)?r=nde:Kx(e,t)?r=rde:mh(e,t)&&(r=sde),r}function ide(e,t){var r;return Gx(e,t)?r="trapezoids":Kx(e,t)?r="sectors":mh(e,t)&&(r="points"),r}function ode(e,t){if(Gx(e,t)){var r;return(r=t.tooltipPayload)===null||r===void 0||(r=r[0])===null||r===void 0||(r=r.payload)===null||r===void 0?void 0:r.payload}if(Kx(e,t)){var n;return(n=t.tooltipPayload)===null||n===void 0||(n=n[0])===null||n===void 0||(n=n.payload)===null||n===void 0?void 0:n.payload}return mh(e,t)?t.payload:{}}function lde(e){var t=e.activeTooltipItem,r=e.graphicalItem,n=e.itemData,s=ide(r,t),i=ode(r,t),o=n.filter(function(c,u){var d=oc(i,c),p=r.props[s].filter(function(x){var g=ade(r,t);return g(x,t)}),h=r.props[s].indexOf(p[p.length-1]),f=u===h;return d&&f}),l=n.indexOf(o[o.length-1]);return l}var pm;function Uu(e){"@babel/helpers - typeof";return Uu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Uu(e)}function cu(){return cu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},cu.apply(this,arguments)}function xA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Sr(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?xA(Object(r),!0).forEach(function(n){Ra(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):xA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cde(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function yA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ER(n.key),n)}}function ude(e,t,r){return t&&yA(e.prototype,t),r&&yA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function dde(e,t,r){return t=wg(t),pde(e,TR()?Reflect.construct(t,r||[],wg(e).constructor):t.apply(e,r))}function pde(e,t){if(t&&(Uu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hde(e)}function hde(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function TR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(TR=function(){return!!e})()}function wg(e){return wg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},wg(e)}function fde(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ov(e,t)}function Ov(e,t){return Ov=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Ov(e,t)}function Ra(e,t,r){return t=ER(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ER(e){var t=mde(e,"string");return Uu(t)=="symbol"?t:t+""}function mde(e,t){if(Uu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Uu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var wo=function(e){function t(r){var n;return cde(this,t),n=dde(this,t,[r]),Ra(n,"pieRef",null),Ra(n,"sectorRefs",[]),Ra(n,"id",Sc("recharts-pie-")),Ra(n,"handleAnimationEnd",function(){var s=n.props.onAnimationEnd;n.setState({isAnimationFinished:!0}),Kt(s)&&s()}),Ra(n,"handleAnimationStart",function(){var s=n.props.onAnimationStart;n.setState({isAnimationFinished:!1}),Kt(s)&&s()}),n.state={isAnimationFinished:!r.isAnimationActive,prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,sectorToFocus:0},n}return fde(t,e),ude(t,[{key:"isActiveIndex",value:function(n){var s=this.props.activeIndex;return Array.isArray(s)?s.indexOf(n)!==-1:n===s}},{key:"hasActiveIndex",value:function(){var n=this.props.activeIndex;return Array.isArray(n)?n.length!==0:n||n===0}},{key:"renderLabels",value:function(n){var s=this.props.isAnimationActive;if(s&&!this.state.isAnimationFinished)return null;var i=this.props,o=i.label,l=i.labelLine,c=i.dataKey,u=i.valueKey,d=Pt(this.props,!1),p=Pt(o,!1),h=Pt(l,!1),f=o&&o.offsetRadius||20,x=n.map(function(g,y){var b=(g.startAngle+g.endAngle)/2,v=_r(g.cx,g.cy,g.outerRadius+f,b),k=Sr(Sr(Sr(Sr({},d),g),{},{stroke:"none"},p),{},{index:y,textAnchor:t.getTextAnchor(v.x,g.cx)},v),N=Sr(Sr(Sr(Sr({},d),g),{},{fill:"none",stroke:g.fill},h),{},{index:y,points:[_r(g.cx,g.cy,g.outerRadius,b),v]}),j=c;return an(c)&&an(u)?j="value":an(c)&&(j=u),H.createElement(Tn,{key:"label-".concat(g.startAngle,"-").concat(g.endAngle,"-").concat(g.midAngle,"-").concat(y)},l&&t.renderLabelLineItem(l,N,"line"),t.renderLabelItem(o,k,es(g,j)))});return H.createElement(Tn,{className:"recharts-pie-labels"},x)}},{key:"renderSectorsStatically",value:function(n){var s=this,i=this.props,o=i.activeShape,l=i.blendStroke,c=i.inactiveShape;return n.map(function(u,d){if((u==null?void 0:u.startAngle)===0&&(u==null?void 0:u.endAngle)===0&&n.length!==1)return null;var p=s.isActiveIndex(d),h=c&&s.hasActiveIndex()?c:null,f=p?o:h,x=Sr(Sr({},u),{},{stroke:l?u.fill:u.stroke,tabIndex:-1});return H.createElement(Tn,cu({ref:function(y){y&&!s.sectorRefs.includes(y)&&s.sectorRefs.push(y)},tabIndex:-1,className:"recharts-pie-sector"},gc(s.props,u,d),{key:"sector-".concat(u==null?void 0:u.startAngle,"-").concat(u==null?void 0:u.endAngle,"-").concat(u.midAngle,"-").concat(d)}),H.createElement(_R,cu({option:f,isActive:p,shapeType:"sector"},x)))})}},{key:"renderSectorsWithAnimation",value:function(){var n=this,s=this.props,i=s.sectors,o=s.isAnimationActive,l=s.animationBegin,c=s.animationDuration,u=s.animationEasing,d=s.animationId,p=this.state,h=p.prevSectors,f=p.prevIsAnimationActive;return H.createElement(di,{begin:l,duration:c,isActive:o,easing:u,from:{t:0},to:{t:1},key:"pie-".concat(d,"-").concat(f),onAnimationStart:this.handleAnimationStart,onAnimationEnd:this.handleAnimationEnd},function(x){var g=x.t,y=[],b=i&&i[0],v=b.startAngle;return i.forEach(function(k,N){var j=h&&h[N],w=N>0?ba(k,"paddingAngle",0):0;if(j){var S=ms(j.endAngle-j.startAngle,k.endAngle-k.startAngle),T=Sr(Sr({},k),{},{startAngle:v+w,endAngle:v+S(g)+w});y.push(T),v=T.endAngle}else{var C=k.endAngle,A=k.startAngle,P=ms(0,C-A),E=P(g),_=Sr(Sr({},k),{},{startAngle:v+w,endAngle:v+E+w});y.push(_),v=_.endAngle}}),H.createElement(Tn,null,n.renderSectorsStatically(y))})}},{key:"attachKeyboardHandlers",value:function(n){var s=this;n.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var o=++s.state.sectorToFocus%s.sectorRefs.length;s.sectorRefs[o].focus(),s.setState({sectorToFocus:o});break}case"ArrowRight":{var l=--s.state.sectorToFocus<0?s.sectorRefs.length-1:s.state.sectorToFocus%s.sectorRefs.length;s.sectorRefs[l].focus(),s.setState({sectorToFocus:l});break}case"Escape":{s.sectorRefs[s.state.sectorToFocus].blur(),s.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,s=n.sectors,i=n.isAnimationActive,o=this.state.prevSectors;return i&&s&&s.length&&(!o||!oc(o,s))?this.renderSectorsWithAnimation():this.renderSectorsStatically(s)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,s=this.props,i=s.hide,o=s.sectors,l=s.className,c=s.label,u=s.cx,d=s.cy,p=s.innerRadius,h=s.outerRadius,f=s.isAnimationActive,x=this.state.isAnimationFinished;if(i||!o||!o.length||!Oe(u)||!Oe(d)||!Oe(p)||!Oe(h))return null;var g=fn("recharts-pie",l);return H.createElement(Tn,{tabIndex:this.props.rootTabIndex,className:g,ref:function(b){n.pieRef=b}},this.renderSectors(),c&&this.renderLabels(o),Ss.renderCallByParent(this.props,null,!1),(!f||x)&&Ti.renderCallByParent(this.props,o,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,s){return s.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==s.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:s.curSectors,isAnimationFinished:!0}:n.sectors!==s.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,s){return n>s?"start":n<s?"end":"middle"}},{key:"renderLabelLineItem",value:function(n,s,i){if(H.isValidElement(n))return H.cloneElement(n,s);if(Kt(n))return n(s);var o=fn("recharts-pie-label-line",typeof n!="boolean"?n.className:"");return H.createElement(rc,cu({},s,{key:i,type:"linear",className:o}))}},{key:"renderLabelItem",value:function(n,s,i){if(H.isValidElement(n))return H.cloneElement(n,s);var o=i;if(Kt(n)&&(o=n(s),H.isValidElement(o)))return o;var l=fn("recharts-pie-label-text",typeof n!="boolean"&&!Kt(n)?n.className:"");return H.createElement(xc,cu({},s,{alignmentBaseline:"middle",className:l}),o)}}])}(m.PureComponent);pm=wo;Ra(wo,"displayName","Pie");Ra(wo,"defaultProps",{stroke:"#fff",fill:"#808080",legendType:"rect",cx:"50%",cy:"50%",startAngle:0,endAngle:360,innerRadius:0,outerRadius:"80%",paddingAngle:0,labelLine:!0,hide:!1,minAngle:0,isAnimationActive:!ci.isSsr,animationBegin:400,animationDuration:1500,animationEasing:"ease",nameKey:"name",blendStroke:!1,rootTabIndex:0});Ra(wo,"parseDeltaAngle",function(e,t){var r=Js(t-e),n=Math.min(Math.abs(t-e),360);return r*n});Ra(wo,"getRealPieData",function(e){var t=e.data,r=e.children,n=Pt(e,!1),s=wa(r,Ix);return t&&t.length?t.map(function(i,o){return Sr(Sr(Sr({payload:i},n),i),s&&s[o]&&s[o].props)}):s&&s.length?s.map(function(i){return Sr(Sr({},n),i.props)}):[]});Ra(wo,"parseCoordinateOfPie",function(e,t){var r=t.top,n=t.left,s=t.width,i=t.height,o=hR(s,i),l=n+Xs(e.cx,s,s/2),c=r+Xs(e.cy,i,i/2),u=Xs(e.innerRadius,o,0),d=Xs(e.outerRadius,o,o*.8),p=e.maxRadius||Math.sqrt(s*s+i*i)/2;return{cx:l,cy:c,innerRadius:u,outerRadius:d,maxRadius:p}});Ra(wo,"getComposedData",function(e){var t=e.item,r=e.offset,n=t.type.defaultProps!==void 0?Sr(Sr({},t.type.defaultProps),t.props):t.props,s=pm.getRealPieData(n);if(!s||!s.length)return null;var i=n.cornerRadius,o=n.startAngle,l=n.endAngle,c=n.paddingAngle,u=n.dataKey,d=n.nameKey,p=n.valueKey,h=n.tooltipType,f=Math.abs(n.minAngle),x=pm.parseCoordinateOfPie(n,r),g=pm.parseDeltaAngle(o,l),y=Math.abs(g),b=u;an(u)&&an(p)?(li(!1,`Use "dataKey" to specify the value of pie,
6997      the props "valueKey" will be deprecated in 1.1.0`),b="value"):an(u)&&(li(!1,`Use "dataKey" to specify the value of pie,
6998      the props "valueKey" will be deprecated in 1.1.0`),b=p);var v=s.filter(function(T){return es(T,b,0)!==0}).length,k=(y>=360?v:v-1)*c,N=y-v*f-k,j=s.reduce(function(T,C){var A=es(C,b,0);return T+(Oe(A)?A:0)},0),w;if(j>0){var S;w=s.map(function(T,C){var A=es(T,b,0),P=es(T,d,C),E=(Oe(A)?A:0)/j,_;C?_=S.endAngle+Js(g)*c*(A!==0?1:0):_=o;var I=_+Js(g)*((A!==0?f:0)+E*N),D=(_+I)/2,M=(x.innerRadius+x.outerRadius)/2,B=[{name:P,value:A,payload:T,dataKey:b,type:h}],$=_r(x.cx,x.cy,M,D);return S=Sr(Sr(Sr({percent:E,cornerRadius:i,name:P,tooltipPayload:B,midAngle:D,middleRadius:M,tooltipPosition:$},T),x),{},{value:es(T,b),startAngle:_,endAngle:I,payload:T,paddingAngle:Js(g)*c}),S})}return Sr(Sr({},x),{},{sectors:w,data:s})});var gde=Math.ceil,xde=Math.max;function yde(e,t,r,n){for(var s=-1,i=xde(gde((t-e)/(r||1)),0),o=Array(i);i--;)o[n?i:++s]=e,e+=r;return o}var bde=yde,vde=bde,wde=jw,wb=o$;function jde(e){return function(t,r,n){return n&&typeof n!="number"&&wde(t,r,n)&&(r=n=void 0),t=wb(t),r===void 0?(r=t,t=0):r=wb(r),n=n===void 0?t<r?1:-1:wb(n),vde(t,r,n,e)}}var Nde=jde,kde=Nde,Sde=kde(),Cde=Sde;const jg=zs(Cde);function gh(e){"@babel/helpers - typeof";return gh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},gh(e)}function bA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function vA(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?bA(Object(r),!0).forEach(function(n){IR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function IR(e,t,r){return t=Pde(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Pde(e){var t=Ade(e,"string");return gh(t)=="symbol"?t:t+""}function Ade(e,t){if(gh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(gh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var _de=["Webkit","Moz","O","ms"],Tde=function(t,r){var n=t.replace(/(\w)/,function(i){return i.toUpperCase()}),s=_de.reduce(function(i,o){return vA(vA({},i),{},IR({},o+n,r))},{});return s[t]=r,s};function zu(e){"@babel/helpers - typeof";return zu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zu(e)}function Ng(){return Ng=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ng.apply(this,arguments)}function wA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function jb(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?wA(Object(r),!0).forEach(function(n){ha(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Ede(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function jA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,RR(n.key),n)}}function Ide(e,t,r){return t&&jA(e.prototype,t),r&&jA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ode(e,t,r){return t=kg(t),Rde(e,OR()?Reflect.construct(t,r||[],kg(e).constructor):t.apply(e,r))}function Rde(e,t){if(t&&(zu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Dde(e)}function Dde(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function OR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(OR=function(){return!!e})()}function kg(e){return kg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},kg(e)}function Mde(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Rv(e,t)}function Rv(e,t){return Rv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Rv(e,t)}function ha(e,t,r){return t=RR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RR(e){var t=Lde(e,"string");return zu(t)=="symbol"?t:t+""}function Lde(e,t){if(zu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(zu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var $de=function(t){var r=t.data,n=t.startIndex,s=t.endIndex,i=t.x,o=t.width,l=t.travellerWidth;if(!r||!r.length)return{};var c=r.length,u=Np().domain(jg(0,c)).range([i,i+o-l]),d=u.domain().map(function(p){return u(p)});return{isTextActive:!1,isSlideMoving:!1,isTravellerMoving:!1,isTravellerFocused:!1,startX:u(n),endX:u(s),scale:u,scaleValues:d}},NA=function(t){return t.changedTouches&&!!t.changedTouches.length},qu=function(e){function t(r){var n;return Ede(this,t),n=Ode(this,t,[r]),ha(n,"handleDrag",function(s){n.leaveTimer&&(clearTimeout(n.leaveTimer),n.leaveTimer=null),n.state.isTravellerMoving?n.handleTravellerMove(s):n.state.isSlideMoving&&n.handleSlideDrag(s)}),ha(n,"handleTouchMove",function(s){s.changedTouches!=null&&s.changedTouches.length>0&&n.handleDrag(s.changedTouches[0])}),ha(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var s=n.props,i=s.endIndex,o=s.onDragEnd,l=s.startIndex;o==null||o({endIndex:i,startIndex:l})}),n.detachDragEndListener()}),ha(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),ha(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),ha(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),ha(n,"handleSlideDragStart",function(s){var i=NA(s)?s.changedTouches[0]:s;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}
vendor: 4,730 bytes, line 6998
6998return Mde(t,e),Ide(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var s=n.startX,i=n.endX,o=this.state.scaleValues,l=this.props,c=l.gap,u=l.data,d=u.length-1,p=Math.min(s,i),h=Math.max(s,i),f=t.getIndexInRange(o,p),x=t.getIndexInRange(o,h);return{startIndex:f-f%c,endIndex:x===d?d:x-x%c}}},{key:"getTextOfTick",value:function(n){var s=this.props,i=s.data,o=s.tickFormatter,l=s.dataKey,c=es(i[n],l,n);return Kt(o)?o(c,n):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var s=this.state,i=s.slideMoveStartX,o=s.startX,l=s.endX,c=this.props,u=c.x,d=c.width,p=c.travellerWidth,h=c.startIndex,f=c.endIndex,x=c.onChange,g=n.pageX-i;g>0?g=Math.min(g,u+d-p-l,u+d-p-o):g<0&&(g=Math.max(g,u-o,u-l));var y=this.getIndex({startX:o+g,endX:l+g});(y.startIndex!==h||y.endIndex!==f)&&x&&x(y),this.setState({startX:o+g,endX:l+g,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,s){var i=NA(s)?s.changedTouches[0]:s;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var s=this.state,i=s.brushMoveStartX,o=s.movingTravellerId,l=s.endX,c=s.startX,u=this.state[o],d=this.props,p=d.x,h=d.width,f=d.travellerWidth,x=d.onChange,g=d.gap,y=d.data,b={startX:this.state.startX,endX:this.state.endX},v=n.pageX-i;v>0?v=Math.min(v,p+h-f-u):v<0&&(v=Math.max(v,p-u)),b[o]=u+v;var k=this.getIndex(b),N=k.startIndex,j=k.endIndex,w=function(){var T=y.length-1;return o==="startX"&&(l>c?N%g===0:j%g===0)||l<c&&j===T||o==="endX"&&(l>c?j%g===0:N%g===0)||l>c&&j===T};this.setState(ha(ha({},o,u+v),"brushMoveStartX",n.pageX),function(){x&&w()&&x(k)})}},{key:"handleTravellerMoveKeyboard",value:function(n,s){var i=this,o=this.state,l=o.scaleValues,c=o.startX,u=o.endX,d=this.state[s],p=l.indexOf(d);if(p!==-1){var h=p+n;if(!(h===-1||h>=l.length)){var f=l[h];s==="startX"&&f>=u||s==="endX"&&f<=c||this.setState(ha({},s,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,s=n.x,i=n.y,o=n.width,l=n.height,c=n.fill,u=n.stroke;return H.createElement("rect",{stroke:u,fill:c,x:s,y:i,width:o,height:l})}},{key:"renderPanorama",value:function(){var n=this.props,s=n.x,i=n.y,o=n.width,l=n.height,c=n.data,u=n.children,d=n.padding,p=m.Children.only(u);return p?H.cloneElement(p,{x:s,y:i,width:o,height:l,margin:d,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,s){var i,o,l=this,c=this.props,u=c.y,d=c.travellerWidth,p=c.height,h=c.traveller,f=c.ariaLabel,x=c.data,g=c.startIndex,y=c.endIndex,b=Math.max(n,this.props.x),v=jb(jb({},Pt(this.props,!1)),{},{x:b,y:u,width:d,height:p}),k=f||"Min value: ".concat((i=x[g])===null||i===void 0?void 0:i.name,", Max value: ").concat((o=x[y])===null||o===void 0?void 0:o.name);return H.createElement(Tn,{tabIndex:0,role:"slider","aria-label":k,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[s],onTouchStart:this.travellerDragStartHandlers[s],onKeyDown:function(j){["ArrowLeft","ArrowRight"].includes(j.key)&&(j.preventDefault(),j.stopPropagation(),l.handleTravellerMoveKeyboard(j.key==="ArrowRight"?1:-1,s))},onFocus:function(){l.setState({isTravellerFocused:!0})},onBlur:function(){l.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(h,v))}},{key:"renderSlide",value:function(n,s){var i=this.props,o=i.y,l=i.height,c=i.stroke,u=i.travellerWidth,d=Math.min(n,s)+u,p=Math.max(Math.abs(s-n)-u,0);return H.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:d,y:o,width:p,height:l})}},{key:"renderText",value:function(){var n=this.props,s=n.startIndex,i=n.endIndex,o=n.y,l=n.height,c=n.travellerWidth,u=n.stroke,d=this.state,p=d.startX,h=d.endX,f=5,x={pointerEvents:"none",fill:u};
6998return H.createElement(Tn,{className:"recharts-brush-texts"},H.createElement(xc,Ng({textAnchor:"end",verticalAnchor:"middle",x:Math.min(p,h)-f,y:o+l/2},x),this.getTextOfTick(s)),H.createElement(xc,Ng({textAnchor:"start",verticalAnchor:"middle",x:Math.max(p,h)+c+f,y:o+l/2},x),this.getTextOfTick(i)))}},{key:"render",value:function(){var n=this.props,s=n.data,i=n.className,o=n.children,l=n.x,c=n.y,u=n.width,d=n.height,p=n.alwaysShowText,h=this.state,f=h.startX,x=h.endX,g=h.isTextActive,y=h.isSlideMoving,b=h.isTravellerMoving,v=h.isTravellerFocused;if(!s||!s.length||!Oe(l)||!Oe(c)||!Oe(u)||!Oe(d)||u<=0||d<=0)return null;var k=fn("recharts-brush",i),N=H.Children.count(o)===1,j=Tde("userSelect","none");return H.createElement(Tn,{className:k,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:j},this.renderBackground(),N&&this.renderPanorama(),this.renderSlide(f,x),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(x,"endX"),(g||y||b||v||p)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var s=n.x,i=n.y,o=n.width,l=n.height,c=n.stroke,u=Math.floor(i+l/2)-1;return H.createElement(H.Fragment,null,H.createElement("rect",{x:s,y:i,width:o,height:l,fill:c,stroke:"none"}),H.createElement("line",{x1:s+1,y1:u,x2:s+o-1,y2:u,fill:"none",stroke:"#fff"}),H.createElement("line",{x1:s+1,y1:u+2,x2:s+o-1,y2:u+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,s){var i;return H.isValidElement(n)?i=H.cloneElement(n,s):Kt(n)?i=n(s):i=t.renderDefaultTraveller(s),i}},{key:"getDerivedStateFromProps",value:function(n,s){var i=n.data,o=n.width,l=n.x,c=n.travellerWidth,u=n.updateId,d=n.startIndex,p=n.endIndex;if(i!==s.prevData||u!==s.prevUpdateId)return jb({prevData:i,prevTravellerWidth:c,prevUpdateId:u,prevX:l,prevWidth:o},i&&i.length?$de({data:i,width:o,x:l,travellerWidth:c,startIndex:d,endIndex:p}):{scale:null,scaleValues:null});if(s.scale&&(o!==s.prevWidth||l!==s.prevX||c!==s.prevTravellerWidth)){s.scale.range([l,l+o-c]);var h=s.scale.domain().map(function(f){return s.scale(f)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:u,prevX:l,prevWidth:o,startX:s.scale(n.startIndex),endX:s.scale(n.endIndex),scaleValues:h}}return null}},{key:"getIndexInRange",value:function(n,s){for(var i=n.length,o=0,l=i-1;l-o>1;){var c=Math.floor((o+l)/2);n[c]>s?l=c:o=c}return s>=n[l]?l:o}}])}(m.PureComponent);ha(qu,"displayName","Brush");ha(qu,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var Ei=function(t,r){var n=t.alwaysShow,s=t.ifOverflow;return n&&(s="extendDomain"),s===r},Fde=c$,Bde=l$,Ude=jc;function zde(e,t){var r={};return t=Ude(t),Bde(e,function(n,s,i){Fde(r,s,t(n,s,i))}),r}var qde=zde;const Hde=zs(qde);function Wde(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}var Vde=Wde,Gde=V_;function Kde(e,t){var r=!0;return Gde(e,function(n,s,i){return r=!!t(n,s,i),r}),r}var Yde=Kde,Jde=Vde,Xde=Yde,Zde=jc,Qde=ww,epe=jw;function tpe(e,t,r){var n=Qde(e)?Jde:Xde;return r&&epe(e,t,r)&&(t=void 0),n(e,Zde(t))}var npe=tpe;const DR=zs(npe);var rpe=["x","y"];function xh(e){"@babel/helpers - typeof";return xh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xh(e)}function Dv(){return Dv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Dv.apply(this,arguments)}function kA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Jd(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?kA(Object(r),!0).forEach(function(n){spe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):kA(Object(r)).forEac
vendor: 119,273 bytes, lines 6998-7003
6998h(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function spe(e,t,r){return t=ape(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ape(e){var t=ipe(e,"string");return xh(t)=="symbol"?t:t+""}function ipe(e,t){if(xh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(xh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ope(e,t){if(e==null)return{};var r=lpe(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function lpe(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function cpe(e,t){var r=e.x,n=e.y,s=ope(e,rpe),i="".concat(r),o=parseInt(i,10),l="".concat(n),c=parseInt(l,10),u="".concat(t.height||s.height),d=parseInt(u,10),p="".concat(t.width||s.width),h=parseInt(p,10);return Jd(Jd(Jd(Jd(Jd({},t),s),o?{x:o}:{}),c?{y:c}:{}),{},{height:d,width:h,name:t.name,radius:t.radius})}function SA(e){return H.createElement(_R,Dv({shapeType:"rectangle",propTransformer:cpe,activeClassName:"recharts-active-bar"},e))}var upe=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,s){if(typeof t=="number")return t;var i=Oe(n)||VZ(n);return i?t(n,s):(i||bc(),r)}},dpe=["value","background"],MR;function Hu(e){"@babel/helpers - typeof";return Hu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hu(e)}function ppe(e,t){if(e==null)return{};var r=hpe(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function hpe(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Sg(){return Sg=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Sg.apply(this,arguments)}function CA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function as(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?CA(Object(r),!0).forEach(function(n){Ko(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):CA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function fpe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function PA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,$R(n.key),n)}}function mpe(e,t,r){return t&&PA(e.prototype,t),r&&PA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function gpe(e,t,r){return t=Cg(t),xpe(e,LR()?Reflect.construct(t,r||[],Cg(e).constructor):t.apply(e,r))}function xpe(e,t){if(t&&(Hu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ype(e)}function ype(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function LR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(LR=function(){return!!e})()}function Cg(e){return Cg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Cg(e)}function bpe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mv(e,t)}function Mv(e,t){return Mv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Mv(e,t)}function Ko(e,t,r){return t=$R(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function $R(e){var t=vpe(e,"string");return Hu(t)=="symbol"?t:t+""}function vpe(e,t){if(Hu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Hu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var _c=function(e){function t(){var r;fpe(this,t);for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];return r=gpe(this,t,[].concat(s)),Ko(r,"state",{isAnimationFinished:!1}),Ko(r,"id",Sc("recharts-bar-")),Ko(r,"handleAnimationEnd",function(){var o=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),o&&o()}),Ko(r,"handleAnimationStart",function(){var o=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),o&&o()}),r}return bpe(t,e),mpe(t,[{key:"renderRectanglesStatically",value:function(n){var s=this,i=this.props,o=i.shape,l=i.dataKey,c=i.activeIndex,u=i.activeBar,d=Pt(this.props,!1);return n&&n.map(function(p,h){var f=h===c,x=f?u:o,g=as(as(as({},d),p),{},{isActive:f,option:x,index:h,dataKey:l,onAnimationStart:s.handleAnimationStart,onAnimationEnd:s.handleAnimationEnd});return H.createElement(Tn,Sg({className:"recharts-bar-rectangle"},gc(s.props,p,h),{key:"rectangle-".concat(p==null?void 0:p.x,"-").concat(p==null?void 0:p.y,"-").concat(p==null?void 0:p.value,"-").concat(h)}),H.createElement(SA,g))})}},{key:"renderRectanglesWithAnimation",value:function(){var n=this,s=this.props,i=s.data,o=s.layout,l=s.isAnimationActive,c=s.animationBegin,u=s.animationDuration,d=s.animationEasing,p=s.animationId,h=this.state.prevData;return H.createElement(di,{begin:c,duration:u,isActive:l,easing:d,from:{t:0},to:{t:1},key:"bar-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(f){var x=f.t,g=i.map(function(y,b){var v=h&&h[b];if(v){var k=ms(v.x,y.x),N=ms(v.y,y.y),j=ms(v.width,y.width),w=ms(v.height,y.height);return as(as({},y),{},{x:k(x),y:N(x),width:j(x),height:w(x)})}if(o==="horizontal"){var S=ms(0,y.height),T=S(x);return as(as({},y),{},{y:y.y+y.height-T,height:T})}var C=ms(0,y.width),A=C(x);return as(as({},y),{},{width:A})});return H.createElement(Tn,null,n.renderRectanglesStatically(g))})}},{key:"renderRectangles",value:function(){var n=this.props,s=n.data,i=n.isAnimationActive,o=this.state.prevData;return i&&s&&s.length&&(!o||!oc(o,s))?this.renderRectanglesWithAnimation():this.renderRectanglesStatically(s)}},{key:"renderBackground",value:function(){var n=this,s=this.props,i=s.data,o=s.dataKey,l=s.activeIndex,c=Pt(this.props.background,!1);return i.map(function(u,d){u.value;var p=u.background,h=ppe(u,dpe);if(!p)return null;var f=as(as(as(as(as({},h),{},{fill:"#eee"},p),c),gc(n.props,u,d)),{},{onAnimationStart:n.handleAnimationStart,onAnimationEnd:n.handleAnimationEnd,dataKey:o,index:d,className:"recharts-bar-background-rectangle"});return H.createElement(SA,Sg({key:"background-bar-".concat(d),option:n.props.background,isActive:d===l},f))})}},{key:"renderErrorBar",value:function(n,s){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,o=i.data,l=i.xAxis,c=i.yAxis,u=i.layout,d=i.children,p=wa(d,Bh);if(!p)return null;var h=u==="vertical"?o[0].height/2:o[0].width/2,f=function(y,b){var v=Array.isArray(y.value)?y.value[1]:y.value;return{x:y.x,y:y.y,value:v,errorVal:es(y,b)}},x={clipPath:n?"url(#clipPath-".concat(s,")"):null};return H.createElement(Tn,x,p.map(function(g){return H.cloneElement(g,{key:"error-bar-".concat(s,"-").concat(g.props.dataKey),data:o,xAxis:l,yAxis:c,layout:u,offset:h,dataPointFormatter:f})}))}},{key:"render",value:function(){var n=this.props,s=n.hide,i=n.data,o=n.className,l=n.xAxis,c=n.yAxis,u=n.left,d=n.top,p=n.width,h=n.height,f=n.isAnimationActive,x=n.background,g=n.id;if(s||!i||!i.length)return null;var y=this.state.isAnimationFinished,b=fn("recharts-bar",o),v=l&&l.allowDataOverflow,k=c&&c.allowDataOverflow,N=v||k,j=an(g)?this.id:g;return H.createElement(Tn,{className:b},v||k?H.createElement("defs",null,H.createElement("clipPath",{id:"clipPath-".concat(j)},H.createElement("rect",{x:v?u:u-p/2,y:k?d:d-h/2,width:v?p:p*2,height:k?h:h*2}))):null,H.createElement(Tn,{className:"recharts-bar-rectangles",clipPath:N?"url(#clipPath-".concat(j,")"):null},x?this.renderBackground():null,this.renderRectangles()),this.renderErrorBar(N,j),(!f||y)&&Ti.renderCallByParent(this.props,i))}}],[{key:"getDerivedStateFromProps",value:function(n,s){return n.animationId!==s.prevAnimationId?{prevAnimationId:n.animationId,curData:n.data,prevData:s.curData}:n.data!==s.curData?{curData:n.data}:null}}])}(m.PureComponent);MR=_c;Ko(_c,"displayName","Bar");Ko(_c,"defaultProps",{xAxisId:0,yAxisId:0,legendType:"rect",minPointSize:0,hide:!1,data:[],layout:"vertical",activeBar:!1,isAnimationActive:!ci.isSsr,animationBegin:0,animationDuration:400,animationEasing:"ease"});Ko(_c,"getComposedData",function(e){var t=e.props,r=e.item,n=e.barPosition,s=e.bandSize,i=e.xAxis,o=e.yAxis,l=e.xAxisTicks,c=e.yAxisTicks,u=e.stackedData,d=e.dataStartIndex,p=e.displayedData,h=e.offset,f=Hie(n,r);if(!f)return null;var x=t.layout,g=r.type.defaultProps,y=g!==void 0?as(as({},g),r.props):r.props,b=y.dataKey,v=y.children,k=y.minPointSize,N=x==="horizontal"?o:i,j=u?N.scale.domain():null,w=Xie({numericAxis:N}),S=wa(v,Ix),T=p.map(function(C,A){var P,E,_,I,D,M;u?P=Wie(u[d+A],j):(P=es(C,b),Array.isArray(P)||(P=[w,P]));var B=upe(k,MR.defaultProps.minPointSize)(P[1],A);if(x==="horizontal"){var $,K=[o.scale(P[0]),o.scale(P[1])],R=K[0],Y=K[1];E=yP({axis:i,ticks:l,bandSize:s,offset:f.offset,entry:C,index:A}),_=($=Y??R)!==null&&$!==void 0?$:void 0,I=f.size;var Z=R-Y;if(D=Number.isNaN(Z)?0:Z,M={x:E,y:o.y,width:I,height:o.height},Math.abs(B)>0&&Math.abs(D)<Math.abs(B)){var O=Js(D||B)*(Math.abs(B)-Math.abs(D));_-=O,D+=O}}else{var ne=[i.scale(P[0]),i.scale(P[1])],oe=ne[0],he=ne[1];if(E=oe,_=yP({axis:o,ticks:c,bandSize:s,offset:f.offset,entry:C,index:A}),I=he-oe,D=f.size,M={x:i.x,y:_,width:i.width,height:D},Math.abs(B)>0&&Math.abs(I)<Math.abs(B)){var ae=Js(I||B)*(Math.abs(B)-Math.abs(I));I+=ae}}return as(as(as({},C),{},{x:E,y:_,width:I,height:D,value:u?P:P[1],payload:C,background:M},S&&S[A]&&S[A].props),{},{tooltipPayload:[dR(r,C)],tooltipPosition:{x:E+I/2,y:_+D/2}})});return as({data:T,layout:x},h)});function yh(e){"@babel/helpers - typeof";return yh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},yh(e)}function wpe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function AA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,FR(n.key),n)}}function jpe(e,t,r){return t&&AA(e.prototype,t),r&&AA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _A(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Ja(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?_A(Object(r),!0).forEach(function(n){Yx(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_A(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Yx(e,t,r){return t=FR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function FR(e){var t=Npe(e,"string");return yh(t)=="symbol"?t:t+""}function Npe(e,t){if(yh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(yh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Oj=function(t,r,n,s,i){var o=t.width,l=t.height,c=t.layout,u=t.children,d=Object.keys(r),p={left:n.left,leftMirror:n.left,right:o-n.right,rightMirror:o-n.right,top:n.top,topMirror:n.top,bottom:l-n.bottom,bottomMirror:l-n.bottom},h=!!fa(u,_c);return d.reduce(function(f,x){var g=r[x],y=g.orientation,b=g.domain,v=g.padding,k=v===void 0?{}:v,N=g.mirror,j=g.reversed,w="".concat(y).concat(N?"Mirror":""),S,T,C,A,P;if(g.type==="number"&&(g.padding==="gap"||g.padding==="no-gap")){var E=b[1]-b[0],_=1/0,I=g.categoricalDomain.sort(YZ);if(I.forEach(function(ne,oe){oe>0&&(_=Math.min((ne||0)-(I[oe-1]||0),_))}),Number.isFinite(_)){var D=_/E,M=g.layout==="vertical"?n.height:n.width;if(g.padding==="gap"&&(S=D*M/2),g.padding==="no-gap"){var B=Xs(t.barCategoryGap,D*M),$=D*M/2;S=$-B-($-B)/M*B}}}s==="xAxis"?T=[n.left+(k.left||0)+(S||0),n.left+n.width-(k.right||0)-(S||0)]:s==="yAxis"?T=c==="horizontal"?[n.top+n.height-(k.bottom||0),n.top+(k.top||0)]:[n.top+(k.top||0)+(S||0),n.top+n.height-(k.bottom||0)-(S||0)]:T=g.range,j&&(T=[T[1],T[0]]);var K=oR(g,i,h),R=K.scale,Y=K.realScaleType;R.domain(b).range(T),lR(R);var Z=cR(R,Ja(Ja({},g),{},{realScaleType:Y}));s==="xAxis"?(P=y==="top"&&!N||y==="bottom"&&N,C=n.left,A=p[w]-P*g.height):s==="yAxis"&&(P=y==="left"&&!N||y==="right"&&N,C=p[w]-P*g.width,A=n.top);var O=Ja(Ja(Ja({},g),Z),{},{realScaleType:Y,x:C,y:A,scale:R,width:s==="xAxis"?n.width:g.width,height:s==="yAxis"?n.height:g.height});return O.bandSize=ug(O,Z),!g.hide&&s==="xAxis"?p[w]+=(P?-1:1)*O.height:g.hide||(p[w]+=(P?-1:1)*O.width),Ja(Ja({},f),{},Yx({},x,O))},{})},BR=function(t,r){var n=t.x,s=t.y,i=r.x,o=r.y;return{x:Math.min(n,i),y:Math.min(s,o),width:Math.abs(i-n),height:Math.abs(o-s)}},kpe=function(t){var r=t.x1,n=t.y1,s=t.x2,i=t.y2;return BR({x:r,y:n},{x:s,y:i})},UR=function(){function e(t){wpe(this,e),this.scale=t}return jpe(e,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=n.bandAware,i=n.position;if(r!==void 0){if(i)switch(i){case"start":return this.scale(r);case"middle":{var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+o}case"end":{var l=this.bandwidth?this.bandwidth():0;return this.scale(r)+l}default:return this.scale(r)}if(s){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),s=n[0],i=n[n.length-1];return s<=i?r>=s&&r<=i:r>=i&&r<=s}}],[{key:"create",value:function(r){return new e(r)}}])}();Yx(UR,"EPS",1e-4);var Rj=function(t){var r=Object.keys(t).reduce(function(n,s){return Ja(Ja({},n),{},Yx({},s,UR.create(t[s])))},{});return Ja(Ja({},r),{},{apply:function(s){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=i.bandAware,l=i.position;return Hde(s,function(c,u){return r[u].apply(c,{bandAware:o,position:l})})},isInRange:function(s){return DR(s,function(i,o){return r[o].isInRange(i)})}})};function Spe(e){return(e%180+180)%180}var Cpe=function(t){var r=t.width,n=t.height,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=Spe(s),o=i*Math.PI/180,l=Math.atan(n/r),c=o>l&&o<Math.PI-l?n/Math.sin(o):r/Math.cos(o);return Math.abs(c)},Ppe=u$(function(e){return{x:e.left,y:e.top,width:e.width,height:e.height}},function(e){return["l",e.left,"t",e.top,"w",e.width,"h",e.height].join("")}),Dj=m.createContext(void 0),Mj=m.createContext(void 0),zR=m.createContext(void 0),qR=m.createContext({}),HR=m.createContext(void 0),WR=m.createContext(0),VR=m.createContext(0),TA=function(t){var r=t.state,n=r.xAxisMap,s=r.yAxisMap,i=r.offset,o=t.clipPathId,l=t.children,c=t.width,u=t.height,d=Ppe(i);return H.createElement(Dj.Provider,{value:n},H.createElement(Mj.Provider,{value:s},H.createElement(qR.Provider,{value:i},H.createElement(zR.Provider,{value:d},H.createElement(HR.Provider,{value:o},H.createElement(WR.Provider,{value:u},H.createElement(VR.Provider,{value:c},l)))))))},Ape=function(){return m.useContext(HR)},GR=function(t){var r=m.useContext(Dj);r==null&&bc();var n=r[t];return n==null&&bc(),n},_pe=function(){var t=m.useContext(Dj);return qo(t)},Tpe=function(){var t=m.useContext(Mj),r=d$(t,function(n){return DR(n.domain,Number.isFinite)});return r||qo(t)},KR=function(t){var r=m.useContext(Mj);r==null&&bc();var n=r[t];return n==null&&bc(),n},Epe=function(){var t=m.useContext(zR);return t},Ipe=function(){return m.useContext(qR)},Lj=function(){return m.useContext(VR)},$j=function(){return m.useContext(WR)};function Wu(e){"@babel/helpers - typeof";return Wu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wu(e)}function Ope(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Rpe(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,JR(n.key),n)}}function Dpe(e,t,r){return t&&Rpe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Mpe(e,t,r){return t=Pg(t),Lpe(e,YR()?Reflect.construct(t,r||[],Pg(e).constructor):t.apply(e,r))}function Lpe(e,t){if(t&&(Wu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return $pe(e)}function $pe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function YR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(YR=function(){return!!e})()}function Pg(e){return Pg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Pg(e)}function Fpe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Lv(e,t)}function Lv(e,t){return Lv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Lv(e,t)}function EA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function IA(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?EA(Object(r),!0).forEach(function(n){Fj(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):EA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Fj(e,t,r){return t=JR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function JR(e){var t=Bpe(e,"string");return Wu(t)=="symbol"?t:t+""}function Bpe(e,t){if(Wu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Wu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Upe(e,t){return Wpe(e)||Hpe(e,t)||qpe(e,t)||zpe()}function zpe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
6999In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qpe(e,t){if(e){if(typeof e=="string")return OA(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return OA(e,t)}}function OA(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Hpe(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function Wpe(e){if(Array.isArray(e))return e}function $v(){return $v=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},$v.apply(this,arguments)}var Vpe=function(t,r){var n;return H.isValidElement(t)?n=H.cloneElement(t,r):Kt(t)?n=t(r):n=H.createElement("line",$v({},r,{className:"recharts-reference-line-line"})),n},Gpe=function(t,r,n,s,i,o,l,c,u){var d=i.x,p=i.y,h=i.width,f=i.height;if(n){var x=u.y,g=t.y.apply(x,{position:o});if(Ei(u,"discard")&&!t.y.isInRange(g))return null;var y=[{x:d+h,y:g},{x:d,y:g}];return c==="left"?y.reverse():y}if(r){var b=u.x,v=t.x.apply(b,{position:o});if(Ei(u,"discard")&&!t.x.isInRange(v))return null;var k=[{x:v,y:p+f},{x:v,y:p}];return l==="top"?k.reverse():k}if(s){var N=u.segment,j=N.map(function(w){return t.apply(w,{position:o})});return Ei(u,"discard")&&p$(j,function(w){return!t.isInRange(w)})?null:j}return null};function Kpe(e){var t=e.x,r=e.y,n=e.segment,s=e.xAxisId,i=e.yAxisId,o=e.shape,l=e.className,c=e.alwaysShow,u=Ape(),d=GR(s),p=KR(i),h=Epe();if(!u||!h)return null;li(c===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var f=Rj({x:d.scale,y:p.scale}),x=xs(t),g=xs(r),y=n&&n.length===2,b=Gpe(f,x,g,y,h,e.position,d.orientation,p.orientation,e);if(!b)return null;var v=Upe(b,2),k=v[0],N=k.x,j=k.y,w=v[1],S=w.x,T=w.y,C=Ei(e,"hidden")?"url(#".concat(u,")"):void 0,A=IA(IA({clipPath:C},Pt(e,!0)),{},{x1:N,y1:j,x2:S,y2:T});return H.createElement(Tn,{className:fn("recharts-reference-line",l)},Vpe(o,A),Ss.renderCallByParent(e,kpe({x1:N,y1:j,x2:S,y2:T})))}var Bj=function(e){function t(){return Ope(this,t),Mpe(this,t,arguments)}return Fpe(t,e),Dpe(t,[{key:"render",value:function(){return H.createElement(Kpe,this.props)}}])}(H.Component);Fj(Bj,"displayName","ReferenceLine");Fj(Bj,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle"});function Fv(){return Fv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Fv.apply(this,arguments)}function Vu(e){"@babel/helpers - typeof";return Vu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vu(e)}function RA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function DA(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?RA(Object(r),!0).forEach(function(n){Jx(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):RA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Ype(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Jpe(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ZR(n.key),n)}}function Xpe(e,t,r){return t&&Jpe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Zpe(e,t,r){return t=Ag(t),Qpe(e,XR()?Reflect.construct(t,r||[],Ag(e).constructor):t.apply(e,r))}function Qpe(e,t){if(t&&(Vu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ehe(e)}function ehe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function XR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(XR=function(){return!!e})()}function Ag(e){return Ag=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Ag(e)}function the(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Bv(e,t)}function Bv(e,t){return Bv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Bv(e,t)}function Jx(e,t,r){return t=ZR(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ZR(e){var t=nhe(e,"string");return Vu(t)=="symbol"?t:t+""}function nhe(e,t){if(Vu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Vu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var rhe=function(t){var r=t.x,n=t.y,s=t.xAxis,i=t.yAxis,o=Rj({x:s.scale,y:i.scale}),l=o.apply({x:r,y:n},{bandAware:!0});return Ei(t,"discard")&&!o.isInRange(l)?null:l},Xx=function(e){function t(){return Ype(this,t),Zpe(this,t,arguments)}return the(t,e),Xpe(t,[{key:"render",value:function(){var n=this.props,s=n.x,i=n.y,o=n.r,l=n.alwaysShow,c=n.clipPathId,u=xs(s),d=xs(i);if(li(l===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.'),!u||!d)return null;var p=rhe(this.props);if(!p)return null;var h=p.x,f=p.y,x=this.props,g=x.shape,y=x.className,b=Ei(this.props,"hidden")?"url(#".concat(c,")"):void 0,v=DA(DA({clipPath:b},Pt(this.props,!0)),{},{cx:h,cy:f});return H.createElement(Tn,{className:fn("recharts-reference-dot",y)},t.renderDot(g,v),Ss.renderCallByParent(this.props,{x:h-o,y:f-o,width:2*o,height:2*o}))}}])}(H.Component);Jx(Xx,"displayName","ReferenceDot");Jx(Xx,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#fff",stroke:"#ccc",fillOpacity:1,strokeWidth:1});Jx(Xx,"renderDot",function(e,t){var r;return H.isValidElement(e)?r=H.cloneElement(e,t):Kt(e)?r=e(t):r=H.createElement(Uh,Fv({},t,{cx:t.cx,cy:t.cy,className:"recharts-reference-dot-dot"})),r});function Uv(){return Uv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Uv.apply(this,arguments)}function Gu(e){"@babel/helpers - typeof";return Gu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Gu(e)}function MA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function LA(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?MA(Object(r),!0).forEach(function(n){Zx(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):MA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function she(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ahe(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,eD(n.key),n)}}function ihe(e,t,r){return t&&ahe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function ohe(e,t,r){return t=_g(t),lhe(e,QR()?Reflect.construct(t,r||[],_g(e).constructor):t.apply(e,r))}function lhe(e,t){if(t&&(Gu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return che(e)}function che(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function QR(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(QR=function(){return!!e})()}function _g(e){return _g=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},_g(e)}function uhe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&zv(e,t)}function zv(e,t){return zv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},zv(e,t)}function Zx(e,t,r){return t=eD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function eD(e){var t=dhe(e,"string");return Gu(t)=="symbol"?t:t+""}function dhe(e,t){if(Gu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Gu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var phe=function(t,r,n,s,i){var o=i.x1,l=i.x2,c=i.y1,u=i.y2,d=i.xAxis,p=i.yAxis;if(!d||!p)return null;var h=Rj({x:d.scale,y:p.scale}),f={x:t?h.x.apply(o,{position:"start"}):h.x.rangeMin,y:n?h.y.apply(c,{position:"start"}):h.y.rangeMin},x={x:r?h.x.apply(l,{position:"end"}):h.x.rangeMax,y:s?h.y.apply(u,{position:"end"}):h.y.rangeMax};return Ei(i,"discard")&&(!h.isInRange(f)||!h.isInRange(x))?null:BR(f,x)},Qx=function(e){function t(){return she(this,t),ohe(this,t,arguments)}return uhe(t,e),ihe(t,[{key:"render",value:function(){var n=this.props,s=n.x1,i=n.x2,o=n.y1,l=n.y2,c=n.className,u=n.alwaysShow,d=n.clipPathId;li(u===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var p=xs(s),h=xs(i),f=xs(o),x=xs(l),g=this.props.shape;if(!p&&!h&&!f&&!x&&!g)return null;var y=phe(p,h,f,x,this.props);if(!y&&!g)return null;var b=Ei(this.props,"hidden")?"url(#".concat(d,")"):void 0;return H.createElement(Tn,{className:fn("recharts-reference-area",c)},t.renderRect(g,LA(LA({clipPath:b},Pt(this.props,!0)),y)),Ss.renderCallByParent(this.props,y))}}])}(H.Component);Zx(Qx,"displayName","ReferenceArea");Zx(Qx,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#ccc",fillOpacity:.5,stroke:"none",strokeWidth:1});Zx(Qx,"renderRect",function(e,t){var r;return H.isValidElement(e)?r=H.cloneElement(e,t):Kt(e)?r=e(t):r=H.createElement(Ij,Uv({},t,{className:"recharts-reference-area-rect"})),r});function tD(e,t,r){if(t<1)return[];if(t===1&&r===void 0)return e;for(var n=[],s=0;s<e.length;s+=t)n.push(e[s]);return n}function hhe(e,t,r){var n={width:e.width+t.width,height:e.height+t.height};return Cpe(n,r)}function fhe(e,t,r){var n=r==="width",s=e.x,i=e.y,o=e.width,l=e.height;return t===1?{start:n?s:i,end:n?s+o:i+l}:{start:n?s+o:i+l,end:n?s:i}}function Tg(e,t,r,n,s){if(e*t<e*n||e*t>e*s)return!1;var i=r();return e*(t-e*i/2-n)>=0&&e*(t+e*i/2-s)<=0}function mhe(e,t){return tD(e,t+1)}function ghe(e,t,r,n,s){for(var i=(n||[]).slice(),o=t.start,l=t.end,c=0,u=1,d=o,p=function(){var x=n==null?void 0:n[c];if(x===void 0)return{v:tD(n,u)};var g=c,y,b=function(){return y===void 0&&(y=r(x,g)),y},v=x.coordinate,k=c===0||Tg(e,v,b,d,l);k||(c=0,d=o,u+=1),k&&(d=v+e*(b()/2+s),c+=u)},h;u<=i.length;)if(h=p(),h)return h.v;return[]}function bh(e){"@babel/helpers - typeof";return bh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},bh(e)}function $A(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Ms(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?$A(Object(r),!0).forEach(function(n){xhe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$A(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function xhe(e,t,r){return t=yhe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function yhe(e){var t=bhe(e,"string");return bh(t)=="symbol"?t:t+""}function bhe(e,t){if(bh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(bh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vhe(e,t,r,n,s){for(var i=(n||[]).slice(),o=i.length,l=t.start,c=t.end,u=function(h){var f=i[h],x,g=function(){return x===void 0&&(x=r(f,h)),x};if(h===o-1){var y=e*(f.coordinate+e*g()/2-c);i[h]=f=Ms(Ms({},f),{},{tickCoord:y>0?f.coordinate-y*e:f.coordinate})}else i[h]=f=Ms(Ms({},f),{},{tickCoord:f.coordinate});var b=Tg(e,f.tickCoord,g,l,c);b&&(c=f.tickCoord-e*(g()/2+s),i[h]=Ms(Ms({},f),{},{isShow:!0}))},d=o-1;d>=0;d--)u(d);return i}function whe(e,t,r,n,s,i){var o=(n||[]).slice(),l=o.length,c=t.start,u=t.end;if(i){var d=n[l-1],p=r(d,l-1),h=e*(d.coordinate+e*p/2-u);o[l-1]=d=Ms(Ms({},d),{},{tickCoord:h>0?d.coordinate-h*e:d.coordinate});var f=Tg(e,d.tickCoord,function(){return p},c,u);f&&(u=d.tickCoord-e*(p/2+s),o[l-1]=Ms(Ms({},d),{},{isShow:!0}))}for(var x=i?l-1:l,g=function(v){var k=o[v],N,j=function(){return N===void 0&&(N=r(k,v)),N};if(v===0){var w=e*(k.coordinate-e*j()/2-c);o[v]=k=Ms(Ms({},k),{},{tickCoord:w<0?k.coordinate-w*e:k.coordinate})}else o[v]=k=Ms(Ms({},k),{},{tickCoord:k.coordinate});var S=Tg(e,k.tickCoord,j,c,u);S&&(c=k.tickCoord+e*(j()/2+s),o[v]=Ms(Ms({},k),{},{isShow:!0}))},y=0;y<x;y++)g(y);return o}function Uj(e,t,r){var n=e.tick,s=e.ticks,i=e.viewBox,o=e.minTickGap,l=e.orientation,c=e.interval,u=e.tickFormatter,d=e.unit,p=e.angle;if(!s||!s.length||!n)return[];if(Oe(c)||ci.isSsr)return mhe(s,typeof c=="number"&&Oe(c)?c:0);var h=[],f=l==="top"||l==="bottom"?"width":"height",x=d&&f==="width"?jp(d,{fontSize:t,letterSpacing:r}):{width:0,height:0},g=function(k,N){var j=Kt(u)?u(k.value,N):k.value;return f==="width"?hhe(jp(j,{fontSize:t,letterSpacing:r}),x,p):jp(j,{fontSize:t,letterSpacing:r})[f]},y=s.length>=2?Js(s[1].coordinate-s[0].coordinate):1,b=fhe(i,y,f);return c==="equidistantPreserveStart"?ghe(y,b,g,s,o):(c==="preserveStart"||c==="preserveStartEnd"?h=whe(y,b,g,s,o,c==="preserveStartEnd"):h=vhe(y,b,g,s,o),h.filter(function(v){return v.isShow}))}var jhe=["viewBox"],Nhe=["viewBox"],khe=["ticks"];function Ku(e){"@babel/helpers - typeof";return Ku=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ku(e)}function uu(){return uu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},uu.apply(this,arguments)}function FA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function ds(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?FA(Object(r),!0).forEach(function(n){zj(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):FA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Nb(e,t){if(e==null)return{};var r=She(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function She(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Che(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function BA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,rD(n.key),n)}}function Phe(e,t,r){return t&&BA(e.prototype,t),r&&BA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ahe(e,t,r){return t=Eg(t),_he(e,nD()?Reflect.construct(t,r||[],Eg(e).constructor):t.apply(e,r))}function _he(e,t){if(t&&(Ku(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return The(e)}function The(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function nD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(nD=function(){return!!e})()}function Eg(e){return Eg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Eg(e)}function Ehe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&qv(e,t)}function qv(e,t){return qv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},qv(e,t)}function zj(e,t,r){return t=rD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function rD(e){var t=Ihe(e,"string");return Ku(t)=="symbol"?t:t+""}function Ihe(e,t){if(Ku(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Ku(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var md=function(e){function t(r){var n;return Che(this,t),n=Ahe(this,t,[r]),n.state={fontSize:"",letterSpacing:""},n}return Ehe(t,e),Phe(t,[{key:"shouldComponentUpdate",value:function(n,s){var i=n.viewBox,o=Nb(n,jhe),l=this.props,c=l.viewBox,u=Nb(l,Nhe);return!xu(i,c)||!xu(o,u)||!xu(s,this.state)}},{key:"componentDidMount",value:function(){var n=this.layerReference;if(n){var s=n.getElementsByClassName("recharts-cartesian-axis-tick-value")[0];s&&this.setState({fontSize:window.getComputedStyle(s).fontSize,letterSpacing:window.getComputedStyle(s).letterSpacing})}}},{key:"getTickLineCoord",value:function(n){var s=this.props,i=s.x,o=s.y,l=s.width,c=s.height,u=s.orientation,d=s.tickSize,p=s.mirror,h=s.tickMargin,f,x,g,y,b,v,k=p?-1:1,N=n.tickSize||d,j=Oe(n.tickCoord)?n.tickCoord:n.coordinate;switch(u){case"top":f=x=n.coordinate,y=o+ +!p*c,g=y-k*N,v=g-k*h,b=j;break;case"left":g=y=n.coordinate,x=i+ +!p*l,f=x-k*N,b=f-k*h,v=j;break;case"right":g=y=n.coordinate,x=i+ +p*l,f=x+k*N,b=f+k*h,v=j;break;default:f=x=n.coordinate,y=o+ +p*c,g=y+k*N,v=g+k*h,b=j;break}return{line:{x1:f,y1:g,x2:x,y2:y},tick:{x:b,y:v}}}},{key:"getTickTextAnchor",value:function(){var n=this.props,s=n.orientation,i=n.mirror,o;switch(s){case"left":o=i?"start":"end";break;case"right":o=i?"end":"start";break;default:o="middle";break}return o}},{key:"getTickVerticalAnchor",value:function(){var n=this.props,s=n.orientation,i=n.mirror,o="end";switch(s){case"left":case"right":o="middle";break;case"top":o=i?"start":"end";break;default:o=i?"end":"start";break}return o}},{key:"renderAxisLine",value:function(){var n=this.props,s=n.x,i=n.y,o=n.width,l=n.height,c=n.orientation,u=n.mirror,d=n.axisLine,p=ds(ds(ds({},Pt(this.props,!1)),Pt(d,!1)),{},{fill:"none"});if(c==="top"||c==="bottom"){var h=+(c==="top"&&!u||c==="bottom"&&u);p=ds(ds({},p),{},{x1:s,y1:i+h*l,x2:s+o,y2:i+h*l})}else{var f=+(c==="left"&&!u||c==="right"&&u);p=ds(ds({},p),{},{x1:s+f*o,y1:i,x2:s+f*o,y2:i+l})}return H.createElement("line",uu({},p,{className:fn("recharts-cartesian-axis-line",ba(d,"className"))}))}},{key:"renderTicks",value:function(n,s,i){var o=this,l=this.props,c=l.tickLine,u=l.stroke,d=l.tick,p=l.tickFormatter,h=l.unit,f=Uj(ds(ds({},this.props),{},{ticks:n}),s,i),x=this.getTickTextAnchor(),g=this.getTickVerticalAnchor(),y=Pt(this.props,!1),b=Pt(d,!1),v=ds(ds({},y),{},{fill:"none"},Pt(c,!1)),k=f.map(function(N,j){var w=o.getTickLineCoord(N),S=w.line,T=w.tick,C=ds(ds(ds(ds({textAnchor:x,verticalAnchor:g},y),{},{stroke:"none",fill:u},b),T),{},{index:j,payload:N,visibleTicksCount:f.length,tickFormatter:p});return H.createElement(Tn,uu({className:"recharts-cartesian-axis-tick",key:"tick-".concat(N.value,"-").concat(N.coordinate,"-").concat(N.tickCoord)},gc(o.props,N,j)),c&&H.createElement("line",uu({},v,S,{className:fn("recharts-cartesian-axis-tick-line",ba(c,"className"))})),d&&t.renderTickItem(d,C,"".concat(Kt(p)?p(N.value,j):N.value).concat(h||"")))});return H.createElement("g",{className:"recharts-cartesian-axis-ticks"},k)}},{key:"render",value:function(){var n=this,s=this.props,i=s.axisLine,o=s.width,l=s.height,c=s.ticksGenerator,u=s.className,d=s.hide;if(d)return null;var p=this.props,h=p.ticks,f=Nb(p,khe),x=h;return Kt(c)&&(x=h&&h.length>0?c(this.props):c(f)),o<=0||l<=0||!x||!x.length?null:H.createElement(Tn,{className:fn("recharts-cartesian-axis",u),ref:function(y){n.layerReference=y}},i&&this.renderAxisLine(),this.renderTicks(x,this.state.fontSize,this.state.letterSpacing),Ss.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,s,i){var o,l=fn(s.className,"recharts-cartesian-axis-tick-value");return H.isValidElement(n)?o=H.cloneElement(n,ds(ds({},s),{},{className:l})):Kt(n)?o=n(ds(ds({},s),{},{className:l})):o=H.createElement(xc,uu({},s,{className:"recharts-cartesian-axis-tick-value"}),i),o}}])}(m.Component);zj(md,"displayName","CartesianAxis");zj(md,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var Ohe=["x1","y1","x2","y2","key"],Rhe=["offset"];function vc(e){"@babel/helpers - typeof";return vc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vc(e)}function UA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Ls(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?UA(Object(r),!0).forEach(function(n){Dhe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):UA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Dhe(e,t,r){return t=Mhe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Mhe(e){var t=Lhe(e,"string");return vc(t)=="symbol"?t:t+""}function Lhe(e,t){if(vc(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(vc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Wl(){return Wl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Wl.apply(this,arguments)}function zA(e,t){if(e==null)return{};var r=$he(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function $he(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var Fhe=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,s=t.x,i=t.y,o=t.width,l=t.height,c=t.ry;return H.createElement("rect",{x:s,y:i,ry:c,width:o,height:l,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function sD(e,t){var r;if(H.isValidElement(e))r=H.cloneElement(e,t);else if(Kt(e))r=e(t);else{var n=t.x1,s=t.y1,i=t.x2,o=t.y2,l=t.key,c=zA(t,Ohe),u=Pt(c,!1);u.offset;var d=zA(u,Rhe);r=H.createElement("line",Wl({},d,{x1:n,y1:s,x2:i,y2:o,fill:"none",key:l}))}return r}function Bhe(e){var t=e.x,r=e.width,n=e.horizontal,s=n===void 0?!0:n,i=e.horizontalPoints;if(!s||!i||!i.length)return null;var o=i.map(function(l,c){var u=Ls(Ls({},e),{},{x1:t,y1:l,x2:t+r,y2:l,key:"line-".concat(c),index:c});return sD(s,u)});return H.createElement("g",{className:"recharts-cartesian-grid-horizontal"},o)}function Uhe(e){var t=e.y,r=e.height,n=e.vertical,s=n===void 0?!0:n,i=e.verticalPoints;if(!s||!i||!i.length)return null;var o=i.map(function(l,c){var u=Ls(Ls({},e),{},{x1:l,y1:t,x2:l,y2:t+r,key:"line-".concat(c),index:c});return sD(s,u)});return H.createElement("g",{className:"recharts-cartesian-grid-vertical"},o)}function zhe(e){var t=e.horizontalFill,r=e.fillOpacity,n=e.x,s=e.y,i=e.width,o=e.height,l=e.horizontalPoints,c=e.horizontal,u=c===void 0?!0:c;if(!u||!t||!t.length)return null;var d=l.map(function(h){return Math.round(h+s-s)}).sort(function(h,f){return h-f});s!==d[0]&&d.unshift(0);var p=d.map(function(h,f){var x=!d[f+1],g=x?s+o-h:d[f+1]-h;if(g<=0)return null;var y=f%t.length;return H.createElement("rect",{key:"react-".concat(f),y:h,x:n,height:g,width:i,stroke:"none",fill:t[y],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return H.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},p)}function qhe(e){var t=e.vertical,r=t===void 0?!0:t,n=e.verticalFill,s=e.fillOpacity,i=e.x,o=e.y,l=e.width,c=e.height,u=e.verticalPoints;if(!r||!n||!n.length)return null;var d=u.map(function(h){return Math.round(h+i-i)}).sort(function(h,f){return h-f});i!==d[0]&&d.unshift(0);var p=d.map(function(h,f){var x=!d[f+1],g=x?i+l-h:d[f+1]-h;if(g<=0)return null;var y=f%n.length;return H.createElement("rect",{key:"react-".concat(f),x:h,y:o,width:g,height:c,stroke:"none",fill:n[y],fillOpacity:s,className:"recharts-cartesian-grid-bg"})});return H.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},p)}var Hhe=function(t,r){var n=t.xAxis,s=t.width,i=t.height,o=t.offset;return iR(Uj(Ls(Ls(Ls({},md.defaultProps),n),{},{ticks:ao(n,!0),viewBox:{x:0,y:0,width:s,height:i}})),o.left,o.left+o.width,r)},Whe=function(t,r){var n=t.yAxis,s=t.width,i=t.height,o=t.offset;return iR(Uj(Ls(Ls(Ls({},md.defaultProps),n),{},{ticks:ao(n,!0),viewBox:{x:0,y:0,width:s,height:i}})),o.top,o.top+o.height,r)},Yc={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function Ig(e){var t,r,n,s,i,o,l=Lj(),c=$j(),u=Ipe(),d=Ls(Ls({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:Yc.stroke,fill:(r=e.fill)!==null&&r!==void 0?r:Yc.fill,horizontal:(n=e.horizontal)!==null&&n!==void 0?n:Yc.horizontal,horizontalFill:(s=e.horizontalFill)!==null&&s!==void 0?s:Yc.horizontalFill,vertical:(i=e.vertical)!==null&&i!==void 0?i:Yc.vertical,verticalFill:(o=e.verticalFill)!==null&&o!==void 0?o:Yc.verticalFill,x:Oe(e.x)?e.x:u.left,y:Oe(e.y)?e.y:u.top,width:Oe(e.width)?e.width:u.width,height:Oe(e.height)?e.height:u.height}),p=d.x,h=d.y,f=d.width,x=d.height,g=d.syncWithTicks,y=d.horizontalValues,b=d.verticalValues,v=_pe(),k=Tpe();if(!Oe(f)||f<=0||!Oe(x)||x<=0||!Oe(p)||p!==+p||!Oe(h)||h!==+h)return null;var N=d.verticalCoordinatesGenerator||Hhe,j=d.horizontalCoordinatesGenerator||Whe,w=d.horizontalPoints,S=d.verticalPoints;if((!w||!w.length)&&Kt(j)){var T=y&&y.length,C=j({yAxis:k?Ls(Ls({},k),{},{ticks:T?y:k.ticks}):void 0,width:l,height:c,offset:u},T?!0:g);li(Array.isArray(C),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(vc(C),"]")),Array.isArray(C)&&(w=C)}if((!S||!S.length)&&Kt(N)){var A=b&&b.length,P=N({xAxis:v?Ls(Ls({},v),{},{ticks:A?b:v.ticks}):void 0,width:l,height:c,offset:u},A?!0:g);li(Array.isArray(P),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(vc(P),"]")),Array.isArray(P)&&(S=P)}return H.createElement("g",{className:"recharts-cartesian-grid"},H.createElement(Fhe,{fill:d.fill,fillOpacity:d.fillOpacity,x:d.x,y:d.y,width:d.width,height:d.height,ry:d.ry}),H.createElement(Bhe,Wl({},d,{offset:u,horizontalPoints:w,xAxis:v,yAxis:k})),H.createElement(Uhe,Wl({},d,{offset:u,verticalPoints:S,xAxis:v,yAxis:k})),H.createElement(zhe,Wl({},d,{horizontalPoints:w})),H.createElement(qhe,Wl({},d,{verticalPoints:S})))}Ig.displayName="CartesianGrid";var Vhe=["type","layout","connectNulls","ref"],Ghe=["key"];function Yu(e){"@babel/helpers - typeof";return Yu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yu(e)}function qA(e,t){if(e==null)return{};var r=Khe(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Khe(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ap(){return Ap=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ap.apply(this,arguments)}function HA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function pa(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?HA(Object(r),!0).forEach(function(n){Xa(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):HA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Jc(e){return Zhe(e)||Xhe(e)||Jhe(e)||Yhe()}function Yhe(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
7000In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Jhe(e,t){if(e){if(typeof e=="string")return Hv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Hv(e,t)}}function Xhe(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Zhe(e){if(Array.isArray(e))return Hv(e)}function Hv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function Qhe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function WA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,iD(n.key),n)}}function efe(e,t,r){return t&&WA(e.prototype,t),r&&WA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function tfe(e,t,r){return t=Og(t),nfe(e,aD()?Reflect.construct(t,r||[],Og(e).constructor):t.apply(e,r))}function nfe(e,t){if(t&&(Yu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return rfe(e)}function rfe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function aD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(aD=function(){return!!e})()}function Og(e){return Og=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Og(e)}function sfe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Wv(e,t)}function Wv(e,t){return Wv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Wv(e,t)}function Xa(e,t,r){return t=iD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function iD(e){var t=afe(e,"string");return Yu(t)=="symbol"?t:t+""}function afe(e,t){if(Yu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Yu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var gd=function(e){function t(){var r;Qhe(this,t);for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];return r=tfe(this,t,[].concat(s)),Xa(r,"state",{isAnimationFinished:!0,totalLength:0}),Xa(r,"generateSimpleStrokeDasharray",function(o,l){return"".concat(l,"px ").concat(o-l,"px")}),Xa(r,"getStrokeDasharray",function(o,l,c){var u=c.reduce(function(b,v){return b+v});if(!u)return r.generateSimpleStrokeDasharray(l,o);for(var d=Math.floor(o/u),p=o%u,h=l-o,f=[],x=0,g=0;x<c.length;g+=c[x],++x)if(g+c[x]>p){f=[].concat(Jc(c.slice(0,x)),[p-g]);break}var y=f.length%2===0?[0,h]:[h];return[].concat(Jc(t.repeat(c,d)),Jc(f),y).map(function(b){return"".concat(b,"px")}).join(", ")}),Xa(r,"id",Sc("recharts-line-")),Xa(r,"pathRef",function(o){r.mainCurve=o}),Xa(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0}),r.props.onAnimationEnd&&r.props.onAnimationEnd()}),Xa(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1}),r.props.onAnimationStart&&r.props.onAnimationStart()}),r}return sfe(t,e),efe(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();this.setState({totalLength:n})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();n!==this.state.totalLength&&this.setState({totalLength:n})}}},{key:"getTotalLength",value:function(){var n=this.mainCurve;try{return n&&n.getTotalLength&&n.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(n,s){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,o=i.points,l=i.xAxis,c=i.yAxis,u=i.layout,d=i.children,p=wa(d,Bh);if(!p)return null;var h=function(g,y){return{x:g.x,y:g.y,value:g.value,errorVal:es(g.payload,y)}},f={clipPath:n?"url(#clipPath-".concat(s,")"):null};return H.createElement(Tn,f,p.map(function(x){return H.cloneElement(x,{key:"bar-".concat(x.props.dataKey),data:o,xAxis:l,yAxis:c,layout:u,dataPointFormatter:h})}))}},{key:"renderDots",value:function(n,s,i){var o=this.props.isAnimationActive;if(o&&!this.state.isAnimationFinished)return null;var l=this.props,c=l.dot,u=l.points,d=l.dataKey,p=Pt(this.props,!1),h=Pt(c,!0),f=u.map(function(g,y){var b=pa(pa(pa({key:"dot-".concat(y),r:3},p),h),{},{index:y,cx:g.x,cy:g.y,value:g.value,dataKey:d,payload:g.payload,points:u});return t.renderDotItem(c,b)}),x={clipPath:n?"url(#clipPath-".concat(s?"":"dots-").concat(i,")"):null};return H.createElement(Tn,Ap({className:"recharts-line-dots",key:"dots"},x),f)}},{key:"renderCurveStatically",value:function(n,s,i,o){var l=this.props,c=l.type,u=l.layout,d=l.connectNulls;l.ref;var p=qA(l,Vhe),h=pa(pa(pa({},Pt(p,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:s?"url(#clipPath-".concat(i,")"):null,points:n},o),{},{type:c,layout:u,connectNulls:d});return H.createElement(rc,Ap({},h,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(n,s){var i=this,o=this.props,l=o.points,c=o.strokeDasharray,u=o.isAnimationActive,d=o.animationBegin,p=o.animationDuration,h=o.animationEasing,f=o.animationId,x=o.animateNewValues,g=o.width,y=o.height,b=this.state,v=b.prevPoints,k=b.totalLength;return H.createElement(di,{begin:d,duration:p,isActive:u,easing:h,from:{t:0},to:{t:1},key:"line-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(N){var j=N.t;if(v){var w=v.length/l.length,S=l.map(function(E,_){var I=Math.floor(_*w);if(v[I]){var D=v[I],M=ms(D.x,E.x),B=ms(D.y,E.y);return pa(pa({},E),{},{x:M(j),y:B(j)})}if(x){var $=ms(g*2,E.x),K=ms(y/2,E.y);return pa(pa({},E),{},{x:$(j),y:K(j)})}return pa(pa({},E),{},{x:E.x,y:E.y})});return i.renderCurveStatically(S,n,s)}var T=ms(0,k),C=T(j),A;if(c){var P="".concat(c).split(/[,\s]+/gim).map(function(E){return parseFloat(E)});A=i.getStrokeDasharray(C,k,P)}else A=i.generateSimpleStrokeDasharray(k,C);return i.renderCurveStatically(l,n,s,{strokeDasharray:A})})}},{key:"renderCurve",value:function(n,s){var i=this.props,o=i.points,l=i.isAnimationActive,c=this.state,u=c.prevPoints,d=c.totalLength;return l&&o&&o.length&&(!u&&d>0||!oc(u,o))?this.renderCurveWithAnimation(n,s):this.renderCurveStatically(o,n,s)}},{key:"render",value:function(){var n,s=this.props,i=s.hide,o=s.dot,l=s.points,c=s.className,u=s.xAxis,d=s.yAxis,p=s.top,h=s.left,f=s.width,x=s.height,g=s.isAnimationActive,y=s.id;if(i||!l||!l.length)return null;var b=this.state.isAnimationFinished,v=l.length===1,k=fn("recharts-line",c),N=u&&u.allowDataOverflow,j=d&&d.allowDataOverflow,w=N||j,S=an(y)?this.id:y,T=(n=Pt(o,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},C=T.r,A=C===void 0?3:C,P=T.strokeWidth,E=P===void 0?2:P,_=PO(o)?o:{},I=_.clipDot,D=I===void 0?!0:I,M=A*2+E;return H.createElement(Tn,{className:k},N||j?H.createElement("defs",null,H.createElement("clipPath",{id:"clipPath-".concat(S)},H.createElement("rect",{x:N?h:h-f/2,y:j?p:p-x/2,width:N?f:f*2,height:j?x:x*2})),!D&&H.createElement("clipPath",{id:"clipPath-dots-".concat(S)},H.createElement("rect",{x:h-M/2,y:p-M/2,width:f+M,height:x+M}))):null,!v&&this.renderCurve(w,S),this.renderErrorBar(w,S),(v||o)&&this.renderDots(w,D,S),(!g||b)&&Ti.renderCallByParent(this.props,l))}}],[{key:"getDerivedStateFromProps",value:function(n,s){return n.animationId!==s.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:s.curPoints}:n.points!==s.curPoints?{curPoints:n.points}:null}},{key:"repeat",value:function(n,s){for(var i=n.length%2!==0?[].concat(Jc(n),[0]):n,o=[],l=0;l<s;++l)o=[].concat(Jc(o),Jc(i));return o}},{key:"renderDotItem",value:function(n,s){var i;if(H.isValidElement(n))i=H.cloneElement(n,s);else if(Kt(n))i=n(s);else{var o=s.key,l=qA(s,Ghe),c=fn("recharts-line-dot",typeof n!="boolean"?n.className:"");i=H.createElement(Uh,Ap({key:o},l,{className:c}))}return i}}])}(m.PureComponent);Xa(gd,"displayName","Line");Xa(gd,"defaultProps",{xAxisId:0,yAxisId:0,connectNulls:!1,activeDot:!0,dot:!0,legendType:"line",stroke:"#3182bd",strokeWidth:1,fill:"#fff",points:[],isAnimationActive:!ci.isSsr,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",hide:!1,label:!1});Xa(gd,"getComposedData",function(e){var t=e.props,r=e.xAxis,n=e.yAxis,s=e.xAxisTicks,i=e.yAxisTicks,o=e.dataKey,l=e.bandSize,c=e.displayedData,u=e.offset,d=t.layout,p=c.map(function(h,f){var x=es(h,o);return d==="horizontal"?{x:cg({axis:r,ticks:s,bandSize:l,entry:h,index:f}),y:an(x)?null:n.scale(x),value:x,payload:h}:{x:an(x)?null:r.scale(x),y:cg({axis:n,ticks:i,bandSize:l,entry:h,index:f}),value:x,payload:h}});return pa({points:p,layout:d},u)});var ife=["layout","type","stroke","connectNulls","isRange","ref"],ofe=["key"],oD;function Ju(e){"@babel/helpers - typeof";return Ju=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ju(e)}function lD(e,t){if(e==null)return{};var r=lfe(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function lfe(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Vl(){return Vl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Vl.apply(this,arguments)}function VA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Fo(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?VA(Object(r),!0).forEach(function(n){Pi(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):VA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function cfe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function GA(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,uD(n.key),n)}}function ufe(e,t,r){return t&&GA(e.prototype,t),r&&GA(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function dfe(e,t,r){return t=Rg(t),pfe(e,cD()?Reflect.construct(t,r||[],Rg(e).constructor):t.apply(e,r))}function pfe(e,t){if(t&&(Ju(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hfe(e)}function hfe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function cD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(cD=function(){return!!e})()}function Rg(e){return Rg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Rg(e)}function ffe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Vv(e,t)}function Vv(e,t){return Vv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Vv(e,t)}function Pi(e,t,r){return t=uD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function uD(e){var t=mfe(e,"string");return Ju(t)=="symbol"?t:t+""}function mfe(e,t){if(Ju(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Ju(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var ml=function(e){function t(){var r;cfe(this,t);for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];return r=dfe(this,t,[].concat(s)),Pi(r,"state",{isAnimationFinished:!0}),Pi(r,"id",Sc("recharts-area-")),Pi(r,"handleAnimationEnd",function(){var o=r.props.onAnimationEnd;r.setState({isAnimationFinished:!0}),Kt(o)&&o()}),Pi(r,"handleAnimationStart",function(){var o=r.props.onAnimationStart;r.setState({isAnimationFinished:!1}),Kt(o)&&o()}),r}return ffe(t,e),ufe(t,[{key:"renderDots",value:function(n,s,i){var o=this.props.isAnimationActive,l=this.state.isAnimationFinished;if(o&&!l)return null;var c=this.props,u=c.dot,d=c.points,p=c.dataKey,h=Pt(this.props,!1),f=Pt(u,!0),x=d.map(function(y,b){var v=Fo(Fo(Fo({key:"dot-".concat(b),r:3},h),f),{},{index:b,cx:y.x,cy:y.y,dataKey:p,value:y.value,payload:y.payload,points:d});return t.renderDotItem(u,v)}),g={clipPath:n?"url(#clipPath-".concat(s?"":"dots-").concat(i,")"):null};return H.createElement(Tn,Vl({className:"recharts-area-dots"},g),x)}},{key:"renderHorizontalRect",value:function(n){var s=this.props,i=s.baseLine,o=s.points,l=s.strokeWidth,c=o[0].x,u=o[o.length-1].x,d=n*Math.abs(c-u),p=Go(o.map(function(h){return h.y||0}));return Oe(i)&&typeof i=="number"?p=Math.max(i,p):i&&Array.isArray(i)&&i.length&&(p=Math.max(Go(i.map(function(h){return h.y||0})),p)),Oe(p)?H.createElement("rect",{x:c<u?c:c-d,y:0,width:d,height:Math.floor(p+(l?parseInt("".concat(l),10):1))}):null}},{key:"renderVerticalRect",value:function(n){var s=this.props,i=s.baseLine,o=s.points,l=s.strokeWidth,c=o[0].y,u=o[o.length-1].y,d=n*Math.abs(c-u),p=Go(o.map(function(h){return h.x||0}));return Oe(i)&&typeof i=="number"?p=Math.max(i,p):i&&Array.isArray(i)&&i.length&&(p=Math.max(Go(i.map(function(h){return h.x||0})),p)),Oe(p)?H.createElement("rect",{x:0,y:c<u?c:c-d,width:p+(l?parseInt("".concat(l),10):1),height:Math.floor(d)}):null}},{key:"renderClipRect",value:function(n){var s=this.props.layout;return s==="vertical"?this.renderVerticalRect(n):this.renderHorizontalRect(n)}},{key:"renderAreaStatically",value:function(n,s,i,o){var l=this.props,c=l.layout,u=l.type,d=l.stroke,p=l.connectNulls,h=l.isRange;l.ref;var f=lD(l,ife);return H.createElement(Tn,{clipPath:i?"url(#clipPath-".concat(o,")"):null},H.createElement(rc,Vl({},Pt(f,!0),{points:n,connectNulls:p,type:u,baseLine:s,layout:c,stroke:"none",className:"recharts-area-area"})),d!=="none"&&H.createElement(rc,Vl({},Pt(this.props,!1),{className:"recharts-area-curve",layout:c,type:u,connectNulls:p,fill:"none",points:n})),d!=="none"&&h&&H.createElement(rc,Vl({},Pt(this.props,!1),{className:"recharts-area-curve",layout:c,type:u,connectNulls:p,fill:"none",points:s})))}},{key:"renderAreaWithAnimation",value:function(n,s){var i=this,o=this.props,l=o.points,c=o.baseLine,u=o.isAnimationActive,d=o.animationBegin,p=o.animationDuration,h=o.animationEasing,f=o.animationId,x=this.state,g=x.prevPoints,y=x.prevBaseLine;return H.createElement(di,{begin:d,duration:p,isActive:u,easing:h,from:{t:0},to:{t:1},key:"area-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(b){var v=b.t;if(g){var k=g.length/l.length,N=l.map(function(T,C){var A=Math.floor(C*k);if(g[A]){var P=g[A],E=ms(P.x,T.x),_=ms(P.y,T.y);return Fo(Fo({},T),{},{x:E(v),y:_(v)})}return T}),j;if(Oe(c)&&typeof c=="number"){var w=ms(y,c);j=w(v)}else if(an(c)||dd(c)){var S=ms(y,0);j=S(v)}else j=c.map(function(T,C){var A=Math.floor(C*k);if(y[A]){var P=y[A],E=ms(P.x,T.x),_=ms(P.y,T.y);return Fo(Fo({},T),{},{x:E(v),y:_(v)})}return T});return i.renderAreaStatically(N,j,n,s)}return H.createElement(Tn,null,H.createElement("defs",null,H.createElement("clipPath",{id:"animationClipPath-".concat(s)},i.renderClipRect(v))),H.createElement(Tn,{clipPath:"url(#animationClipPath-".concat(s,")")},i.renderAreaStatically(l,c,n,s)))})}},{key:"renderArea",value:function(n,s){var i=this.props,o=i.points,l=i.baseLine,c=i.isAnimationActive,u=this.state,d=u.prevPoints,p=u.prevBaseLine,h=u.totalLength;return c&&o&&o.length&&(!d&&h>0||!oc(d,o)||!oc(p,l))?this.renderAreaWithAnimation(n,s):this.renderAreaStatically(o,l,n,s)}},{key:"render",value:function(){var n,s=this.props,i=s.hide,o=s.dot,l=s.points,c=s.className,u=s.top,d=s.left,p=s.xAxis,h=s.yAxis,f=s.width,x=s.height,g=s.isAnimationActive,y=s.id;if(i||!l||!l.length)return null;var b=this.state.isAnimationFinished,v=l.length===1,k=fn("recharts-area",c),N=p&&p.allowDataOverflow,j=h&&h.allowDataOverflow,w=N||j,S=an(y)?this.id:y,T=(n=Pt(o,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},C=T.r,A=C===void 0?3:C,P=T.strokeWidth,E=P===void 0?2:P,_=PO(o)?o:{},I=_.clipDot,D=I===void 0?!0:I,M=A*2+E;return H.createElement(Tn,{className:k},N||j?H.createElement("defs",null,H.createElement("clipPath",{id:"clipPath-".concat(S)},H.createElement("rect",{x:N?d:d-f/2,y:j?u:u-x/2,width:N?f:f*2,height:j?x:x*2})),!D&&H.createElement("clipPath",{id:"clipPath-dots-".concat(S)},H.createElement("rect",{x:d-M/2,y:u-M/2,width:f+M,height:x+M}))):null,v?null:this.renderArea(w,S),(o||v)&&this.renderDots(w,D,S),(!g||b)&&Ti.renderCallByParent(this.props,l))}}],[{key:"getDerivedStateFromProps",value:function(n,s){return n.animationId!==s.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,curBaseLine:n.baseLine,prevPoints:s.curPoints,prevBaseLine:s.curBaseLine}:n.points!==s.curPoints||n.baseLine!==s.curBaseLine?{curPoints:n.points,curBaseLine:n.baseLine}:null}}])}(m.PureComponent);oD=ml;Pi(ml,"displayName","Area");Pi(ml,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!ci.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});Pi(ml,"getBaseValue",function(e,t,r,n){var s=e.layout,i=e.baseValue,o=t.props.baseValue,l=o??i;if(Oe(l)&&typeof l=="number")return l;var c=s==="horizontal"?n:r,u=c.scale.domain();if(c.type==="number"){var d=Math.max(u[0],u[1]),p=Math.min(u[0],u[1]);return l==="dataMin"?p:l==="dataMax"||d<0?d:Math.max(Math.min(u[0],u[1]),0)}return l==="dataMin"?u[0]:l==="dataMax"?u[1]:u[0]});Pi(ml,"getComposedData",function(e){var t=e.props,r=e.item,n=e.xAxis,s=e.yAxis,i=e.xAxisTicks,o=e.yAxisTicks,l=e.bandSize,c=e.dataKey,u=e.stackedData,d=e.dataStartIndex,p=e.displayedData,h=e.offset,f=t.layout,x=u&&u.length,g=oD.getBaseValue(t,r,n,s),y=f==="horizontal",b=!1,v=p.map(function(N,j){var w;x?w=u[d+j]:(w=es(N,c),Array.isArray(w)?b=!0:w=[g,w]);var S=w[1]==null||x&&es(N,c)==null;return y?{x:cg({axis:n,ticks:i,bandSize:l,entry:N,index:j}),y:S?null:s.scale(w[1]),value:w,payload:N}:{x:S?null:n.scale(w[1]),y:cg({axis:s,ticks:o,bandSize:l,entry:N,index:j}),value:w,payload:N}}),k;return x||b?k=v.map(function(N){var j=Array.isArray(N.value)?N.value[0]:null;return y?{x:N.x,y:j!=null&&N.y!=null?s.scale(j):null}:{x:j!=null?n.scale(j):null,y:N.y}}):k=y?s.scale(g):n.scale(g),Fo({points:v,baseLine:k,layout:f,isRange:b},h)});Pi(ml,"renderDotItem",function(e,t){var r;if(H.isValidElement(e))r=H.cloneElement(e,t);else if(Kt(e))r=e(t);else{var n=fn("recharts-area-dot",typeof e!="boolean"?e.className:""),s=t.key,i=lD(t,ofe);r=H.createElement(Uh,Vl({},i,{key:s,className:n}))}return r});function Xu(e){"@babel/helpers - typeof";return Xu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xu(e)}function gfe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function xfe(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,hD(n.key),n)}}function yfe(e,t,r){return t&&xfe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function bfe(e,t,r){return t=Dg(t),vfe(e,dD()?Reflect.construct(t,r||[],Dg(e).constructor):t.apply(e,r))}function vfe(e,t){if(t&&(Xu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return wfe(e)}function wfe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function dD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(dD=function(){return!!e})()}function Dg(e){return Dg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Dg(e)}function jfe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Gv(e,t)}function Gv(e,t){return Gv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Gv(e,t)}function pD(e,t,r){return t=hD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function hD(e){var t=Nfe(e,"string");return Xu(t)=="symbol"?t:t+""}function Nfe(e,t){if(Xu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Xu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Kv(){return Kv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Kv.apply(this,arguments)}function kfe(e){var t=e.xAxisId,r=Lj(),n=$j(),s=GR(t);return s==null?null:m.createElement(md,Kv({},s,{className:fn("recharts-".concat(s.axisType," ").concat(s.axisType),s.className),viewBox:{x:0,y:0,width:r,height:n},ticksGenerator:function(o){return ao(o,!0)}}))}var nl=function(e){function t(){return gfe(this,t),bfe(this,t,arguments)}return jfe(t,e),yfe(t,[{key:"render",value:function(){return m.createElement(kfe,this.props)}}])}(m.Component);pD(nl,"displayName","XAxis");pD(nl,"defaultProps",{allowDecimals:!0,hide:!1,orientation:"bottom",width:0,height:30,mirror:!1,xAxisId:0,tickCount:5,type:"category",padding:{left:0,right:0},allowDataOverflow:!1,scale:"auto",reversed:!1,allowDuplicatedCategory:!0});function Zu(e){"@babel/helpers - typeof";return Zu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Zu(e)}function Sfe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Cfe(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,gD(n.key),n)}}function Pfe(e,t,r){return t&&Cfe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Afe(e,t,r){return t=Mg(t),_fe(e,fD()?Reflect.construct(t,r||[],Mg(e).constructor):t.apply(e,r))}function _fe(e,t){if(t&&(Zu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Tfe(e)}function Tfe(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function fD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(fD=function(){return!!e})()}function Mg(e){return Mg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Mg(e)}function Efe(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Yv(e,t)}function Yv(e,t){return Yv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Yv(e,t)}function mD(e,t,r){return t=gD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gD(e){var t=Ife(e,"string");return Zu(t)=="symbol"?t:t+""}function Ife(e,t){if(Zu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Zu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Jv(){return Jv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Jv.apply(this,arguments)}var Ofe=function(t){var r=t.yAxisId,n=Lj(),s=$j(),i=KR(r);return i==null?null:m.createElement(md,Jv({},i,{className:fn("recharts-".concat(i.axisType," ").concat(i.axisType),i.className),viewBox:{x:0,y:0,width:n,height:s},ticksGenerator:function(l){return ao(l,!0)}}))},rl=function(e){function t(){return Sfe(this,t),Afe(this,t,arguments)}return Efe(t,e),Pfe(t,[{key:"render",value:function(){return m.createElement(Ofe,this.props)}}])}(m.Component);mD(rl,"displayName","YAxis");mD(rl,"defaultProps",{allowDuplicatedCategory:!0,allowDecimals:!0,hide:!1,orientation:"left",width:60,height:0,mirror:!1,yAxisId:0,tickCount:5,type:"number",padding:{top:0,bottom:0},allowDataOverflow:!1,scale:"auto",reversed:!1});function KA(e){return Lfe(e)||Mfe(e)||Dfe(e)||Rfe()}function Rfe(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
7001In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Dfe(e,t){if(e){if(typeof e=="string")return Xv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Xv(e,t)}}function Mfe(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Lfe(e){if(Array.isArray(e))return Xv(e)}function Xv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var Zv=function(t,r,n,s,i){var o=wa(t,Bj),l=wa(t,Xx),c=[].concat(KA(o),KA(l)),u=wa(t,Qx),d="".concat(s,"Id"),p=s[0],h=r;if(c.length&&(h=c.reduce(function(g,y){if(y.props[d]===n&&Ei(y.props,"extendDomain")&&Oe(y.props[p])){var b=y.props[p];return[Math.min(g[0],b),Math.max(g[1],b)]}return g},h)),u.length){var f="".concat(p,"1"),x="".concat(p,"2");h=u.reduce(function(g,y){if(y.props[d]===n&&Ei(y.props,"extendDomain")&&Oe(y.props[f])&&Oe(y.props[x])){var b=y.props[f],v=y.props[x];return[Math.min(g[0],b,v),Math.max(g[1],b,v)]}return g},h)}return i&&i.length&&(h=i.reduce(function(g,y){return Oe(y)?[Math.min(g[0],y),Math.max(g[1],y)]:g},h)),h},xD={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function s(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function i(c,u,d,p,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new s(d,p||c,h),x=r?r+u:u;return c._events[x]?c._events[x].fn?c._events[x]=[c._events[x],f]:c._events[x].push(f):(c._events[x]=f,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new n:delete c._events[u]}function l(){this._events=new n,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,p;if(this._eventsCount===0)return u;for(p in d=this._events)t.call(d,p)&&u.push(r?p.slice(1):p);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=r?r+u:u,p=this._events[d];if(!p)return[];if(p.fn)return[p.fn];for(var h=0,f=p.length,x=new Array(f);h<f;h++)x[h]=p[h].fn;return x},l.prototype.listenerCount=function(u){var d=r?r+u:u,p=this._events[d];return p?p.fn?1:p.length:0},l.prototype.emit=function(u,d,p,h,f,x){var g=r?r+u:u;if(!this._events[g])return!1;var y=this._events[g],b=arguments.length,v,k;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),b){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,p),!0;case 4:return y.fn.call(y.context,d,p,h),!0;case 5:return y.fn.call(y.context,d,p,h,f),!0;case 6:return y.fn.call(y.context,d,p,h,f,x),!0}for(k=1,v=new Array(b-1);k<b;k++)v[k-1]=arguments[k];y.fn.apply(y.context,v)}else{var N=y.length,j;for(k=0;k<N;k++)switch(y[k].once&&this.removeListener(u,y[k].fn,void 0,!0),b){case 1:y[k].fn.call(y[k].context);break;case 2:y[k].fn.call(y[k].context,d);break;case 3:y[k].fn.call(y[k].context,d,p);break;case 4:y[k].fn.call(y[k].context,d,p,h);break;default:if(!v)for(j=1,v=new Array(b-1);j<b;j++)v[j-1]=arguments[j];y[k].fn.apply(y[k].context,v)}}return!0},l.prototype.on=function(u,d,p){return i(this,u,d,p,!1)},l.prototype.once=function(u,d,p){return i(this,u,d,p,!0)},l.prototype.removeListener=function(u,d,p,h){var f=r?r+u:u;if(!this._events[f])return this;if(!d)return o(this,f),this;var x=this._events[f];if(x.fn)x.fn===d&&(!h||x.once)&&(!p||x.context===p)&&o(this,f);else{for(var g=0,y=[],b=x.length;g<b;g++)(x[g].fn!==d||h&&!x[g].once||p&&x[g].context!==p)&&y.push(x[g]);y.length?this._events[f]=y.length===1?y[0]:y:o(this,f)}return this},l.prototype.removeAllListeners=function(u){var d;return u?(d=r?r+u:u,this._events[d]&&o(this,d)):(this._events=new n,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,e.exports=l})(xD);var $fe=xD.exports;const Ffe=zs($fe);var kb=new Ffe,Sb="recharts.syncMouseEvents";function vh(e){"@babel/helpers - typeof";return vh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vh(e)}function Bfe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ufe(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,yD(n.key),n)}}function zfe(e,t,r){return t&&Ufe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Cb(e,t,r){return t=yD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function yD(e){var t=qfe(e,"string");return vh(t)=="symbol"?t:t+""}function qfe(e,t){if(vh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(vh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Hfe=function(){function e(){Bfe(this,e),Cb(this,"activeIndex",0),Cb(this,"coordinateList",[]),Cb(this,"layout","horizontal")}return zfe(e,[{key:"setDetails",value:function(r){var n,s=r.coordinateList,i=s===void 0?null:s,o=r.container,l=o===void 0?null:o,c=r.layout,u=c===void 0?null:c,d=r.offset,p=d===void 0?null:d,h=r.mouseHandlerCallback,f=h===void 0?null:h;this.coordinateList=(n=i??this.coordinateList)!==null&&n!==void 0?n:[],this.container=l??this.container,this.layout=u??this.layout,this.offset=p??this.offset,this.mouseHandlerCallback=f??this.mouseHandlerCallback,this.activeIndex=Math.min(Math.max(this.activeIndex,0),this.coordinateList.length-1)}},{key:"focus",value:function(){this.spoofMouse()}},{key:"keyboardEvent",value:function(r){if(this.coordinateList.length!==0)switch(r.key){case"ArrowRight":{if(this.layout!=="horizontal")return;this.activeIndex=Math.min(this.activeIndex+1,this.coordinateList.length-1),this.spoofMouse();break}case"ArrowLeft":{if(this.layout!=="horizontal")return;this.activeIndex=Math.max(this.activeIndex-1,0),this.spoofMouse();break}}}},{key:"setIndex",value:function(r){this.activeIndex=r}},{key:"spoofMouse",value:function(){var r,n;if(this.layout==="horizontal"&&this.coordinateList.length!==0){var s=this.container.getBoundingClientRect(),i=s.x,o=s.y,l=s.height,c=this.coordinateList[this.activeIndex].coordinate,u=((r=window)===null||r===void 0?void 0:r.scrollX)||0,d=((n=window)===null||n===void 0?void 0:n.scrollY)||0,p=i+c+u,h=o+this.offset.top+l/2+d;this.mouseHandlerCallback({pageX:p,pageY:h})}}}])}();function Wfe(e,t,r){if(r==="number"&&t===!0&&Array.isArray(e)){var n=e==null?void 0:e[0],s=e==null?void 0:e[1];if(n&&s&&Oe(n)&&Oe(s))return!0}return!1}function Vfe(e,t,r,n){var s=n/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-s:r.left+.5,y:e==="horizontal"?r.top+.5:t.y-s,width:e==="horizontal"?n:r.width-1,height:e==="horizontal"?r.height-1:n}}function bD(e){var t=e.cx,r=e.cy,n=e.radius,s=e.startAngle,i=e.endAngle,o=_r(t,r,n,s),l=_r(t,r,n,i);return{points:[o,l],cx:t,cy:r,radius:n,startAngle:s,endAngle:i}}function Gfe(e,t,r){var n,s,i,o;if(e==="horizontal")n=t.x,i=n,s=r.top,o=r.top+r.height;else if(e==="vertical")s=t.y,o=s,n=r.left,i=r.left+r.width;else if(t.cx!=null&&t.cy!=null)if(e==="centric"){var l=t.cx,c=t.cy,u=t.innerRadius,d=t.outerRadius,p=t.angle,h=_r(l,c,u,p),f=_r(l,c,d,p);n=h.x,s=h.y,i=f.x,o=f.y}else return bD(t);return[{x:n,y:s},{x:i,y:o}]}function wh(e){"@babel/helpers - typeof";return wh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wh(e)}function YA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Uf(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?YA(Object(r),!0).forEach(function(n){Kfe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):YA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Kfe(e,t,r){return t=Yfe(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Yfe(e){var t=Jfe(e,"string");return wh(t)=="symbol"?t:t+""}function Jfe(e,t){if(wh(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(wh(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Xfe(e){var t,r,n=e.element,s=e.tooltipEventType,i=e.isActive,o=e.activeCoordinate,l=e.activePayload,c=e.offset,u=e.activeTooltipIndex,d=e.tooltipAxisBandSize,p=e.layout,h=e.chartName,f=(t=n.props.cursor)!==null&&t!==void 0?t:(r=n.type.defaultProps)===null||r===void 0?void 0:r.cursor;if(!n||!f||!i||!o||h!=="ScatterChart"&&s!=="axis")return null;var x,g=rc;if(h==="ScatterChart")x=o,g=iue;else if(h==="BarChart")x=Vfe(p,o,c,d),g=Ij;else if(p==="radial"){var y=bD(o),b=y.cx,v=y.cy,k=y.radius,N=y.startAngle,j=y.endAngle;x={cx:b,cy:v,startAngle:N,endAngle:j,innerRadius:k,outerRadius:k},g=xR}else x={points:Gfe(p,o,c)},g=rc;var w=Uf(Uf(Uf(Uf({stroke:"#ccc",pointerEvents:"none"},c),x),Pt(f,!1)),{},{payload:l,payloadIndex:u,className:fn("recharts-tooltip-cursor",f.className)});return m.isValidElement(f)?m.cloneElement(f,w):m.createElement(g,w)}var Zfe=["item"],Qfe=["children","className","width","height","style","compact","title","desc"];function Qu(e){"@babel/helpers - typeof";return Qu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qu(e)}function du(){return du=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},du.apply(this,arguments)}function JA(e,t){return nme(e)||tme(e,t)||wD(e,t)||eme()}function eme(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
7002In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tme(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,s,i,o,l=[],c=!0,u=!1;try{if(i=(r=r.call(e)).next,t!==0)for(;!(c=(n=i.call(r)).done)&&(l.push(n.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function nme(e){if(Array.isArray(e))return e}function XA(e,t){if(e==null)return{};var r=rme(e,t),n,s;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function rme(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function sme(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ame(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,jD(n.key),n)}}function ime(e,t,r){return t&&ame(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function ome(e,t,r){return t=Lg(t),lme(e,vD()?Reflect.construct(t,r||[],Lg(e).constructor):t.apply(e,r))}function lme(e,t){if(t&&(Qu(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return cme(e)}function cme(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function vD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(vD=function(){return!!e})()}function Lg(e){return Lg=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Lg(e)}function ume(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Qv(e,t)}function Qv(e,t){return Qv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,s){return n.__proto__=s,n},Qv(e,t)}function ed(e){return hme(e)||pme(e)||wD(e)||dme()}function dme(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
7003In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function wD(e,t){if(e){if(typeof e=="string")return ew(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ew(e,t)}}function pme(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function hme(e){if(Array.isArray(e))return ew(e)}function ew(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function ZA(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function be(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ZA(Object(r),!0).forEach(function(n){Gt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ZA(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Gt(e,t,r){return t=jD(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function jD(e){var t=fme(e,"string");return Qu(t)=="symbol"?t:t+""}function fme(e,t){if(Qu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Qu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var mme={xAxis:["bottom","top"],yAxis:["left","right"]},gme={width:"100%",height:"100%"},ND={x:0,y:0};function zf(e){return e}var xme=function(t,r){return r==="horizontal"?t.x:r==="vertical"?t.y:r==="centric"?t.angle:t.radius},yme=function(t,r,n,s){var i=r.find(function(d){return d&&d.index===n});if(i){if(t==="horizontal")return{x:i.coordinate,y:s.y};if(t==="vertical")return{x:s.x,y:i.coordinate};if(t==="centric"){var o=i.coordinate,l=s.radius;return be(be(be({},s),_r(s.cx,s.cy,l,o)),{},{angle:o,radius:l})}var c=i.coordinate,u=s.angle;return be(be(be({},s),_r(s.cx,s.cy,c,u)),{},{angle:u,radius:c})}return ND},ey=function(t,r){var n=r.graphicalItems,s=r.dataStartIndex,i=r.dataEndIndex,o=(n??[]).reduce(function(l,c){var u=c.props.data;return u&&u.length?[].concat(ed(l),ed(u)):l},[]);return o.length>0?o:t&&t.length&&Oe(s)&&Oe(i)?t.slice(s,i+1):[]};function kD(e){return e==="number"?[0,"auto"]:void 0}var tw=function(t,r,n,s){var i=t.graphicalItems,o=t.tooltipAxis,l=ey(r,t);return n<0||!i||!i.length||n>=l.length?null:i.reduce(function(c,u){var d,p=(d=u.props.data)!==null&&d!==void 0?d:r;p&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(p=p.slice(t.dataStartIndex,t.dataEndIndex+1));var h;if(o.dataKey&&!o.allowDuplicatedCategory){var f=p===void 0?l:p;h=$m(f,o.dataKey,s)}else h=p&&p[n]||l[n];return h?[].concat(ed(c),[dR(u,h)]):c},[])},QA=function(t,r,n,s){var i=s||{x:t.chartX,y:t.chartY},o=xme(i,n),l=t.orderedTooltipTicks,c=t.tooltipAxis,u=t.tooltipTicks,d=$ie(o,l,u,c);if(d>=0&&u){var p=u[d]&&u[d].value,h=tw(t,r,d,p),f=yme(n,l,d,i);return{activeTooltipIndex:d,activeLabel:p,activePayload:h,activeCoordinate:f}}return null},bme=function(t,r){var n=r.axes,s=r.graphicalItems,i=r.axisType,o=r.axisIdKey,l=r.stackGroups,c=r.dataStartIndex,u=r.dataEndIndex,d=t.layout,p=t.children,h=t.stackOffset,f=aR(d,i);return n.reduce(function(x,g){var y,b=g.type.defaultProps!==void 0?be(be({},g.type.defaultProps),g.props):g.props,v=b.type,k=b.dataKey,N=b.allowDataOverflow,j=b.allowDuplicatedCategory,w=b.scale,S=b.ticks,T=b.includeHidden,C=b[o];if(x[C])return x;var A=ey(t.data,{graphicalItems:s.filter(function(Z){var O,ne=o in Z.props?Z.props[o]:(O=Z.type.defaultProps)===null||O===void 0?void 0:O[o];return ne===C}),dataStartIndex:c,dataEndIndex:u}),P=A.length,E,_,I;Wfe(b.domain,N,v)&&(E=fv(b.domain,null,N),f&&(v==="number"||w!=="auto")&&(I=kp(A,k,"category")));var D=kD(v);if(!E||E.length===0){var M,B=(M=b.domain)!==null&&M!==void 0?M:D;if(k){if(E=kp(A,k,v),v==="category"&&f){var $=KZ(E);j&&$?(_=E,E=jg(0,P)):j||(E=wP(B,E,g).reduce(function(Z,O){return Z.indexOf(O)>=0?Z:[].concat(ed(Z),[O])},[]))}else if(v==="category")j?E=E.filter(function(Z){return Z!==""&&!an(Z)}):E=wP(B,E,g).reduce(function(Z,O){return Z.indexOf(O)>=0||O===""||an(O)?Z:[].concat(ed(Z),[O])},[]);else if(v==="number"){var K=qie(A,s.filter(function(Z){var O,ne,oe=o in Z.props?Z.props[o]:(O=Z.type.defaultProps)===null||O===void 0?void 0:O[o],he="hide"in Z.props?Z.props.hide:(ne=Z.type.defaultProps)===null||ne===void 0?void 0:ne.hide;return oe===C&&(T||!he)}),k,i,d);K&&(E=K)}f&&(v==="number"||w!=="auto")&&(I=kp(A,k,"category"))}else f?E=jg(0,P):l&&l[C]&&l[C].hasStack&&v==="number"?E=h==="expand"?[0,1]:uR(l[C].stackGroups,c,u):E=sR(A,s.filter(function(Z){var O=o in Z.props?Z.props[o]:Z.type.defaultProps[o],ne="hide"in Z.props?Z.props.hide:Z.type.defaultProps.hide;return O===C&&(T||!ne)}),v,d,!0);if(v==="number")E=Zv(p,E,C,i,S),B&&(E=fv(B,E,N));else if(v==="category"&&B){var R=B,Y=E.every(function(Z){return R.indexOf(Z)>=0});Y&&(E=R)}}return be(be({},x),{},Gt({},C,be(be({},b),{},{axisType:i,domain:E,categoricalDomain:I,duplicateDomain:_,originalDomain:(y=b.domain)!==null&&y!==void 0?y:D,isCategorical:f,layout:d})))},{})},vme=function(t,r){var n=r.graphicalItems,s=r.Axis,i=r.axisType,o=r.axisIdKey,l=r.stackGroups,c=r.dataStartIndex,u=r.dataEndIndex,d=t.layout,p=t.children,h=ey(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:u}),f=h.length,x=aR(d,i),g=-1;return n.reduce(function(y,b){var v=b.type.defaultProps!==void 0?be(be({},b.type.defaultProps),b.props):b.props,k=v[o],N=kD("number");if(!y[k]){g++;var j;return x?j=jg(0,f):l&&l[k]&&l[k].hasStack?(j=uR(l[k].stackGroups,c,u),j=Zv(p,j,k,i)):(j=fv(N,sR(h,n.filter(function(w){var S,T,C=o in w.props?w.props[o]:(S=w.type.defaultProps)===null||S===void 0?void 0:S[o],A="hide"in w.props?w.props.hide:(T=w.type.defaultProps)===null||T===void 0?void 0:T.hide;return C===k&&!A}),"number",d),s.defaultProps.allowDataOverflow),j=Zv(p,j,k,i)),be(be({},y),{},Gt({},k,be(be({axisType:i},s.defaultProps),{},{hide:!0,orientation:ba(mme,"".concat(i,".").concat(g%2),null),domain:j,originalDomain:N,isCategorical:x,layout:d})))}return y},{})},wme=function(t,r){var n=r.axisType,s=n===void 0?"xAxis":n,i=r.AxisComp,o=r.graphicalItems,l=r.stackGroups,c=r.dataStartIndex,u=r.dataEndIndex,d=t.children,p="".concat(s,"Id"),h=wa(d,i),f={};return h&&h.length?f=bme(t,{axes:h,graphicalItems:o,axisType:s,axisIdKey:p,stackGroups:l,dataStartIndex:c,dataEndIndex:u}):o&&o.length&&(f=vme(t,{Axis:i,graphicalItems:o,axisType:s,axisIdKey:p,stackGroups:l,dataStartIndex:c,dataEndIndex:u})),f},jme=function(t){var r=qo(t),n=ao(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:aj(n,function(s){return s.coordinate}),tooltipAxis:r,tooltipAxisBandSize:ug(r,n)}},e_=function(t){var r=t.children,n=t.defaultShowTooltip,s=fa(r,qu),i=0,o=0;return t.data&&t.data.length!==0&&(o=t.data.length-1),s&&s.props&&(s.props.startIndex>=0&&(i=s.props.startIndex),s.props.endIndex>=0&&(o=s.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:i,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!n}},Nme=function(t){return!t||!t.length?!1:t.some(function(r){var n=co(r&&r.type);return n&&n.indexOf("Bar")>=0})},t_=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},kme=function(t,r){var n=t.props,s=t.graphicalItems,i=t.xAxisMap,o=i===void 0?{}:i,l=t.yAxisMap,c=l===void 0?{}:l,u=n.width,d=n.height,p=n.children,h=n.margin||{},f=fa(p,qu),x=fa(p,uo),g=Object.keys(c).reduce(function(j,w){var S=c[w],T=S.orientation;return!S.mirror&&!S.hide?be(be({},j),{},Gt({},T,j[T]+S.width)):j},{left:h.left||0,right:h.right||0}),y=Object.keys(o).reduce(function(j,w){var S=o[w],T=S.orientation;return!S.mirror&&!S.hide?be(be({},j),{},Gt({},T,ba(j,"".concat(T))+S.height)):j},{top:h.top||0,bottom:h.bottom||0}),b=be(be({},y),g),v=b.bottom;f&&(b.bottom+=f.props.height||qu.defaultProps.height),x&&r&&(b=Uie(b,s,n,r));var k=u-b.left-b.right,N=d-b.top-b.bottom;return be(be({brushBottom:v},b),{},{width:Math.max(k,0),height:Math.max(N,0)})},Sme=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},ty=function(t){var r=t.chartName,n=t.GraphicalChild,s=t.defaultTooltipEventType,i=s===void 0?"axis":s,o=t.validateTooltipEventTypes,l=o===void 0?["axis"]:o,c=t.axisComponents,u=t.legendContent,d=t.formatAxisMap,p=t.defaultProps,h=function(b,v){var k=v.graphicalItems,N=v.stackGroups,j=v.offset,w=v.updateId,S=v.dataStartIndex,T=v.dataEndIndex,C=b.barSize,A=b.layout,P=b.barGap,E=b.barCategoryGap,_=b.maxBarSize,I=t_(A),D=I.numericAxisName,M=I.cateAxisName,B=Nme(k),$=[];return k.forEach(function(K,R){var Y=ey(b.data,{graphicalItems:[K],dataStartIndex:S,dataEndIndex:T}),Z=K.type.defaultProps!==void 0?be(be({},K.type.defaultProps),K.props):K.props,O=Z.dataKey,ne=Z.maxBarSize,oe=Z["".concat(D,"Id")],he=Z["".concat(M,"Id")],ae={},ve=c.reduce(function(mt,ln){var at=v["".concat(ln.axisType,"Map")],gt=Z["".concat(ln.axisType,"Id")];at&&at[gt]||ln.axisType==="zAxis"||bc();var $t=at[gt];return be(be({},mt),{},Gt(Gt({},ln.axisType,$t),"".concat(ln.axisType,"Ticks"),ao($t)))},ae),re=ve[M],se=ve["".concat(M,"Ticks")],le=N&&N[oe]&&N[oe].hasStack&&Zie(K,N[oe].stackGroups),te=co(K.type).indexOf("Bar")>=0,We=ug(re,se),Me=[],Te=B&&Fie({barSize:C,stackGroups:N,totalSize:Sme(ve,M)});if(te){var Ee,st,xt=an(ne)?_:ne,on=(Ee=(st=ug(re,se,!0))!==null&&st!==void 0?st:xt)!==null&&Ee!==void 0?Ee:0;Me=Bie({barGap:P,barCategoryGap:E,bandSize:on!==We?on:We,sizeList:Te[he],maxBarSize:xt}),on!==We&&(Me=Me.map(function(mt){return be(be({},mt),{},{position:be(be({},mt.position),{},{offset:mt.position.offset-on/2})})}))}var Yt=K&&K.type&&K.type.getComposedData;Yt&&$.push({props:be(be({},Yt(be(be({},ve),{},{displayedData:Y,props:b,dataKey:O,item:K,bandSize:We,barPosition:Me,offset:j,stackedData:le,layout:A,dataStartIndex:S,dataEndIndex:T}))),{},Gt(Gt(Gt({key:K.key||"item-".concat(R)},D,ve[D]),M,ve[M]),"animationId",w)),childIndex:iQ(K,b.children),item:K})}),$},f=function(b,v){var k=b.props,N=b.dataStartIndex,j=b.dataEndIndex,w=b.updateId;if(!z2({props:k}))return null;var S=k.children,T=k.layout,C=k.stackOffset,A=k.data,P=k.reverseStackOrder,E=t_(T),_=E.numericAxisName,I=E.cateAxisName,D=wa(S,n),M=Jie(A,D,"".concat(_,"Id"),"".concat(I,"Id"),C,P),B=c.reduce(function(Z,O){var ne="".concat(O.axisType,"Map");return be(be({},Z),{},Gt({},ne,wme(k,be(be({},O),{},{graphicalItems:D,stackGroups:O.axisType===_&&M,dataStartIndex:N,dataEndIndex:j}))))},{}),$=kme(be(be({},B),{},{props:k,graphicalItems:D}),v==null?void 0:v.legendBBox);Object.keys(B).forEach(function(Z){B[Z]=d(k,B[Z],$,Z.replace("Map",""),r)});var K=B["".concat(I,"Map")],R=jme(K),Y=h(k,be(be({},B),{},{dataStartIndex:N,dataEndIndex:j,updateId:w,graphicalItems:D,stackGroups:M,offset:$}));return be(be({formattedGraphicalItems:Y,graphicalItems:D,offset:$,stackGroups:M},R),B)},x=function(y){function b(v){var k,N,j;return sme(this,b),j=ome(this,b,[v]),Gt(j,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Gt(j,"accessibilityManager",new Hfe),Gt(j,"handleLegendBBoxUpdate",function(w){if(w){var S=j.state,T=S.dataStartIndex,C=S.dataEndIndex,A=S.updateId;j.setState(be({legendBBox:w},f({props:j.props,dataStartIndex:T,dataEndIndex:C,updateId:A},be(be({},j.state),{},{legendBBox:w}))))}}),Gt(j,"handleReceiveSyncEvent",function(w,S,T){if(j.props.syncId===w){if(T===j.eventEmitterSymbol&&typeof j.props.syncMethod!="function")return;j.applySyncEvent(S)}}),Gt(j,"handleBrushChange",function(w){var S=w.startIndex,T=w.endIndex;if(S!==j.state.dataStartIndex||T!==j.state.dataEndIndex){var C=j.state.updateId;j.setState(function(){return be({dataStartIndex:S,dataEndIndex:T},f({props:j.props,dataStartIndex:S,dataEndIndex:T,updateId:C},j.state))}),j.triggerSyncEvent({dataStartIndex:S,dataEndIndex:T})}}),Gt(j,"handleMouseEnter",function(w){var S=j.getMouseInfo(w);if(S){var T=be(be({},S),{},{isTooltipActive:!0});j.setState(T),j.triggerSyncEvent(T);var C=j.props.onMouseEnter;Kt(C)&&C(T,w)}}),Gt(j,"triggeredAfterMouseMove",function(w){var S=j.getMouseInfo(w),T=S?be(be({},S),{},{isTooltipActive:!0}):{isTooltipActive:!1};j.setState(T),j.triggerSyncEvent(T);var C=j.props.onMouseMove;Kt(C)&&C(T,w)}),Gt(j,"handleItemMouseEnter",function(w){j.setState(function(){return{isTooltipActive:!0,activeItem:w,activePayload:w.tooltipPayload,activeCoordinate:w.tooltipPosition||{x:w.cx,y:w.cy}}})}),Gt(j,"handleItemMouseLeave",function(){j.setState(function(){return{isTooltipActive:!1}})}),Gt(j,"handleMouseMove",function(w){w.persist(),j.throttleTriggeredAfterMouseMove(w)}),Gt(j,"handleMouseLeave",function(w){j.throttleTriggeredAfterMouseMove.cancel();var S={isTooltipActive:!1};j.setState(S),j.triggerSyncEvent(S);var T=j.props.onMouseLeave;Kt(T)&&T(S,w)}),Gt(j,"handleOuterEvent",function(w){var S=aQ(w),T=ba(j.props,"".concat(S));if(S&&Kt(T)){var C,A;/.*touch.*/i.test(S)?A=j.getMouseInfo(w.changedTouches[0]):A=j.getMouseInfo(w),T((C=A)!==null&&C!==void 0?C:{},w)}}),Gt(j,"handleClick",function(w){var S=j.getMouseInfo(w);if(S){var T=be(be({},S),{},{isTooltipActive:!0});j.setState(T),j.triggerSyncEvent(T);var C=j.props.onClick;Kt(C)&&C(T,w)}}),Gt(j,"handleMouseDown",function(w){var S=j.props.onMouseDown;if(Kt(S)){var T=j.getMouseInfo(w);S(T,w)}}),Gt(j,"handleMouseUp",function(w){var S=j.props.onMouseUp;if(Kt(S)){var T=j.getMouseInfo(w);S(T,w)}}),Gt(j,"handleTouchMove",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&j.throttleTriggeredAfterMouseMove(w.changedTouches[0])}),Gt(j,"handleTouchStart",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&j.handleMouseDown(w.changedTouches[0])}),Gt(j,"handleTouchEnd",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&j.handleMouseUp(w.changedTouches[0])}),Gt(j,"handleDoubleClick",function(w){var S=j.props.onDoubleClick;if(Kt(S)){var T=j.getMouseInfo(w);S(T,w)}}),Gt(j,"handleContextMenu",function(w){var S=j.props.onContextMenu;if(Kt(S)){var T=j.getMouseInfo(w);S(T,w)}}),Gt(j,"triggerSyncEvent",function(w){j.props.syncId!==void 0&&kb.emit(Sb,j.props.syncId,w,j.eventEmitterSymbol)}),Gt(j,"applySyncEvent",function(w){var S=j.props,T=S.layout,C=S.syncMethod,A=j.state.updateId,P=w.dataStartIndex,E=w.dataEndIndex;if(w.dataStartIndex!==void 0||w.dataEndIndex!==void 0)j.setState(be({dataStartIndex:P,dataEndIndex:E},f({props:j.props,dataStartIndex:P,dataEndIndex:E,updateId:A},j.state)));else if(w.activeTooltipIndex!==void 0){var _=w.chartX,I=w.chartY,D=w.activeTooltipIndex,M=j.state,B=M.offset,$=M.tooltipTicks;if(!B)return;if(typeof C=="function")D=C($,w);else if(C==="value"){D=-1;for(var K=0;K<$.length;K++)if($[K].value===w.activeLabel){D=K;break}}var R=be(be({},B),{},{x:B.left,y:B.top}),Y=Math.min(_,R.x+R.width),Z=Math.min(I,R.y+R.height),O=$[D]&&$[D].value,ne=tw(j.state,j.props.data,D),oe=$[D]?{x:T==="horizontal"?$[D].coordinate:Y,y:T==="horizontal"?Z:$[D].coordinate}:ND;j.setState(be(be({},w),{},{activeLabel:O,activeCoordinate:oe,activePayload:ne,activeTooltipIndex:D}))}else j.setState(w)}),Gt(j,"renderCursor",function(w){var S,T=j.state,C=T.isTooltipActive,A=T.activeCoordinate,P=T.activePayload,E=T.offset,_=T.activeTooltipIndex,I=T.tooltipAxisBandSize,D=j.getTooltipEventType(),M=(S=w.props.active)!==null&&S!==void 0?S:C,B=j.props.layout,$=w.key||"_recharts-cursor";return H.createElement(Xfe,{key:$,activeCoordinate:A,activePayload:P,activeTooltipIndex:_,chartName:r,element:w,isActive:M,layout:B,offset:E,tooltipAxisBandSize:I,tooltipEventType:D})}),Gt(j,"renderPolarAxis",function(w,S,T){var C=ba(w,"type.axisType"),A=ba(j.state,"".concat(C,"Map")),P=w.type.defaultProps,E=P!==void 0?be(be({},P),w.props):w.props,_=A&&A[E["".concat(C,"Id")]];return m.cloneElement(w,be(be({},_),{},{className:fn(C,_.className),key:w.key||"".concat(S,"-").concat(T),ticks:ao(_,!0)}))}),Gt(j,"renderPolarGrid",function(w){var S=w.props,T=S.radialLines,C=S.polarAngles,A=S.polarRadius,P=j.state,E=P.radiusAxisMap,_=P.angleAxisMap,I=qo(E),D=qo(_),M=D.cx,B=D.cy,$=D.innerRadius,K=D.outerRadius;return m.cloneElement(w,{polarAngles:Array.isArray(C)?C:ao(D,!0).map(function(R){return R.coordinate}),polarRadius:Array.isArray(A)?A:ao(I,!0).map(function(R){return R.coordinate}),cx:M,cy:B,innerRadius:$,outerRadius:K,key:w.key||"polar-grid",radialLines:T})}),Gt(j,"renderLegend",function(){var w=j.state.formattedGraphicalItems,S=j.props,T=S.children,C=S.width,A=S.height,P=j.props.margin||{},E=C-(P.left||0)-(P.right||0),_=nR({children:T,formattedGraphicalItems:w,legendWidth:E,legendContent:u});if(!_)return null;var I=_.item,D=XA(_,Zfe);return m.cloneElement(I,be(be({},D),{},{chartWidth:C,chartHeight:A,margin:P,onBBoxUpdate:j.handleLegendBBoxUpdate}))}),Gt(j,"renderTooltip",function(){var w,S=j.props,T=S.children,C=S.accessibilityLayer,A=fa(T,ga);if(!A)return null;var P=j.state,E=P.isTooltipActive,_=P.activeCoordinate,I=P.activePayload,D=P.activeLabel,M=P.offset,B=(w=A.props.active)!==null&&w!==void 0?w:E;return m.cloneElement(A,{viewBox:be(be({},M),{},{x:M.left,y:M.top}),active:B,label:D,payload:B?I:[],coordinate:_,accessibilityLayer:C})}),Gt(j,"renderBrush",function(w){var S=j.props,T=S.margin,C=S.data,A=j.state,P=A.offset,E=A.dataStartIndex,_=A.dataEndIndex,I=A.updateId;return m.cloneElement(w,{key:w.key||"_recharts-brush",onChange:Lf(j.handleBrushChange,w.props.onChange),data:C,x:Oe(w.props.x)?w.props.x:P.left,y:Oe(w.props.y)?w.props.y:P.top+P.height+P.brushBottom-(T.bottom||0),width:Oe(w.props.width)?w.props.width:P.width,startIndex:E,endIndex:_,updateId:"brush-".concat(I)})}),Gt(j,"renderReferenceElement",function(w,S,T){if(!w)return null;var C=j,A=C.clipPathId,P=j.state,E=P.xAxisMap,_=P.yAxisMap,I=P.offset,D=w.type.defaultProps||{},M=w.props,B=M.xAxisId,$=B===void 0?D.xAxisId:B,K=M.yAxisId,R=K===void 0?D.yAxisId:K;return m.cloneElement(w,{key:w.key||"".concat(S,"-").concat(T),xAxis:E[$],yAxis:_[R],viewBox:{x:I.left,y:I.top,width:I.width,height:I.height},clipPathId:A})}),Gt(j,"renderActivePoints",function(w){var S=w.item,T=w.activePoint,C=w.basePoint,A=w.childIndex,P=w.isRange,E=[],_=S.props.key,I=S.item.type.defaultProps!==void 0?be(be({},S.item.type.defaultProps),S.item.props):S.item.props,D=I.activeDot,M=I.dataKey,B=be(be({index:A,dataKey:M,cx:T.x,cy:T.y,r:4,fill:Ej(S.item),strokeWidth:2,stroke:"#fff",payload:T.payload,value:T.value},Pt(D,!1)),Fm(D));return E.push(b.renderActiveDot(D,B,"".concat(_,"-activePoint-").concat(A))),C?E.push(b.renderActiveDot(D,be(be({},B),{},{cx:C.x,cy:C.y}),"".concat(_,"-basePoint-").concat(A))):P&&E.push(null),E}),Gt(j,"renderGraphicChild",function(w,S,T){var C=j.filterFormatItem(w,S,T);if(!C)return null;var A=j.getTooltipEventType(),P=j.state,E=P.isTooltipActive,_=P.tooltipAxis,I=P.activeTooltipIndex,D=P.activeLabel,M=j.props.children,B=fa(M,ga),$=C.props,K=$.points,R=$.isRange,Y=$.baseLine,Z=C.item.type.defaultProps!==void 0?be(be({},C.item.type.defaultProps),C.item.props):C.item.props,O=Z.activeDot,ne=Z.hide,oe=Z.activeBar,he=Z.activeShape,ae=!!(!ne&&E&&B&&(O||oe||he)),ve={};A!=="axis"&&B&&B.props.trigger==="click"?ve={onClick:Lf(j.handleItemMouseEnter,w.props.onClick)}:A!=="axis"&&(ve={onMouseLeave:Lf(j.handleItemMouseLeave,w.props.onMouseLeave),onMouseEnter:Lf(j.handleItemMouseEnter,w.props.onMouseEnter)});var re=m.cloneElement(w,be(be({},C.props),ve));function se(ln){return typeof _.dataKey=="function"?_.dataKey(ln.payload):null}if(ae)if(I>=0){var le,te;if(_.dataKey&&!_.allowDuplicatedCategory){var We=typeof _.dataKey=="function"?se:"payload.".concat(_.dataKey.toString());le=$m(K,We,D),te=R&&Y&&$m(Y,We,D)}else le=K==null?void 0:K[I],te=R&&Y&&Y[I];if(he||oe){var Me=w.props.activeIndex!==void 0?w.props.activeIndex:I;return[m.cloneElement(w,be(be(be({},C.props),ve),{},{activeIndex:Me})),null,null]}if(!an(le))return[re].concat(ed(j.renderActivePoints({item:C,activePoint:le,basePoint:te,childIndex:I,isRange:R})))}else{var Te,Ee=(Te=j.getItemByXY(j.state.activeCoordinate))!==null&&Te!==void 0?Te:{graphicalItem:re},st=Ee.graphicalItem,xt=st.item,on=xt===void 0?w:xt,Yt=st.childIndex,mt=be(be(be({},C.props),ve),{},{activeIndex:Yt});return[m.cloneElement(on,mt),null,null]}return R?[re,null,null]:[re,null]}),Gt(j,"renderCustomized",function(w,S,T){return m.cloneElement(w,be(be({key:"recharts-customized-".concat(T)},j.props),j.state))}),Gt(j,"renderMap",{CartesianGrid:{handler:zf,once:!0},ReferenceArea:{handler:j.renderReferenceElement},ReferenceLine:{handler:zf},ReferenceDot:{handler:j.renderReferenceElement},XAxis:{handler:zf},YAxis:{handler:zf},Brush:{handler:j.renderBrush,once:!0},Bar:{handler:j.renderGraphicChild},Line:{handler:j.renderGraphicChild},Area:{handler:j.renderGraphicChild},Radar:{handler:j.renderGraphicChild},RadialBar:{handler:j.renderGraphicChild},Scatter:{handler:j.renderGraphicChild},Pie:{handler:j.renderGraphicChild},Funnel:{handler:j.renderGraphicChild},Tooltip:{handler:j.renderCursor,once:!0},PolarGrid:{handler:j.renderPolarGrid,once:!0},PolarAngleAxis:{handler:j.renderPolarAxis},PolarRadiusAxis:{handler:j.renderPolarAxis},Customized:{handler:j.renderCustomized}}),j.clipPathId="".concat((k=v.id)!==null&&k!==void 0?k:Sc("recharts"),"-clip"),j.throttleTriggeredAfterMouseMove=t4(j.triggeredAfterMouseMove,(N=v.throttleDelay)!==null&&N!==void 0?N:1e3/60),j.state={},j}return ume(b,y),ime(b,[{key:"componentDidMount",value:function(){var k,N;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(k=this.props.margin.left)!==null&&k!==void 0?k:0,top:(N=this.props.margin.top)!==null&&N!==void 0?N:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var k=this.props,N=k.children,j=k.data,w=k.height,S=k.layout,T=fa(N,ga);if(T){var C=T.props.defaultIndex;if(!(typeof C!="number"||C<0||C>this.state.tooltipTicks.length-1)){var A=this.state.tooltipTicks[C]&&this.state.tooltipTicks[C].value,P=tw(this.state,j,C,A),E=this.state.tooltipTicks[C].coordinate,_=(this.state.offset.top+w)/2,I=S==="horizontal",D=I?{x:E,y:_}:{y:E,x:_},M=this.state.formattedGraphicalItems.find(function($){var K=$.item;return K.type.name==="Scatter"});M&&(D=be(be({},D),M.props.points[C].tooltipPosition),P=M.props.points[C].tooltipPayload);var B={activeTooltipIndex:C,isTooltipActive:!0,activeLabel:A,activePayload:P,activeCoordinate:D};this.setState(B),this.renderCursor(T),this.accessibilityManager.setIndex(C)}}}},{key:"getSnapshotBeforeUpdate",value:function(k,N){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==N.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==k.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==k.margin){var j,w;this.accessibilityManager.setDetails({offset:{left:(j=this.props.margin.left)!==null&&j!==void 0?j:0,top:(w=this.props.margin.top)!==null&&w!==void 0?w:0}})}return null}},{key:"componentDidUpdate",value:function(k){M0([fa(k.children,ga)],[fa(this.props.children,ga)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var k=fa(this.props.children,ga);if(k&&typeof k.props.shared=="boolean"){var N=k.props.shared?"axis":"item";return l.indexOf(N)>=0?N:i}return i}},{key:"getMouseInfo",value:function(k){if(!this.container)return null;var N=this.container,j=N.getBoundingClientRect(),w=mne(j),S={chartX:Math.round(k.pageX-w.left),chartY:Math.round(k.pageY-w.top)},T=j.width/N.offsetWidth||1,C=this.inRange(S.chartX,S.chartY,T);if(!C)return null;var A=this.state,P=A.xAxisMap,E=A.yAxisMap,_=this.getTooltipEventType(),I=QA(this.state,this.props.data,this.props.layout,C);if(_!=="axis"&&P&&E){var D=qo(P).scale,M=qo(E).scale,B=D&&D.invert?D.invert(S.chartX):null,$=M&&M.invert?M.invert(S.chartY):null;return be(be({},S),{},{xValue:B,yValue:$},I)}return I?be(be({},S),I):null}},{key:"inRange",value:function(k,N){var j=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,w=this.props.layout,S=k/j,T=N/j;if(w==="horizontal"||w==="vertical"){var C=this.state.offset,A=S>=C.left&&S<=C.left+C.width&&T>=C.top&&T<=C.top+C.height;return A?{x:S,y:T}:null}var P=this.state,E=P.angleAxisMap,_=P.radiusAxisMap;if(E&&_){var I=qo(E);return kP({x:S,y:T},I)}return null}},{key:"parseEventsOfWrapper",value:function(){var k=this.props.children,N=this.getTooltipEventType(),j=fa(k,ga),w={};j&&N==="axis"&&(j.props.trigger==="click"?w={onClick:this.handleClick}:w={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var S=Fm(this.props,this.handleOuterEvent);return be(be({},S),w)}},{key:"addListener",value:function(){kb.on(Sb,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){kb.removeListener(Sb,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(k,N,j){for(var w=this.state.formattedGraphicalItems,S=0,T=w.length;S<T;S++){var C=w[S];if(C.item===k||C.props.key===k.key||N===co(C.item.type)&&j===C.childIndex)return C}return null}},{key:"renderClipPath",value:function(){var k=this.clipPathId,N=this.state.offset,j=N.left,w=N.top,S=N.height,T=N.width;return H.createElement("defs",null,H.createElement("clipPath",{id:k},H.createElement("rect",{x:j,y:w,height:S,width:T})))}},{key:"getXScales",value:function(){var k=this.state.xAxisMap;return k?Object.entries(k).reduce(function(N,j){var w=JA(j,2),S=w[0],T=w[1];return be(be({},N),{},Gt({},S,T.scale))},{}):null}},{key:"getYScales",value:function(){var k=this.state.yAxisMap;return k?Object.entries(k).reduce(function(N,j){var w=JA(j,2),S=w[0],T=w[1];return be(be({},N),{},Gt({},S,T.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(k){var N;return(N=this.state.xAxisMap)===null||N===void 0||(N=N[k])===null||N===void 0?void 0:N.scale}},{key:"getYScaleByAxisId",value:function(k){var N;return(N=this.state.yAxisMap)===null||N===void 0||(N=N[k])===null||N===void 0?void 0:N.scale}},{key:"getItemByXY",value:function(k){var N=this.state,j=N.formattedGraphicalItems,w=N.activeItem;if(j&&j.length)for(var S=0,T=j.length;S<T;S++){var C=j[S],A=C.props,P=C.item,E=P.type.defaultProps!==void 0?be(be({},P.type.defaultProps),P.props):P.props,_=co(P.type);if(_==="Bar"){var I=(A.data||[]).find(function($){return Bce(k,$)});if(I)return{graphicalItem:C,payload:I}}else if(_==="RadialBar"){var D=(A.data||[]).find(function($){return kP(k,$)});if(D)return{graphicalItem:C,payload:D}}else if(Gx(C,w)||Kx(C,w)||mh(C,w)){var M=lde({graphicalItem:C,activeTooltipItem:w,itemData:E.data}),B=E.activeIndex===void 0?M:E.activeIndex;return{graphicalItem:be(be({},C),{},{childIndex:B}),payload:mh(C,w)?E.data[M]:C.props.data[M]}}}return null}},{key:"render",value:function(){var k=this;if(!z2(this))return null;var N=this.props,j=N.children,w=N.className,S=N.width,T=N.height,C=N.style,A=N.compact,P=N.title,E=N.desc,_=XA(N,Qfe),I=Pt(_,!1);if(A)return H.createElement(TA,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},H.createElement($0,du({},I,{width:S,height:T,title:P,desc:E}),this.renderClipPath(),H2(j,this.renderMap)));if(this.props.accessibilityLayer){var D,M;I.tabIndex=(D=this.props.tabIndex)!==null&&D!==void 0?D:0,I.role=(M=this.props.role)!==null&&M!==void 0?M:"application",I.onKeyDown=function($){k.accessibilityManager.keyboardEvent($)},I.onFocus=function(){k.accessibilityManager.focus()}}var B=this.parseEventsOfWrapper();return H.createElement(TA,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},H.createElement("div",du({className:fn("recharts-wrapper",w),style:be({position:"relative",curs
7003or:"default",width:S,height:T},C)},B,{ref:function(K){k.container=K}}),H.createElement($0,du({},I,{width:S,height:T,title:P,desc:E,style:gme}),this.renderClipPath(),H2(j,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(m.Component);Gt(x,"displayName",r),Gt(x,"defaultProps",be({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},p)),Gt(x,"getDerivedStateFromProps",function(y,b){var v=y.dataKey,k=y.data,N=y.children,j=y.width,w=y.height,S=y.layout,T=y.stackOffset,C=y.margin,A=b.dataStartIndex,P=b.dataEndIndex;if(b.updateId===void 0){var E=e_(y);return be(be(be({},E),{},{updateId:0},f(be(be({props:y},E),{},{updateId:0}),b)),{},{prevDataKey:v,prevData:k,prevWidth:j,prevHeight:w,prevLayout:S,prevStackOffset:T,prevMargin:C,prevChildren:N})}if(v!==b.prevDataKey||k!==b.prevData||j!==b.prevWidth||w!==b.prevHeight||S!==b.prevLayout||T!==b.prevStackOffset||!xu(C,b.prevMargin)){var _=e_(y),I={chartX:b.chartX,chartY:b.chartY,isTooltipActive:b.isTooltipActive},D=be(be({},QA(b,k,S)),{},{updateId:b.updateId+1}),M=be(be(be({},_),I),D);return be(be(be({},M),f(be({props:y},M),b)),{},{prevDataKey:v,prevData:k,prevWidth:j,prevHeight:w,prevLayout:S,prevStackOffset:T,prevMargin:C,prevChildren:N})}if(!M0(N,b.prevChildren)){var B,$,K,R,Y=fa(N,qu),Z=Y&&(B=($=Y.props)===null||$===void 0?void 0:$.startIndex)!==null&&B!==void 0?B:A,O=Y&&(K=(R=Y.props)===null||R===void 0?void 0:R.endIndex)!==null&&K!==void 0?K:P,ne=Z!==A||O!==P,oe=!an(k),he=oe&&!ne?b.updateId:b.updateId+1;return be(be({updateId:he},f(be(be({props:y},b),{},{updateId:he,dataStartIndex:Z,dataEndIndex:O}),b)),{},{prevChildren:N,dataStartIndex:Z,dataEndIndex:O})}return null}),Gt(x,"renderActiveDot",function(y,b,v){var k;return m.isValidElement(y)?k=m.cloneElement(y,b):Kt(y)?k=y(b):k=H.createElement(Uh,b),H.createElement(Tn,{className:"recharts-active-dot",key:v},k)});var g=m.forwardRef(function(b,v){return H.createElement(x,du({},b,{ref:v}))});return g.displayName=x.displayName,g},Cme=ty({chartName:"LineChart",GraphicalChild:gd,axisComponents:[{axisType:"xAxis",AxisComp:nl},{axisType:"yAxis",AxisComp:rl}],formatAxisMap:Oj}),Pme=ty({chartName:"BarChart",GraphicalChild:_c,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:nl},{axisType:"yAxis",AxisComp:rl}],formatAxisMap:Oj}),Ame=ty({chartName:"PieChart",GraphicalChild:wo,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:Vx},{axisType:"radiusAxis",AxisComp:Hx}],formatAxisMap:loe,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}}),_me=ty({chartName:"AreaChart",GraphicalChild:ml,axisComponents:[{axisType:"xAxis",AxisComp:nl},{axisType:"yAxis",AxisComp:rl}],formatAxisMap:Oj});const Xc=["hsl(var(--primary))","hsl(var(--accent))","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#ec4899"];function Tme(e){if(!e||e.length===0)return"table";const t=Object.keys(e[0]),r=t.filter(s=>typeof e[0][s]=="number"),n=t.filter(s=>typeof e[0][s]=="string");return r.length===1&&n.length===1&&e.length<=10?"pie":r.length>=1&&n.length>=1?"bar":r.length>=2?"line":"table"}function Eme({data:e,sql:t,error:r,isLoading:n}){const[s,i]=m.useState("bar");m.useEffect(()=>{e&&e.length>0&&i(Tme(e))},[e]);const o=[{id:"bar",label:"Bar",icon:si},{id:"line",label:"Line",icon:Sw},{id:"pie",label:"Pie",icon:z$},{id:"table",label:"Table",icon:Di}];if(n)return a.jsx("div",{className:"h-full flex items-center justify-center",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx("div",{className:"w-12 h-12 mx-auto rounded-2xl bg-primary/10 flex items-center justify-center animate-pulse",children:a.jsx(si,{className:"w-6 h-6 text-primary"})}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Running query..."}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Analyzing your data"})]})});if(r)return a.jsx("div",{className:"h-full flex items-center justify-center p-8",children:a.jsxs("div",{className:"text-center space-y-2 max-w-sm",children:[a.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),a.jsx("p",{className:"text-xs text-muted-foreground font-mono bg-destructive/10 p-3 rounded-lg",children:r})]})});if(!e||e.length===0)return a.jsx("div",{className:"h-full flex items-center justify-center",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx("div",{className:"w-14 h-14 mx-auto rounded-2xl bg-gradient-to-br from-primary/10 to-accent/10 flex items-center justify-center",children:a.jsx(si,{className:"w-7 h-7 text-primary/60"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Data Copilot"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Ask a question about your data in natural language"})]})]})});const l=Object.keys(e[0]),c=l.filter(d=>typeof e[0][d]=="number"),u=l.find(d=>typeof e[0][d]=="string")||l[0];return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx("div",{className:"flex items-center gap-0.5 bg-secondary rounded-lg p-0.5",children:o.map(d=>a.jsxs("button",{onClick:()=>i(d.id),className:L("flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition-colors",s===d.id?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[a.jsx(d.icon,{className:"w-3.5 h-3.5"}),d.label]},d.id))}),a.jsxs("span",{className:"ml-auto text-[10px] text-muted-foreground",children:[e.length," rows"]})]}),t&&a.jsx("div",{className:"border-b px-3 py-2 bg-secondary/30",children:a.jsx("pre",{className:"text-[10px] font-mono text-muted-foreground truncate",children:t})}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:s==="table"?a.jsx($r,{className:"h-full",children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsx("tr",{className:"border-b bg-secondary/30",children:l.map(d=>a.jsx("th",{className:"px-3 py-2 text-left font-semibold text-foreground whitespace-nowrap",children:d},d))})}),a.jsx("tbody",{children:e.map((d,p)=>a.jsx("tr",{className:"border-b hover:bg-secondary/20 transition-colors",children:l.map(h=>
7003a.jsx("td",{className:"px-3 py-1.5 text-foreground/80 whitespace-nowrap max-w-[300px] truncate font-mono",children:typeof d[h]=="object"?JSON.stringify(d[h]):String(d[h]??"")},h))},p))})]})})}):s==="pie"?a.jsx(dm,{width:"100%",height:"100%",children:a.jsxs(Ame,{children:[a.jsx(wo,{data:e,dataKey:c[0]||l[1],nameKey:u,cx:"50%",cy:"50%",outerRadius:"70%",label:({name:d,percent:p})=>`${d} ${(p*100).toFixed(0)}%`,children:e.map((d,p)=>a.jsx(Ix,{fill:Xc[p%Xc.length]},p))}),a.jsx(ga,{}),a.jsx(uo,{})]})}):s==="line"?a.jsx(dm,{width:"100%",height:"100%",children:a.jsxs(Cme,{data:e,children:[a.jsx(Ig,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),a.jsx(nl,{dataKey:u,tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),a.jsx(rl,{tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),a.jsx(ga,{}),a.jsx(uo,{}),c.map((d,p)=>a.jsx(gd,{type:"monotone",dataKey:d,stroke:Xc[p%Xc.length],strokeWidth:2,dot:{r:3}},d))]})}):a.jsx(dm,{width:"100%",height:"100%",children:a.jsxs(Pme,{data:e,children:[a.jsx(Ig,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),a.jsx(nl,{dataKey:u,tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),a.jsx(rl,{tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),a.jsx(ga,{}),a.jsx(uo,{}),c.map((d,p)=>a.jsx(_c,{dataKey:d,fill:Xc[p%Xc.length],radius:[4,4,0,0]},d))]})})})]})}function SD(e){const[t,r]=m.useState(null),n=m.useRef(!1),{connections:s,runQuery:i}=Rh(e),{connections:o,callTool:l}=z1(e),c=m.useCallback((g,y)=>{r(b=>b&&{...b,steps:b.steps.map(v=>v.stepId===g?{...v,...y}:v)})},[]),u=m.useCallback((g,y)=>{r(b=>b&&{...b,steps:b.steps.map(v=>v.stepId===g?{...v,logs:[...v.logs,y]}:v)})},[]),d=g=>new Promise(y=>setTimeout(y,g)),p=m.useCallback(async(g,y)=>{var b,v,k,N,j,w;switch(g.type){case"trigger":return{output:{triggered:!0,...y}};case"action":{const S=g.config||{};if(S.sql||S.query){const T=S.sql||S.query;if(s.length===0)throw new Error("No database connected");const C=s[0],A=await i(C.id,T);return{output:{rows:A.rows,rowCount:A.rowCount}}}if(S.mcpTool||S.tool){const T=S.mcpTool||S.tool,C=S.args||S.arguments||{};if(o.length===0)throw new Error("No MCP servers connected");const A=o.find(E=>E.is_active)||o[0];return{output:await l(A,T,C)}}if(S.url){const T=S.method||"GET",C=S.headers||{},A=S.body?JSON.stringify(S.body):void 0,P=await fetch(S.url,{method:T,headers:C,body:A}),E=await P.json().catch(()=>P.text());return{output:{status:P.status,data:E}}}if(S.transform)try{return{output:new Function("context","data",S.transform)(y,y._lastOutput)}}catch(T){throw new Error(`Transform error: ${T.message}`)}return{output:{message:`Action "${g.name}" completed (no handler configured)`}}}case"condition":{const S=g.config||{};let T=!1;if(S.expression)try{T=new Function("context","data",`return !!(${S.expression})`)(y,y._lastOutput)}catch{T=!1}else if(S.field&&S.operator){const A=((b=y._lastOutput)==null?void 0:b[S.field])??y[S.field],P=S.value;switch(S.operator){case"eq":case"==":T=A==P;break;case"neq":case"!=":T=A!=P;break;case"gt":case">":T=A>P;break;case"lt":case"<":T=A<P;break;case"gte":case">=":T=A>=P;break;case"lte":case"<=":T=A<=P;break;case"contains":T=String(A).includes(String(P));break;default:T=!!A}}else T=!!y._lastOutput;const C=T?(v=g.condition)==null?void 0:v.ifTrue:(k=g.condition)==null?void 0:k.ifFalse;return{output:{condition:T},nextStepId:C}}case"delay":{const S=(((N=g.config)==null?void 0:N.seconds)||((j=g.config)==null?void 0:j.duration)||1)*1e3;return await d(Math.min(S,3e4)),{output:{delayed:S}}}case"loop":{const S=g.config||{},T=((w=y._lastOutput)==null?void 0:w.rows)||y._lastOutput||[],C=[],A=S.maxIterations||100;if(Array.isArray(T))for(let P=0;P<Math.min(T.length,A)&&!n.current;P++)C.push(T[P]);return{output:{iterations:C.length,items:C}}}case"integration":{const S=g.config||{},T=(S.service||S.provider||"").toLowerCase(),C=S.action||"send";if(S.mcpTool||S.tool){const A=S.mcpTool||S.tool,P=S.args||S.arguments||S.params||{};if(o.length===0)throw new Error(`No MCP servers connected. Connect an MCP server (e.g. n8n) to use ${T||"integration"} tools.`);const E=o.find(I=>I.is_active)||o[0];return{output:await l(E,A,P)}}if(S.url||S.webhook){const A=S.url||S.webhook,P=S.method||"POST",E={"Content-Type":"application/json",...S.headers||{}};S.apiKey&&(E.Authorization=`Bearer ${S.apiKey}`);const _=S.body||S.payload||S.message?JSON.stringify(S.body||S.payload||{text:S.message}):void 0,I=await fetch(A,{method:P,headers:E,body:_}),D=await I.json().catch(()=>I.text());if(!I.ok)throw new Error(`Integration ${T} failed [${I.status}
7003]: ${typeof D=="string"?D:JSON.stringify(D)}`);return{output:{status:I.status,service:T,action:C,data:D}}}if(S.edgeFunction){const{data:A,error:P}=await G.functions.invoke(S.edgeFunction,{body:S.payload||S.params||{service:T,action:C,...S}});if(P)throw new Error(`Edge function ${S.edgeFunction} failed: ${P.message}`);return{output:{service:T,action:C,data:A}}}return{output:{message:`Integration "${g.name}" completed (configure url, mcpTool, or edgeFunction)`,service:T,action:C}}}case"end":return{output:{finished:!0,finalContext:y}};default:return{output:{message:`Unknown step type: ${g.type}`}}}},[s,i,o,l]),h=m.useCallback(async(g,y)=>{n.current=!1;const b={id:`exec-${Date.now()}`,workflowName:g.name,status:"running",startedAt:Date.now(),steps:g.steps.map(N=>({stepId:N.id,status:"pending",logs:[]})),context:{...y}};r(b);const v={...y};new Map(g.steps.map(N=>[N.id,N]));let k=0;try{for(;k<g.steps.length;){if(n.current){r(j=>j&&{...j,status:"cancelled",finishedAt:Date.now()});return}const N=g.steps[k];c(N.id,{status:"running",startedAt:Date.now()}),u(N.id,`Starting: ${N.name}`);try{const{output:j,nextStepId:w}=await p(N,v);if(v._lastOutput=j,v[N.id]=j,c(N.id,{status:"done",finishedAt:Date.now(),output:j}),u(N.id,"Completed successfully"),w){const S=g.steps.findIndex(T=>T.id===w);if(S!==-1){u(N.id,`Branching to: ${w}`),k=S;continue}}if(N.next&&N.next.length>0){const S=g.steps.findIndex(T=>T.id===N.next[0]);if(S!==-1){k=S;continue}}k++}catch(j){c(N.id,{status:"error",finishedAt:Date.now(),error:j.message}),u(N.id,`Error: ${j.message}`);for(let w=k+1;w<g.steps.length;w++)c(g.steps[w].id,{status:"skipped"});r(w=>w&&{...w,status:"error",finishedAt:Date.now(),context:v});return}}r(N=>N&&{...N,status:"done",finishedAt:Date.now(),context:v})}catch{r(j=>j&&{...j,status:"error",finishedAt:Date.now()})}},[p,c,u]),f=m.useCallback(()=>{n.current=!0},[]),x=m.useCallback(()=>{r(null),n.current=!1},[]);return{execution:t,run:h,cancel:f,reset:x}}const Ime={trigger:Oi,action:hr,condition:oo,delay:Lr,loop:x6,end:cT,integration:Ma},n_={trigger:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",action:"bg-primary/10 text-primary border-primary/20",condition:"bg-amber-500/10 text-amber-600 border-amber-500/20",delay:"bg-sky-500/10 text-sky-600 border-sky-500/20",loop:"bg-violet-500/10 text-violet-600 border-violet-500/20",end:"bg-muted text-muted-foreground border-border",integration:"bg-pink-500/10 text-pink-600 border-pink-500/20"},r_={pending:{icon:Lr,className:"text-muted-foreground/40"},running:{icon:ze,className:"text-primary animate-spin"},done:{icon:mn,className:"text-emerald-500"},error:{icon:aa,className:"text-destructive"},skipped:{icon:w6,className:"text-muted-foreground/50"}};function Ome(e){try{const t=new WeakSet;return JSON.stringify(e,(r,n)=>{if(r==="_lastOutput"||r==="finalContext")return"[ref]";if(typeof n=="object"&&n!==null){if(t.has(n))return"[circular]";t.add(n)}return n},2)}catch{return String(e)}}function Rme({step:e,index:t,execStep:r}){const n=Ime[e.type]||hr,s=n_[e.type]||n_.action,i=r==null?void 0:r.status,o=i?r_[i].icon:null,l=i?r_[i].className:"";return a.jsxs("div",{className:L("border rounded-xl p-4 transition-all hover:shadow-md relative",s,i==="running"&&"ring-2 ring-primary/30",i==="error"&&"ring-2 ring-destructive/30",i==="done"&&"opacity-90",i==="skipped"&&"opacity-40"),children:[o&&a.jsx("div",{className:L("absolute top-3 right-3",l),children:a.jsx(o,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:L("w-8 h-8 rounded-lg flex items-center justify-center shrink-0",s),children:a.jsx(n,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",children:["#",t+1]}),a.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider opacity-70 shrink-0",children:e.type}),(r==null?void 0:r.finishedAt)&&(r==null?void 0:r.startedAt)&&a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground ml-auto shrink-0",children:[((r.finishedAt-r.startedAt)/1e3).toFixed(1),"s"]})]}),a.jsx("p",{className:"text-sm font-semibold mt-0.5 break-words",children:e.name}),e.description&&a.jsx("p",{className:"text-xs opacity-80 mt-1 leading-relaxed break-words",children:e.description}),e.config&&Object.keys(e.config).length>0&&a.jsx("div",{className:"mt-2 space-y-1 overflow-hidden",children:Object.entries(e.config).map(([c,u])=>a.jsxs("div",{className:"text-[10px] font-mono flex gap-1 break-all",children:[a.jsxs("span",{className:"opacity-60 shrink-0",children:[c,":"]}),a.jsx("span",{className:"opacity-90 truncate",children:typeof u=="object"?JSON.stringify(u):String(u)})]},c))}),e.condition&&a.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[10px]",children:[a.jsxs("span",{className:"bg-emerald-500/20 text-emerald-700 px-2 py-0.5 rounded-full",children:["✓ ",e.condition.ifTrue]}),a.jsxs("span",{className:"bg-rose-500/20 text-rose-700 px-2 py-0.5 rounded-full",children:["✗ ",e.condition.ifFalse]})]}),r&&r.logs.length>0&&a.jsx("div",{className:"mt-2 space-y-0.5 border-t border-current/10 pt-2",children:r.logs.map((c,u)=>a.jsx("p",{className:"text-[10px] font-mono opacity-60 break-words",children:c},u))}),(r==null?void 0:r.error)&&a.jsxs("div",{className:"mt-2 flex items-start gap-1.5 text-destructive",children:[a.jsx(Ar,{className:"w-3 h-3 shrink-0 mt-0.5"}),a.jsx("p",{className:"text-[10px] font-mono break-words",children:r.error})]}),(r==null?void 0:r.output)&&r.status==="done"&&a.jsxs("details",{className:"mt-2",children:[a.jsx("summary",{className:"text-[10px] font-mono curs
7003or-pointer opacity-50 hover:opacity-80",children:"View output"}),a.jsx("pre",{className:"text-[10px] font-mono mt-1 p-2 rounded bg-foreground/5 overflow-auto max-h-24 whitespace-pre-wrap break-all",children:Ome(r.output)})]})]})]})]})}function Dme({workflow:e}){const{project:t}=gn(),{execution:r,run:n,cancel:s,reset:i}=SD((t==null?void 0:t.id)||null),o=()=>{e&&(W.info(`Running workflow: ${e.name}`),n(e))};if(!e)return a.jsx("div",{className:"h-full flex items-center justify-center",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx("div",{className:"w-14 h-14 mx-auto rounded-2xl bg-gradient-to-br from-primary/10 to-accent/10 flex items-center justify-center",children:a.jsx(Ri,{className:"w-7 h-7 text-primary/60"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Workflow Builder"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Describe a workflow and AI will generate the automation steps"})]})]})});const l=new Map(r==null?void 0:r.steps.map(p=>[p.stepId,p])),c=(r==null?void 0:r.status)==="running",u=(r==null?void 0:r.status)==="done",d=(r==null?void 0:r.status)==="error";return a.jsx($r,{className:"h-full",children:a.jsxs("div",{className:"p-4 sm:p-6",children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("h3",{className:"text-base font-bold text-foreground break-words",children:e.name}),e.description&&a.jsx("p",{className:"text-xs text-muted-foreground mt-1 break-words",children:e.description}),a.jsxs("div",{className:"flex items-center justify-center gap-2 mt-2 text-[10px] text-muted-foreground",children:[a.jsxs("span",{children:[e.steps.length," steps"]}),a.jsx("span",{children:"•"}),a.jsxs("span",{children:[e.steps.filter(p=>p.type==="condition").length," conditions"]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4 flex-wrap",children:[!c&&a.jsxs(Q,{size:"sm",className:"h-8 text-xs gap-1.5",onClick:o,children:[a.jsx(Oi,{className:"w-3.5 h-3.5"}),u||d?"Run Again":"Run Workflow"]}),c&&a.jsxs(Q,{size:"sm",variant:"destructive",className:"h-8 text-xs gap-1.5",onClick:s,children:[a.jsx(cT,{className:"w-3.5 h-3.5"}),"Cancel"]}),(u||d)&&a.jsxs(Q,{size:"sm",variant:"outline",className:"h-8 text-xs gap-1.5",onClick:i,children:[a.jsx(Ri,{className:"w-3.5 h-3.5"}),"Reset"]})]}),r&&a.jsxs("div",{className:L("mt-3 inline-flex items-center gap-1.5 text-[11px] font-medium px-3 py-1 rounded-full",r.status==="running"&&"bg-primary/10 text-primary",r.status==="done"&&"bg-emerald-500/10 text-emerald-600",r.status==="error"&&"bg-destructive/10 text-destructive",r.status==="cancelled"&&"bg-muted text-muted-foreground"),children:[r.status==="running"&&a.jsx(ze,{className:"w-3 h-3 animate-spin"}),r.status==="done"&&a.jsx(mn,{className:"w-3 h-3"}),r.status==="error"&&a.jsx(aa,{className:"w-3 h-3"}),r.status==="running"&&"Running...",r.status==="done"&&`Completed in ${((r.finishedAt-r.startedAt)/1e3).toFixed(1)}s`,r.status==="error"&&"Failed",r.status==="cancelled"&&"Cancelled"]})]}),a.jsx("div",{className:"space-y-2 max-w-lg mx-auto",children:e.steps.map((p,h)=>a.jsxs("div",{children:[a.jsx(Rme,{step:p,index:h,execStep:l.get(p.id)}),h<e.steps.length-1&&a.jsx("div",{className:"flex justify-center py-1",children:a.jsx(qb,{className:"w-4 h-4 text-muted-foreground/40"})})]},p.id))})]})})}function s_(e){if(!e)return"#000000";if(e.startsWith("#"))return e;const t=e.match(/rgba?\(([^)]+)\)/);if(!t)return"#000000";const r=t[1].split(",").map(o=>parseFloat(o.trim())),[n,s,i]=r;return Number.isNaN(n)||Number.isNaN(s)||Number.isNaN(i)?"#000000":"#"+[n,s,i].map(o=>Math.max(0,Math.min(255,Math.round(o))).toString(16).padStart(2,"0")).join("")}function Mme({target:e,onApply:t,onClose:r}){const[n,s]=m.useState("text"),[i,o]=m.useState(""),[l,c]=m.useState("#000000"),[u,d]=m.useState("#ffffff"),[p,h]=m.useState(!1),[f,x]=m.useState(!1),[g,y]=m.useState(!1),[b,v]=m.useState(!1),[k,N]=m.useState(!1),[j,w]=m.useState(""),[S,T]=m.useState(""),[C,A]=m.useState(""),[P,E]=m.useState([]),[_,I]=m.useState(!1),[D,M]=m.useState(null),[B,$]=m.useState(0),[K,R]=m.useState(0),[Y,Z]=m.useState(!1),[O,ne]=m.useState(!1),[oe,he]=m.useState(""),[ae,ve]=m.useState(!1),re=m.useRef(null);if(m.useEffect(()=>{e&&(e.isImage?s("image"):s("text"),o(e.text),c(s_(e.computedColor)),d(s_(e.computedBg)),h(!1),x(!1),y(!1),v(!1),N(!1),w(""),T(e.imgSrc||""),A(""),E([]),M(null),$(0),R(0),Z(!1),ne(!1),he(""),ve(!1),requestAnimationFrame(()=>{var q,Nt;e.isImage||((q=re.current)==null||q.focus(),(Nt=re.current)==null||Nt.select())}))},[e]),m.useEffect(()=>{function q(Nt){e&&(Nt.key==="Escape"?(Nt.preventDefault(),r()):Nt.key==="Enter"&&(Nt.metaKey||Nt.ctrlKey)&&
7003(Nt.preventDefault(),ue()))}return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e,i,n,l,u,p,f,g,b,k,j,S]),!e)return null;const se=360,le=360,te=8,We=e.iframeOffset.top+e.rect.top+e.rect.height+8;let Te=e.iframeOffset.left+e.rect.left;Te+se>window.innerWidth-te&&(Te=Math.max(te,window.innerWidth-se-te)),Te<te&&(Te=te);let Ee=We;if(Ee+le>window.innerHeight-te){const q=e.iframeOffset.top+e.rect.top-le-8;Ee=q>=te?q:Math.max(te,window.innerHeight-le-te)}Ee<te&&(Ee=te);const st=i.trim(),xt=st!==e.text.trim(),on=p||f,Yt=g||b||k,mt=!!j,ln=!!S&&S!==(e.imgSrc||""),at=Y||O,gt=!!oe.trim();let $t=!1;n==="text"?$t=xt:n==="color"?$t=on:n==="visibility"?$t=!0:n==="format"?$t=Yt||mt:n==="image"?$t=ln:n==="spacing"?$t=at:n==="ai"&&($t=gt);async function ue(){if(!(!e||!$t||ae)){ve(!0);try{n==="text"?await t({kind:"text",newText:st},e):n==="color"?await t({kind:"color",textColor:p?l:void 0,bgColor:f?u:void 0},e):n==="visibility"?await t({kind:"visibility",hide:!0},e):n==="format"?(Yt&&await t({kind:"format",bold:g,italic:b,underline:k},e),mt&&j&&await t({kind:"heading",level:j},e)):n==="image"?await t({kind:"image",src:S.trim()},e):n==="spacing"?await t({kind:"spacing",padding:Y?B:void 0,margin:O?K:void 0},e):n==="ai"&&await t({kind:"ai",instruction:oe.trim()},e)}finally{ve(!1)}}}async function je(){const q=C.trim();if(q){I(!0),M(null);try{const{data:Nt,error:U}=await G.functions.invoke("pexels-search",{body:{query:q,per_page:12}});if(U)throw U;const Ne=Nt;Ne.error?(M(Ne.setupHint||Ne.error),E([])):E(Ne.photos||[])}catch(Nt){M(Nt.message||"Pexels search failed"),E([])}finally{I(!1)}}}const it=[{id:"text",icon:kT,label:"Text",show:!e.isImage},{id:"format",icon:Pk,label:"Format",show:!e.isImage},{id:"color",icon:Ai,label:"Color",show:!e.isImage},{id:"spacing",icon:o6,label:"Space",show:!e.isImage},{id:"image",icon:ad,label:"Image",show:!!e.isImage},{id:"ai",icon:Dn,label:"SJ AI",show:!0},{id:"visibility",icon:ku,label:"Hide",show:!0}].filter(q=>q.show);return a.jsxs("div",{role:"dialog","aria-label":"Visual editor",className:"fixed z-[100] w-[360px] rounded-lg border bg-card shadow-2xl",style:{top:Ee,left:Te},onClick:q=>q.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b bg-muted/30 rounded-t-lg",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"font-mono text-[10px] uppercase tracking-wider text-muted-foreground",children:e.tagName}),a.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-[150px]",children:e.className.split(" ").slice(0,2).join(" ")||"no class"})]}),a.jsx("button",{onClick:r,className:"w-5 h-5 flex items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground","aria-label":"Close",children:a.jsx(qn,{className:"w-3.5 h-3.5"})})]}),a.jsx("div",{className:"flex border-b",children:it.map(q=>a.jsxs("button",{onClick:()=>s(q.id),className:L("flex-1 flex items-center justify-center gap-1 px-1 py-1.5 text-[10.5px] font-medium border-b-2 transition-colors",n===q.id?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"),children:[q.id==="ai"?a.jsx(ri,{className:"h-4 w-4"}):a.jsx(q.icon,{className:"w-3 h-3"}),q.label]},q.id))}),a.jsxs("div",{className:"p-3 space-y-2",children:[n==="text"&&a.jsx("textarea",{ref:re,value:i,onChange:q=>o(q.target.value),rows:Math.min(6,Math.max(2,i.split(`
7004`).length)),className:"w-full text-sm bg-background border rounded-md px-2.5 py-1.5 resize-none focus:outline-none focus:ring-1 focus:ring-primary/40 leading-snug",placeholder:"Edit the text…"}),n==="format"&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("div",{className:"flex items-center gap-1",children:[{key:"bold",icon:Pk,value:g,set:y,title:"Bold (wrap in <strong>)"},{key:"italic",icon:e6,value:b,set:v,title:"Italic (wrap in <em>)"},{key:"underline",icon:_6,value:k,set:N,title:"Underline (wrap in <u>)"}].map(q=>a.jsx("button",{type:"button",onClick:()=>q.set(!q.value),title:q.title,className:L("w-8 h-8 flex items-center justify-center rounded-md border text-xs font-semibold transition-colors",q.value?"bg-primary/10 text-primary border-primary/30":"bg-background text-muted-foreground border-border hover:text-foreground"),children:a.jsx(q.icon,{className:"w-3.5 h-3.5"})},q.key))}),a.jsxs("label",{className:"flex items-center gap-2 text-[11px] pt-1 border-t",children:[a.jsx(Z$,{className:"w-3 h-3 text-muted-foreground"}),a.jsx("span",{className:"w-16 text-muted-foreground",children:"Heading"}),a.jsxs("select",{value:j,onChange:q=>w(q.target.value),className:"flex-1 bg-background border rounded px-2 py-1 text-[11px] focus:outline-none focus:ring-1 focus:ring-primary/40",children:[a.jsx("option",{value:"",children:"— no change —"}),a.jsx("option",{value:"h1",children:"h1 (largest)"}),a.jsx("option",{value:"h2",children:"h2"}),a.jsx("option",{value:"h3",children:"h3"}),a.jsx("option",{value:"h4",children:"h4"}),a.jsx("option",{value:"h5",children:"h5"}),a.jsx("option",{value:"h6",children:"h6 (smallest)"}),a.jsx("option",{value:"p",children:"paragraph"})]})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug",children:"Bold/italic/underline wrap the text in tags. Heading swaps the wrapping tag (e.g. p → h2)."})]}),n==="color"&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 text-[11px]",children:[a.jsx("input",{type:"checkbox",checked:p,onChange:q=>h(q.target.checked),className:"w-3 h-3"}),a.jsx("span",{className:"w-12 text-muted-foreground",children:"Text"}
7004),a.jsx("input",{type:"color",value:l,onChange:q=>{c(q.target.value),h(!0)},className:"w-8 h-6 p-0 border rounded cursor-pointer bg-transparent"}),a.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:l})]}),a.jsxs("label",{className:"flex items-center gap-2 text-[11px]",children:[a.jsx("input",{type:"checkbox",checked:f,onChange:q=>x(q.target.checked),className:"w-3 h-3"}),a.jsx("span",{className:"w-12 text-muted-foreground",children:"Bg"}),a.jsx("input",{type:"color",value:u,onChange:q=>{d(q.target.value),x(!0)},className:"w-8 h-6 p-0 border rounded cursor-pointer bg-transparent"}),a.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:u})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug",children:"Tick the boxes for the colors you want to apply, then Apply."})]}),n==="image"&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("label",{className:"block text-[11px] text-muted-foreground",children:"Image URL"}),a.jsx("input",{type:"url",value:S,onChange:q=>T(q.target.value),placeholder:"https://…",className:"w-full text-xs bg-background border rounded-md px-2.5 py-1.5 focus:outline-none focus:ring-1 focus:ring-primary/40 font-mono"}),S&&a.jsx("div",{className:"border rounded-md overflow-hidden bg-muted/30 aspect-video flex items-center justify-center max-h-32",children:a.jsx("img",{src:S,alt:"preview",className:"max-w-full max-h-full object-contain",onError:q=>{q.currentTarget.style.display="none"}})}),a.jsxs("div",{className:"border-t pt-2 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(ja,{className:"w-3 h-3 text-muted-foreground"}),a.jsx("span",{className:"text-[10px] uppercase tracking-wider font-mono text-muted-foreground",children:"Search Pexels"})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"text",value:C,onChange:q=>A(q.target.value),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),je())},placeholder:"e.g. business team, mountain",className:"flex-1 text-xs bg-background border rounded-md px-2.5 py-1.5 focus:outline-none focus:ring-1 focus:ring-primary/40"}),a.jsx("button",{type:"button",onClick:je,disabled:!C.trim()||_,className:L("px-2 py-1.5 rounded text-[11px] font-semibold transition-colors",!C.trim()||_?"bg-muted text-muted-foreground":"bg-primary/10 text-primary hover:bg-primary/15"),children:_?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):"Find"})]}),D&&a.jsx("p",{className:"text-[10px] text-amber-600 dark:text-amber-400 leading-snug",children:D}),P.length>0&&a.jsx("div",{className:"grid grid-cols-3 gap-1 max-h-40 overflow-auto",children:P.map(q=>a.jsx("button",{type:"button",onClick:()=>T(q.src),title:`${q.alt||"Pexels photo"} — ${q.photographer}`,className:L("aspect-square overflow-hidden rounded border",S===q.src?"border-primary ring-1 ring-primary/30":"border-border hover:border-primary/40"),children:a.jsx("img",{src:q.thumb,alt:q.alt,className:"w-full h-full object-cover",loading:"lazy"})},q.id))})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug",children:"Click a thumbnail to use it. Photos courtesy of Pexels."})]}),n==="spacing"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("label",{className:"space-y-1 block",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"flex items-center gap-2 text-[11px]",children:[a.jsx("input",{type:"checkbox",checked:Y,onChange:q=>Z(q.target.checked),className:"w-3 h-3"}),a.jsx("span",{className:"text-muted-foreground",children:"Padding"})]}),a.jsxs("span",{className:"font-mono text-[10px] text-muted-foreground",children:[B,"px"]})]}),a.jsx("input",{type:"range",min:0,max:96,step:2,value:B,onChange:q=>{$(Number(q.target.value)),Z(!0)},className:"w-full accent-primary"})]}),a.jsxs("label",{className:"space-y-1 block",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"flex items-center gap-2 text-[11px]",children:[a.jsx("input",{type:"checkbox",checked:O,onChange:q=>ne(q.target.checked),className:"w-3 h-3"}),a.jsx("span",{className:"text-muted-foreground",children:"Margin"})]}),a.jsxs("span",{className:"font-mono text-[10px] text-muted-foreground",children:[K,"px"]})]}),a.jsx("input",{type:"range",min:0,max:96,step:2,value:K,onChange:q=>{R(Number(q.target.value)),ne(!0)},className:"w-full accent-primary"})]}),a.jsxs("p",{className:"text-[10px] text-muted-foreground leading-snug",children:["Adjust spacing in pixels. Tick a box and slide. Writes inline ",a.jsx("code",{className:"text-[10px] px-1 py-px rounded bg-muted",children:"padding"})," / ",a.jsx("code",{className:"text-[10px] px-1 py-px rounded bg-muted",children:"margin"})," styles directly."]})]}),n==="ai"&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("label",{className:"block text-[11px] text-muted-foreground",children:"Describe the change — Studio Jungle AI will edit the file."}),a.jsx("textarea",{value:oe,onChange:q=>he(q.target.value),rows:3,placeholder:e.isImage?"e.g. Replace this image with a hero shot of a coffee shop, dark, atmospheric":"e.g. Make this section more compact, add an emoji prefix, rewrite as a quote",className:"w-full text-sm bg-background border rounded-md px-2.5 py-1.5 resize-none focus:outline-none focus:ring-1 focus:ring-primary/40 leading-snug"}),a.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug",children:`Use this when no other tab fits — e.g. structural rewrites, multi-step changes, or "make this look better". The AI sees the clicked element's text 
7004+ tag + classes.`})]}),n==="visibility"&&a.jsxs("div",{className:"space-y-2 py-1",children:[a.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:["Hide this element from the page. The element stays in the source code with ",a.jsx("code",{className:"text-[10px] px-1 py-px rounded bg-muted",children:"display:none"})," so you can unhide later by editing the file."]}),a.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-foreground/80",children:[a.jsx(ys,{className:"w-3 h-3"}),a.jsx("span",{children:"Currently visible"})]})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground",children:"⌘↵ apply · esc cancel"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("button",{onClick:r,className:"px-2.5 py-1 rounded text-[11px] text-muted-foreground hover:text-foreground hover:bg-muted",children:"Cancel"}),a.jsx("button",{onClick:ue,disabled:!$t||ae,className:L("flex items-center gap-1 px-2.5 py-1 rounded text-[11px] font-semibold",!$t||ae?"bg-muted text-muted-foreground cursor-not-allowed":"bg-primary text-primary-foreground hover:bg-primary/90"),children:ae?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"}),"Applying"]}):a.jsxs(a.Fragment,{children:[a.jsx(Wn,{className:"w-3 h-3"}),"Apply"]})})]})]})]})]})}const a_=`
7005<script>
7006(function () {
7007  if (window.__sjVisualEditInstalled) return;
7008  window.__sjVisualEditInstalled = true;
7009
7010  var ACTIVE = false;
7011  var SKIP_TAGS = { HTML: 1, BODY: 1, HEAD: 1, SCRIPT: 1, STYLE: 1, META: 1, LINK: 1, NOSCRIPT: 1, IFRAME: 1 };
7012  var hovered = null;
7013  var STYLE_ID = '__sj-tap-tweak-style';
7014
7015  function ensureStyle() {
7016    if (document.getElementById(STYLE_ID)) return;
7017    var s = document.createElement('style');
7018    s.id = STYLE_ID;
7019    s.textContent = [
7020      '[data-sj-hover] { outline: 2px solid hsl(152 60% 36%) !important; outline-offset: 1px !important; cursor: pointer !important; }',
7021      'body[data-sj-tap-active] * { user-select: none !important; }',
7022      '#__sj-ve-status { position: fixed !important; top: 12px !important; right: 12px !important; z-index: 2147483647 !important; display: inline-flex !important; align-items: center !important; gap: 6px !important; padding: 6px 12px !important; border-radius: 999px !important; font: 600 11px/1.25 ui-sans-serif,system-ui,sans-serif !important; letter-spacing: 0.01em !important; box-shadow: 0 4px 16px rgba(0,0,0,0.2) !important; pointer-events: none !important; transition: opacity .35s ease, transform .35s ease !important; backdrop-filter: blur(10px) !important; -webkit-backdrop-filter: blur(10px) !important; transform: translateY(0) !important; }',
7023      '#__sj-ve-status[data-on="1"] { background: hsl(152 60% 36%) !important; color: #fff !important; border: 1px solid hsl(152 55% 30%) !important; }',
7024      '#__sj-ve-status[data-on="0"] { background: rgba(24,24,27,0.92) !important; color: #fafafa !important; border: 1px solid rgba(255,255,255,0.14) !important; }',
7025      '#__sj-ve-status .__sj-ve-dot { width: 6px !important; height: 6px !important; border-radius: 999px !important; background: currentColor !important; opacity: .9 !important; flex-shrink: 0 !important; }',
7026      '#__sj-ve-status[data-on="1"] .__sj-ve-dot { background: #fff !important; box-shadow: 0 0 0 2px rgba(255,255,255,0.35) !important; }',
7027    ].join('\\n');
7028    document.head.appendChild(s);
7029  }
7030
7031  function setStatusBadge(state) {
7032    var b = document.getElementById('__sj-ve-status');
7033    if (!state) {
7034      if (b) b.remove();
7035      return;
7036    }
7037    if (!b) {
7038      b = document.createElement('div');
7039      b.id = '__sj-ve-status';
7040      (document.body || document.documentElement).appendChild(b);
7041    }
7042    b.setAttribute('data-on', '1');
7043    b.innerHTML = '<span class="__sj-ve-dot" aria-hidden="true"></span><span>Visual Editor ON · click any text</span>';
7044    b.style.opacity = '1';
7045    b.style.transform = 'translateY(0)';
7046  }
7047
7048  function clearHover() {
7049    if (hovered) {
7050      hovered.removeAttribute('data-sj-hover');
7051      hovered = null;
7052    }
7053  }
7054
7055  // Multi-select: track elements the user shift-clicked. Each gets a
7056  // distinct outline so it's obvious they're staged. Cleared on
7057  // 'sj:clear-multi-select' from the studio (after Apply or Cancel).
7058  var SELECTED = []; // array of { el, text, tagName, className, rect, computedColor, computedBg, imgSrc }
7059  function clearMultiSelect() {
7060    for (var i = 0; i < SELECTED.length; i++) {
7061      try { SELECTED[i].el.removeAttribute('data-sj-multi'); } catch (_e) {}
7062    }
7063    SELECTED = [];
7064  }
7065  function ensureMultiStyle() {
7066    var sid = '__sj-multi-style';
7067    if (document.getElementById(sid)) return;
7068    var s = document.createElement('style');
7069    s.id = sid;
7070    s.textContent = [
7071      '[data-sj-multi] { outline: 2px dashed hsl(82 70% 45%) !important; outline-offset: 1px !important; }',
7072      '[data-sj-drop] { outline: 2px solid hsl(28 90% 50%) !important; outline-offset: 2px !important; box-shadow: 0 0 0 4px hsl(28 90% 50% / 0.15) !important; }',
7073      '[data-sj-dragging] { opacity: 0.5 !important; cursor: grabbing !important; }',
7074    ].join('\\n');
7075    document.head.appendChild(s);
7076  }
7077
7078  // Drag-to-reorder state
7079  var dragStartEl = null;
7080  var dragStartPos = null;
7081  var dropTargetEl = null;
7082  var dragMode = false;
7083
7084  function clearDragState() {
7085    if (dragStartEl) try { dragStartEl.removeAttribute('data-sj-dragging'); } catch (_e) {}
7086    if (dropTargetEl) try { dropTargetEl.removeAttribute('data-sj-drop'); } catch (_e) {}
7087    document.body && (document.body.style.cursor = '');
7088    dragStartEl = null;
7089    dragStartPos = null;
7090    dropTargetEl = null;
7091    // dragMode stays true briefly so the trailing click is suppressed
7092    setTimeout(function () { dragMode = false; }, 100);
7093  }
7094
7095  // Leaf rule: editable elements must have NO element children. This
7096  // guarantees textContent is a single contiguous string and matches
7097  // verbatim in the source file (no JSX spans breaking it up).
7098  function isLeafTextElement(el) {
7099    if (!el || !el.tagName || SKIP_TAGS[el.tagName]) return false;
7100    if (el.children && el.children.length > 0) return false;
7101    var text = (el.textContent || '').trim();
7102    return text.length > 0 && text.length < 500;
7103  }
7104
7105  // Side-channel: when caretRangeFromPoint targets a text node inside a
7106  // mixed-content parent (like <p>plain <strong>bold</strong></p>), we
7107  // capture just that text node's value rather than the parent's full
7108  // textContent (which would include sibling text + child element text).
7109  var _overrideText = null;
7110
7111  function nearestLeafDescendant(root, x, y) {
7112    if (!root) return null;
7113    if (isLeafTextElement(root)) return root;
7114    var best = null;
7115    var bestDist = Infinity;
7116    var stack = [root];
7117    while (stack.length) {
7118      var n = stack.pop();
7119      if (!n) continue;
7120      if (isLeafTextElement(n)) {
7121        var r = n.getBoundingClientRect();
7122        if (r.width === 0 && r.height === 0) continue;
7123        var cx = Math.max(r.left, Math.min(x, r.right));
7124        var cy = Math.max(r.top, Math.min(y, r.bottom));
7125        var dx = cx - x;
7126        var dy = cy - y;
7127        var d = dx * dx + dy * dy;
7128        if (d < bestDist) { bestDist = d; best = n; }
7129      } else if (n.children) {
7130        for (var i = 0; i < n.children.length; i++) stack.push(n.children[i]);
7131      }
7132    }
7133    return best;
7134  }
7135
7136  // Try to resolve the EXACT text node under the cursor. Works for
7137  // paragraphs and buttons with mixed content (text + inline children +
7138  // icons). Falls back to leaf-element search if no text node is hit.
7139  function pickTarget(e) {
7140    _overrideText = null;
7141    var doc = document;
7142
7143    // 1. Exact text-node via caretRangeFromPoint — best for paragraphs,
7144    //    buttons with icons, mixed-content elements.
7145    var caret = null;
7146    try {
7147      if (typeof doc.caretRangeFromPoint === 'function') {
7148        caret = doc.caretRangeFromPoint(e.clientX, e.clientY);
7149      } else if (typeof doc.caretPositionFromPoint === 'function') {
7150        var pos = doc.caretPositionFromPoint(e.clientX, e.clientY);
7151        if (pos) caret = { startContainer: pos.offsetNode };
7152      }
7153    } catch (_e) {}
7154    if (caret && caret.startContainer && caret.startContainer.nodeType === 3) {
7155      var tn = caret.startContainer;
7156      var nv = (tn.nodeValue || '').trim();
7157      var p = tn.parentElement;
7158      if (p && nv && nv.length < 500 && !SKIP_TAGS[p.tagName]) {
7159        _overrideText = nv;
7160        return p;
7161      }
7162    }
7163
7164    // 2. Direct leaf at cursor
7165    var els = (typeof doc.elementsFromPoint === 'function')
7166      ? doc.elementsFromPoint(e.clientX, e.clientY)
7167      : [];
7168    for (var i = 0; i < els.length; i++) {
7169      if (isLeafTextElement(els[i])) return els[i];
7170    }
7171
7172    // 3. Walk down inside e.target if it has element children
7173    if (e.target && e.target.children && e.target.children.length > 0) {
7174      var inside = nearestLeafDescendant(e.target, e.clientX, e.clientY);
7175      if (inside) return inside;
7176    }
7177
7178    // 4. Walk up
7179    var t = e.target;
7180    while (t && !isLeafTextElement(t)) t = t.parentElement;
7181    return t || null;
7182  }
7183
7184  function imgAtPoint(x, y) {
7185    var doc = document;
7186    if (typeof doc.elementsFromPoint !== 'function') return null;
7187    var els;
7188    try { els = doc.elementsFromPoint(x, y); } catch (_e) { return null; }
7189    for (var i = 0; i < els.length; i++) {
7190      if (els[i] && els[i].tagName === 'IMG') return els[i];
7191    }
7192    return null;
7193  }
7194
7195  function onMouseMove(e) {
7196    if (!ACTIVE) return;
7197    // Drag-to-reorder: detect drag transition and track drop target
7198    if (dragStartEl && dragStartPos && !dragMode) {
7199      var dx = e.clientX - dragStartPos.x;
7200      var dy = e.clientY - dragStartPos.y;
7201      if (Math.sqrt(dx * dx + dy * dy) > 8) {
7202        dragMode = true;
7203        ensureMultiStyle();
7204        try { dragStartEl.setAttribute('data-sj-dragging', ''); } catch (_e) {}
7205        if (document.body) document.body.style.cursor = 'grabbing';
7206      }
7207    }
7208    if (dragMode) {
7209      var dt = imgAtPoint(e.clientX, e.clientY) || pickTarget(e);
7210      if (dt && dt !== dragStartEl) {
7211        if (dropTargetEl !== dt) {
7212          if (dropTargetEl) try { dropTargetEl.removeAttribute('data-sj-drop'); } catch (_e) {}
7213          try { dt.setAttribute('data-sj-drop', ''); } catch (_e) {}
7214          dropTargetEl = dt;
7215        }
7216      }
7217      return; // Skip hover updates during drag
7218    }
7219    var t = imgAtPoint(e.clientX, e.clientY) || pickTarget(e);
7220    if (t === hovered) return;
7221    clearHover();
7222    if (t) {
7223      t.setAttribute('data-sj-hover', '');
7224      hovered = t;
7225    }
7226  }
7227
7228  function onMouseDown(e) {
7229    if (!ACTIVE) return;
7230    if (e.shiftKey || e.metaKey || e.ctrlKey || e.altKey) return; // modifiers reserved
7231    if (e.button !== 0) return; // primary button only
7232    var t = imgAtPoint(e.clientX, e.clientY) || pickTarget(e);
7233    if (!t) return;
7234    dragStartEl = t;
7235    dragStartPos = { x: e.clientX, y: e.clientY };
7236    dragMode = false;
7237  }
7238
7239  function onMouseUp(e) {
7240    if (!ACTIVE) return;
7241    if (dragMode && dragStartEl && dropTargetEl) {
7242      e.preventDefault();
7243      e.stopPropagation();
7244      var sourcePayload = buildPayload(dragStartEl, dragStartEl.tagName === 'IMG');
7245      var targetPayload = buildPayload(dropTargetEl, dropTargetEl.tagName === 'IMG');
7246      parent.postMessage({
7247        type: 'sj:visual-edit-drop',
7248        payload: { source: sourcePayload, target: targetPayload },
7249      }, '*');
7250    }
7251    clearDragState();
7252  }
7253
7254  // Walk up to find the nearest data-sj-source ancestor (the clicked text
7255  // node lives inside a leaf, but the source attribute may be on its
7256  // parent open tag in the synthesized HTML).
7257  function findSourceMarker(el) {
7258    var cur = el;
7259    while (cur) {
7260      if (cur.getAttribute) {
7261        var v = cur.getAttribute('data-sj-source');
7262        if (v) return v;
7263      }
7264      cur = cur.parentElement;
7265    }
7266    return '';
7267  }
7268
7269  function buildPayload(t, isImage) {
7270    var rect = t.getBoundingClientRect();
7271    var cs = window.getComputedStyle(t);
7272    var className = (typeof t.className === 'string' ? t.className : '') || '';
7273    var sourceMarker = findSourceMarker(t);
7274    var base = {
7275      tagName: t.tagName.toLowerCase(),
7276      className: className,
7277      computedColor: cs.color || '',
7278      computedBg: cs.backgroundColor || '',
7279      sourceMarker: sourceMarker,
7280      rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
7281    };
7282    if (isImage) {
7283      base.text = (t.alt || '').trim();
7284      base.imgSrc = t.getAttribute('src') || '';
7285      base.isImage = true;
7286    } else {
7287      base.text = (_overrideText !== null ? _overrideText : (t.textContent || '')).trim();
7288    }
7289    return base;
7290  }
7291
7292  function onClick(e) {
7293    if (!ACTIVE) return;
7294    // Suppress the click that follows a drag — onMouseUp already
7295    // dispatched the drop event.
7296    if (dragMode) {
7297      e.preventDefault();
7298      e.stopPropagation();
7299      return;
7300    }
7301    e.preventDefault();
7302    e.stopPropagation();
7303
7304    // Image click: prefer detecting <img> at the click point so the user
7305    // can swap or hide it without needing a text leaf.
7306    var doc = document;
7307    var imgEl = null;
7308    try {
7309      var atPoint = (typeof doc.elementsFromPoint === 'function') ? doc.elementsFromPoint(e.clientX, e.clientY) : [];
7310      for (var i = 0; i < atPoint.length; i++) {
7311        if (atPoint[i] && atPoint[i].tagName === 'IMG') { imgEl = atPoint[i]; break; }
7312      }
7313    } catch (_e) {}
7314
7315    var resolvedTarget = imgEl;
7316    var resolvedIsImage = !!imgEl;
7317    if (!resolvedTarget) {
7318      resolvedTarget = pickTarget(e);
7319      if (!resolvedTarget) return;
7320    }
7321
7322    var payload = buildPayload(resolvedTarget, resolvedIsImage);
7323
7324    // Shift-click → add to multi-selection (do NOT open toolbar).
7325    if (e.shiftKey) {
7326      ensureMultiStyle();
7327      try { resolvedTarget.setAttribute('data-sj-multi', ''); } catch (_e) {}
7328      // Avoid duplicates
7329      var already = false;
7330      for (var s = 0; s < SELECTED.length; s++) {
7331        if (SELECTED[s].el === resolvedTarget) { already = true; break; }
7332      }
7333      if (!already) SELECTED.push({ el: resolvedTarget, payload: payload });
7334      else {
7335        // Re-clicking a selected element with shift toggles it off
7336        for (var s2 = 0; s2 < SELECTED.length; s2++) {
7337          if (SELECTED[s2].el === resolvedTarget) {
7338            SELECTED.splice(s2, 1);
7339            try { resolvedTarget.removeAttribute('data-sj-multi'); } catch (_e) {}
7340            break;
7341          }
7342        }
7343      }
7344      parent.postMessage({
7345        type: 'sj:visual-edit-multi',
7346        payload: { items: SELECTED.map(function (x) { return x.payload; }) },
7347      }, '*');
7348      return;
7349    }
7350
7351    // Plain click → clear multi-selection and open single-edit toolbar
7352    if (SELECTED.length > 0) {
7353      clearMultiSelect();
7354      parent.postMessage({ type: 'sj:visual-edit-multi', payload: { items: [] } }, '*');
7355    }
7356    parent.postMessage({ type: 'sj:visual-edit-clicked', payload: payload }, '*');
7357  }
7358
7359  function activate() {
7360    ensureStyle();
7361    ACTIVE = true;
7362    if (document.body) document.body.setAttribute('data-sj-tap-active', '');
7363    document.addEventListener('mousemove', onMouseMove, true);
7364    document.addEventListener('mousedown', onMouseDown, true);
7365    document.addEventListener('mouseup', onMouseUp, true);
7366    document.addEventListener('click', onClick, true);
7367    setStatusBadge(true);
7368  }
7369
7370  function deactivate() {
7371    ACTIVE = false;
7372    clearHover();
7373    clearDragState();
7374    if (document.body) document.body.removeAttribute('data-sj-tap-active');
7375    document.removeEventListener('mousemove', onMouseMove, true);
7376    document.removeEventListener('mousedown', onMouseDown, true);
7377    document.removeEventListener('mouseup', onMouseUp, true);
7378    document.removeEventListener('click', onClick, true);
7379    setStatusBadge(false);
7380  }
7381
7382  window.addEventListener('message', function (event) {
7383    var data = event && event.data;
7384    if (!data || typeof data !== 'object') return;
7385    if (data.type === 'sj:visual-editor-on') activate();
7386    else if (data.type === 'sj:visual-editor-off') { deactivate(); clearMultiSelect(); }
7387    else if (data.type === 'sj:clear-multi-select') clearMultiSelect();
7388  });
7389
7390  // Tell the parent we're ready. Parent replies with the current desired
7391  // state so we activate even if the toggle was on before the iframe
7392  // finished loading. Send on script install AND on DOMContentLoaded for
7393  // safety across srcdoc timing differences.
7394  function announceReady() {
7395    try { parent.postMessage({ type: 'sj:visual-editor-ready' }, '*'); } catch (_e) {}
7396    try { console.log('[sj-visual-editor] iframe overlay installed; sent ready'); } catch (_e) {}
7397  }
7398  // Pre-create styles so first activate is instant. Clear any stale tap
7399  // flag left from a prior HMR reload so nav links stay clickable when
7400  // the visual editor is off.
7401  if (document.body) document.body.removeAttribute('data-sj-tap-active');
7402  if (document.head) ensureStyle();
7403  announceReady();
7404  if (document.readyState === 'loading') {
7405    document.addEventListener('DOMContentLoaded', function () { ensureStyle(); announceReady(); });
7406  }
7407})();
7408<\/script>
7409`;function CD(e){return!e||e.includes("__sjVisualEditInstalled")?e:e.includes("</body>")?e.replace("</body>",a_+"</body>"):e+a_}function PD(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"&&n.content?r.push({path:s.replace(/^\/+/,"").split("\\").join("/"),content:n.content}):n.type==="folder"&&n.children&&r.push(...PD(n.children,s))}return r}async function Lme(e){var n,s;if(!e)return;let t="",r="";try{const{data:i}=await G.from("project_cloud_config").select("env_vars").eq("project_id",e).maybeSingle();(n=i==null?void 0:i.env_vars)!=null&&n.SUPABASE_URL&&((s=i==null?void 0:i.env_vars)!=null&&s.SUPABASE_ANON_KEY)&&(t=i.env_vars.SUPABASE_URL,r=i.env_vars.SUPABASE_ANON_KEY)}catch{}if(!t)try{const{data:i}=await G.from("projects").select("custom_supabase_url, custom_supabase_anon_key").eq("id",e).single();t=(i==null?void 0:i.custom_supabase_url)||"",r=(i==null?void 0:i.custom_supabase_anon_key)||""}catch{}if((!t||!r)&&(t="https://xfmlsevleobdlnjqxmdi.supabase.co",r="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"),!(!t||!r))return{VITE_SUPABASE_URL:t,VITE_SUPABASE_ANON_KEY:r,VITE_SUPABASE_PUBLISHABLE_KEY:r}}function Pb(){const e="https://xfmlsevleobdlnjqxmdi.supabase.co",t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo";return{VITE_SUPABASE_URL:e,VITE_SUPABASE_ANON_KEY:t,VITE_SUPABASE_PUBLISHABLE_KEY:t}}const $me=[{id:"web",label:"Desktop",icon:Aw,tooltip:"Live Vite preview when a real app exists. Falls back to instant HTML only while files are still being created or when Visual Editor is active."},{id:"mobile",label:"Mobile",icon:Nc,tooltip:"Interactive phone preview — renders the generated app inside Studio Jungle device chrome for tap-through mobile testing."}];function ny(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="folder"&&n.children?r.push(...ny(n.children,s)):n.type==="file"&&typeof n.content=="string"&&r.push({path:s,content:n.content})}return r}function Fme(e){var n;const t=e.replace(/^\/+/,"").replace(/\\/g,"/");if(!t||t.endsWith("/")||t.startsWith("node_modules/")||t.startsWith("dist/")||t.startsWith("build/")||t.startsWith(".git/")||t.startsWith(".github/")||t.startsWith(".vercel/")||t.startsWith(".netlify/")||t.startsWith("coverage/")||t.startsWith("supabase/")||t.startsWith(".sj/"))return!1;const r=((n=t.split("/").pop())==null?void 0:n.toLowerCase())||"";return r==="readme.md"||r==="dockerfile"||r===".dockerignore"||r==="netlify.toml"||r==="vercel.json"||r.endsWith(".zip")||r.endsWith(".tar")||r.endsWith(".gz")||r.endsWith(".sql")||r.endsWith(".md")?!1:t==="package.json"||t==="package-lock.json"||t==="index.html"||t===".env"||t===".env.example"||t.startsWith("src/")||t.startsWith("public/")||/^(vite|tsconfig|tailwind|postcss|eslint)\.config\.(js|cjs|mjs|ts)$/.test(t)||/^tsconfig(\.[\w-]+)?\.json$/.test(t)}function Bme(e){const t=new Map;for(const r of ny(e)){const n=r.path.replace(/^\/+/,"").replace(/\\/g,"/");Fme(n)&&(r.content.length>1e6||t.set(n,{path:n,content:r.content}))}return Array.from(t.values())}function nw(e){return e==="/"?"Home":e.replace(/^\//,"").replace(/[-_/]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())||"Route"}function Ume(e){const t=ny(e),r=new Map,n=s=>{if(!s||s.includes("*")||s.includes(":"))return;let i=s.split(/[?#]/)[0]||"/";i=i.startsWith("/")?i:`/${i}`,i=i.replace(/\/+/g,"/"),(i==="/index"||i==="/index.html")&&(i="/"),i=i.replace(/\/index\.html$/i,"").replace(/\.html$/i,""),i.length>1&&(i=i.replace(/\/$/,"")),["/home","/homepage","/landing","/landing-page"].includes(i.toLowerCase())&&(i="/"),r.set(i,{id:i,name:nw(i),source:"react"})};for(const s of t)if(/\.(tsx|jsx|ts|js)$/.test(s.path)){for(const i of s.content.matchAll(/<Route\b[^>]*\bpath=["']([^"']+)["']/g))n(i[1]);for(const i of s.content.matchAll(/\b(?:to|href)=["'](\/[A-Za-z0-9/_-]+)["']/g))n(i[1])}for(const s of t){const i=s.path.match(/^src\/(?:pages|routes|views|screens)\/(.+)\.(tsx|jsx)$/i);if(!i)continue;const o=i[1].replace(/\/index$/i,"").replace(/(?:Page|Screen|View)$/i,"").replace(/^Home$/i,"").replace(/^Landing$/i,"");n(o?`/${o.replace(/\\/g,"/").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`:"/")}return t.some(s=>s.path==="src/App.tsx"||s.path==="src/main.tsx")&&n("/"),Array.from(r.values())}function zme(e){if(!e)return!1;const t=e.slice(0,6e3),r=/<div\s+id=["']root["'][^>]*>\s*(?:<!--[\s\S]*?-->\s*)?<\/div>/i.test(t),n=/<title>\s*Studio\s*Jungle/i.test(t)||/Studiojungle/i.test(t)||/studiojungle\.ai/i.test(t),s=/\/@vite\/client/i.test(t)||/<script\s+type=["']module["'][^>]*\bsrc=["']\/?src\/main\.[tj]sx?["']/i.test(t);return r&&(n||s)}function qme(e){if(!e)return!1;const t=/<script\s+type=["']module["'][^>]*\bsrc=["']\/?src\/main\.[tj]sx?["']/i.test(e)||/\/@vite\/client/i.test(e),r=e.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").trim();return t&&r.length<12||/^[\s,;)}\]]+/.test(r)||/[{}]\)|\)\}|=>|;\s*\}|\}
7409\s*,|\{\s*\)/.test(r)||/\b(?:const|let|var|return|function)\s+[A-Za-z_$]/.test(r)}function qf(e){return zme(e)||qme(e)}const Hme=`
7410<style id="__sjPreviewUtilityCss">
7411*,::before,::after{box-sizing:border-box}html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}body{margin:0;min-height:100vh;background:#fff;color:#0f172a}img,svg,video,canvas{display:block;max-width:100%}button,input,textarea,select{font:inherit}button,[role=button],a{cursor:pointer}a{color:inherit;text-decoration:none}h1,h2,h3,h4,p{margin:0}
7412.min-h-screen{min-height:100vh}.h-screen{height:100vh}.w-full{width:100%}.h-full{height:100%}.w-screen{width:100vw}.max-w-xs{max-width:20rem}.max-w-sm{max-width:24rem}.max-w-md{max-width:28rem}.max-w-lg{max-width:32rem}.max-w-xl{max-width:36rem}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-5xl{max-width:64rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-auto{margin-left:auto}.mr-auto{margin-right:auto}
7413.block{display:block}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.flex{display:flex}.grid{display:grid}.hidden{display:none}.relative{position:relative}.absolute{position:absolute}.fixed{position:fixed}.sticky{position:sticky}.inset-0{inset:0}.top-0{top:0}.right-0{right:0}.bottom-0{bottom:0}.left-0{left:0}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}
7414.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-start{justify-content:flex-start}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-end{justify-content:flex-end}.place-items-center{place-items:center}.self-start{align-self:flex-start}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-auto{overflow:auto}
7415.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.col-span-1{grid-column:span 1/span 1}.col-span-2{grid-column:span 2/span 2}.col-span-3{grid-column:span 3/span 3}.col-span-4{grid-column:span 4/span 4}.col-span-5{grid-column:span 5/span 5}.col-span-6{grid-column:span 6/span 6}.col-span-7{grid-column:span 7/span 7}.col-span-8{grid-column:span 8/span 8}.col-span-9{grid-column:span 9/span 9}.col-span-10{grid-column:span 10/span 10}.col-span-11{grid-column:span 11/span 11}.col-span-12{grid-column:span 12/span 12}
7416.gap-1{gap:.25rem}.gap-1\\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-10{gap:2.5rem}.gap-12{gap:3rem}.space-y-1>*+*{margin-top:.25rem}.space-y-2>*+*{margin-top:.5rem}.space-y-3>*+*{margin-top:.75rem}.space-y-4>*+*{margin-top:1rem}.space-y-6>*+*{margin-top:1.5rem}.space-y-8>*+*{margin-top:2rem}
7417.p-1{padding:.25rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-10{padding:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.py-10{padding-top:2.5rem;padding-bottom:2.5rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-20{padding-top:5rem;padding-bottom:5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.pt-8{padding-top:2rem}.pb-4{padding-bottom:1rem}.pb-6{padding-bottom:1.5rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}
7418.rounded{border-radius:.25rem}.rounded-md{border-radius:.375rem}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.border{border:1px solid #e2e8f0}.border-t{border-top:1px solid #e2e8f0}.border-b{border-bottom:1px solid #e2e8f0}.border-slate-100{border-color:#f1f5f9}.border-slate-200{border-color:#e2e8f0}.border-slate-300{border-color:#cbd5e1}.border-gray-200{border-color:#e5e7eb}
7419.bg-white{background:#fff}.bg-slate-50{background:#f8fafc}.bg-slate-100{background:#f1f5f9}.bg-slate-900{background:#0f172a}.bg-gray-50{background:#f9fafb}.bg-gray-100{background:#f3f4f6}.bg-black{background:#000}.bg-emerald-50{background:#ecfdf5}.bg-emerald-100{background:#d1fae5}.bg-emerald-500{background:#10b981}.bg-emerald-600{background:#059669}.bg-green-50{background:#f0fdf4}.bg-green-100{background:#dcfce7}.bg-green-600{background:#16a34a}.bg-blue-50{background:#eff6ff}.bg-blue-100{background:#dbeafe}.bg-blue-600{background:#2563eb}.bg-indigo-600{background:#4f46e5}.bg-red-50{background:#fef2f2}.bg-orange-50{background:#fff7ed}.bg-yellow-50{background:#fefce8}.bg-white\\/80{background:rgba(255,255,255,.8)}.bg-white\\/90{background:rgba(255,255,255,.9)}.backdrop-blur{backdrop-filter:blur(8px)}.backdrop-blur-xl{backdrop-filter:blur(24px)}
7420.text-white{color:#fff}.text-black{color:#000}.text-slate-400{color:#94a3b8}.text-slate-500{color:#64748b}.text-slate-600{color:#475569}.text-slate-700{color:#334155}.text-slate-800{color:#1e293b}.text-slate-900{color:#0f172a}.text-gray-500{color:#6b7280}.text-gray-600{color:#4b5563}.text-gray-700{color:#374151}.text-gray-900{color:#111827}.text-emerald-500{color:#10b981}.text-emerald-600{color:#059669}.text-emerald-700{color:#047857}.text-green-600{color:#16a34a}.text-blue-600{color:#2563eb}.text-red-600{color:#dc2626}.text-orange-600{color:#ea580c}
7421.bg-paper{background:#fbf8f1}.bg-cream{background:#fff7ed}.bg-ink{background:#111827}.bg-jungle{background:#1f8f5f}.bg-moss{background:#7a8f5a}.bg-fjord-50{background:#f0f9fb}.bg-fjord-100{background:#d9f0f4}.bg-fjord-500{background:#2ca6b0}.bg-fjord-600{background:#168894}.bg-fjord-700{background:#0d6b79}.bg-fjord-800{background:#164b5f}.bg-fjord-900{background:#102332}.bg-coral-50{background:#fff1ed}.bg-coral-100{background:#ffe1d8}.bg-coral-400{background:#fb8a6f}.bg-coral-500{background:#f46f52}.bg-coral-600{background:#df5538}.bg-gold-50{background:#fff8e6}.bg-gold-100{background:#f9e7b2}.bg-gold-400{background:#dca846}.bg-gold-500{background:#c88a2b}.text-paper{color:#fbf8f1}.text-cream{color:#fff7ed}.text-ink{color:#111827}.text-jungle{color:#1f8f5f}.text-moss{color:#7a8f5a}.text-fjord-50{color:#f0f9fb}.text-fjord-100{color:#d9f0f4}.text-fjord-500{color:#2ca6b0}.text-fjord-600{color:#168894}.text-fjord-700{color:#0d6b79}.text-fjord-800{color:#164b5f}.text-fjord-900{color:#102332}.text-coral-400{color:#fb8a6f}.text-coral-500{color:#f46f52}.text-gold-400{color:#dca846}.text-gold-500{color:#c88a2b}.border-fjord-100{border-color:#d9f0f4}.border-fjord-200{border-color:#b9e1e8}.border-fjord-900{border-color:#102332}.border-coral-200{border-color:#ffc6b8}.border-gold-200{border-color:#efd28a}.from-paper{--tw-gradient-from:#fbf8f1}.from-fjord-50{--tw-gradient-from:#f0f9fb}.from-fjord-900{--tw-gradient-from:#102332}.to-white{--tw-gradient-to:#fff}.to-fjord-100{--tw-gradient-to:#d9f0f4}.to-fjord-900{--tw-gradient-to:#102332}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-from,#fff),var(--tw-gradient-to,rgba(255,255,255,0)))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-from,#fff),var(--tw-gradient-to,rgba(255,255,255,0)))}.text-fjord-900\\/85{color:rgba(16,35,50,.85)}.text-fjord-900\\/70{color:rgba(16,35,50,.7)}.text-white\\/80{color:rgba(255,255,255,.8)}.text-white\\/70{color:rgba(255,255,255,.7)}.bg-fjord-900\\/90{background:rgba(16,35,50,.9)}.bg-white\\/70{background:rgba(255,255,255,.7)}.border-white\\/20{border-color:rgba(255,255,255,.2)}
7422.text-xs{font-size:.75rem;line-height:1rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-6xl{font-size:3.75rem;line-height:1}.font-medium{font-weight:500}.font-semibold{font-weight:600}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-black{font-weight:900}.uppercase{text-transform:uppercase}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.leading-none{line-height:1}.leading-tight{line-height:1.25}.leading-snug{line-height:1.375}.leading-relaxed{line-height:1.625}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}
7423.shadow{box-shadow:0 1px 3px rgba(15,23,42,.1),0 1px 2px rgba(15,23,42,.06)}.shadow-sm{box-shadow:0 1px 2px rgba(15,23,42,.05)}.shadow-md{box-shadow:0 4px 6px -1px rgba(15,23,42,.1),0 2px 4px -2px rgba(15,23,42,.1)}.shadow-lg{box-shadow:0 10px 15px -3px rgba(15,23,42,.1),0 4px 6px -4px rgba(15,23,42,.1)}.shadow-xl{box-shadow:0 20px 25px -5px rgba(15,23,42,.1),0 8px 10px -6px rgba(15,23,42,.1)}.shadow-2xl{box-shadow:0 25px 50px -12px rgba(15,23,42,.25)}
7424.object-cover{object-fit:cover}.object-contain{object-fit:contain}.aspect-square{aspect-ratio:1/1}.aspect-video{aspect-ratio:16/9}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.transition{transition:all .15s ease}.transition-all{transition:all .15s ease}.duration-200{transition-duration:.2s}.hover\\:bg-slate-100:hover{background:#f1f5f9}.hover\\:bg-emerald-700:hover{background:#047857}
7424.hover\\:shadow-lg:hover{box-shadow:0 10px 15px -3px rgba(15,23,42,.1),0 4px 6px -4px rgba(15,23,42,.1)}
7425@media (min-width:640px){.sm\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\\:flex-row{flex-direction:row}.sm\\:text-5xl{font-size:3rem;line-height:1}.sm\\:px-6{padding-left:1.5rem;padding-right:1.5rem}}
7426@media (min-width:768px){.md\\:flex{display:flex}.md\\:hidden{display:none}.md\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.md\\:grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.md\\:col-span-2{grid-column:span 2/span 2}.md\\:col-span-3{grid-column:span 3/span 3}.md\\:col-span-4{grid-column:span 4/span 4}.md\\:col-span-5{grid-column:span 5/span 5}.md\\:col-span-6{grid-column:span 6/span 6}.md\\:col-span-7{grid-column:span 7/span 7}.md\\:col-span-8{grid-column:span 8/span 8}.md\\:flex-row{flex-direction:row}.md\\:text-5xl{font-size:3rem;line-height:1}.md\\:text-6xl{font-size:3.75rem;line-height:1}.md\\:p-8{padding:2rem}.md\\:px-8{padding-left:2rem;padding-right:2rem}}
7427@media (min-width:1024px){.lg\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.lg\\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\\:grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.lg\\:col-span-2{grid-column:span 2/span 2}.lg\\:col-span-3{grid-column:span 3/span 3}.lg\\:col-span-4{grid-column:span 4/span 4}.lg\\:col-span-5{grid-column:span 5/span 5}.lg\\:col-span-6{grid-column:span 6/span 6}.lg\\:col-span-7{grid-column:span 7/span 7}.lg\\:col-span-8{grid-column:span 8/span 8}.lg\\:text-6xl{font-size:3.75rem;line-height:1}.lg\\:text-7xl{font-size:4.5rem;line-height:1}}
7428</style>
7429`,Wme=`
7430<script>
7431(function () {
7432  if (window.__sjImageFixupInstalled) return;
7433  window.__sjImageFixupInstalled = true;
7434  var IMG_URL = /^https:\\/\\/(?:images\\.unsplash\\.com|assets\\.mixkit\\.co|videos\\.pexels\\.com|coverr\\.co|images\\.pexels\\.com)\\/[^\\s]+$/i;
7435  var EXT_URL = /^https?:\\/\\/[^\\s]+\\.(?:jpg|jpeg|png|webp|gif|avif)(?:\\?[^\\s]*)?$/i;
7436  var VIDEO_URL = /\\.mp4(?:\\?|$)/i;
7437  var SKIP_TAGS = { A: 1, CODE: 1, PRE: 1, TEXTAREA: 1, INPUT: 1, SCRIPT: 1, STYLE: 1 };
7438
7439  function fixupNode(textNode) {
7440    var raw = textNode.nodeValue || '';
7441    if (/\\\\u[0-9a-fA-F]{4}/.test(raw)) {
7442      textNode.nodeValue = raw.replace(/\\\\u([0-9a-fA-F]{4})/g, function(_, hex) {
7443        return String.fromCharCode(parseInt(hex, 16));
7444      });
7445      raw = textNode.nodeValue || '';
7446    }
7447    var url = raw.trim();
7448    if (!url || !(IMG_URL.test(url) || EXT_URL.test(url))) return;
7449    var parent = textNode.parentElement;
7450    if (!parent || SKIP_TAGS[parent.tagName]) return;
7451    if (parent.querySelector && parent.querySelector('img,video')) return;
7452    var isVideo = VIDEO_URL.test(url);
7453    var el = document.createElement(isVideo ? 'video' : 'img');
7454    el.setAttribute('src', url);
7455    if (isVideo) {
7456      el.setAttribute('autoplay', '');
7457      el.setAttribute('loop', '');
7458      el.setAttribute('muted', '');
7459      el.setAttribute('playsinline', '');
7460    } else {
7461      el.setAttribute('alt', '');
7462      el.setAttribute('loading', 'lazy');
7463    }
7464    el.style.width = '100%';
7465    el.style.height = '100%';
7466    el.style.objectFit = 'cover';
7467    el.style.borderRadius = 'inherit';
7468    el.style.display = 'block';
7469    textNode.parentNode.replaceChild(el, textNode);
7470  }
7471
7472  function scan(root) {
7473    if (!root) return;
7474    var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
7475    var pending = [];
7476    var n;
7477    while ((n = walker.nextNode())) pending.push(n);
7478    pending.forEach(fixupNode);
7479  }
7480
7481  if (document.readyState === 'loading') {
7482    document.addEventListener('DOMContentLoaded', function () { scan(document.body); });
7483  } else {
7484    scan(document.body);
7485  }
7486
7487  var observer = new MutationObserver(function (mutations) {
7488    mutations.forEach(function (m) {
7489      m.addedNodes.forEach(function (n) {
7490        if (n.nodeType === 1) scan(n);
7491        else if (n.nodeType === 3) fixupNode(n);
7492      });
7493    });
7494  });
7495  if (document.body) observer.observe(document.body, { childList: true, subtree: true });
7496  else document.addEventListener('DOMContentLoaded', function () {
7497    observer.observe(document.body, { childList: true, subtree: true });
7498  });
7499})();
7500<\/script>
7501`;function AD(e){if(!e||typeof e!="string")return e;let t=e;const r=(i,o,l)=>l!=null&&l.test(i)?i:/<\/head\s*>/i.test(i)?i.replace(/<\/head\s*>/i,`${o}
7502</head>`):/<html\b[^>]*>/i.test(i)?i.replace(/<html\b[^>]*>/i,c=>`${c}
7503<head>
7504${o}
7505</head>`):`<!doctype html><html><head>${o}</head><body>${i}</body></html>`,n=i=>{let o=i.replace(/<link\b[^>]*\bhref\s*=\s*["']https?:\/\/cdn\.tailwindcss\.com[^"']*["'][^>]*>/gi,"").replace(/\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,"");for(let l=0;l<24;l++){const c=o.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,"").replace(/<script\b[^>]*\/>/gi,"");if(c===o)break;o=c}return o.replace(/<script\b[\s\S]*$/gi,"")},s=(i,o)=>/<\/body\s*>/i.test(i)?i.replace(/<\/body\s*>/i,`${o}
7506</body>`):i+o;return t=n(t),t=r(t,Hme,/id=["']__sjPreviewUtilityCss["']/i),t.includes("__sjImageFixupInstalled")||(t=s(t,Wme)),t.includes("__sjNavInterceptInstalled")||(t=s(t,Vme)),t}const Vme=`
7507<script>
7508(function(){
7509  if (window.__sjNavInterceptInstalled) return;
7510  window.__sjNavInterceptInstalled = true;
7511
7512  // Inside a srcdoc iframe, window.location.href is "about:srcdoc". Relative
7513  // URLs there (e.g. "dashboard.html") resolve to a path the browser tries to
7514  // navigate the iframe to — which sometimes falls through to the parent's
7515  // origin (studiojungle.ai). Anchor every relative resolution at a stable
7516  // synthetic origin so the intercept can pick a clean pathname.
7517  var SYNTHETIC_BASE = 'https://__sj-preview__/';
7518
7519  function isStudioHost(host) {
7520    return host === 'studiojungle.ai'
7521      || host === 'www.studiojungle.ai'
7522      || host === 'localhost'
7523      || host === '127.0.0.1'
7524      || /^127\\.0\\.0\\.1:\\d+$/.test(host)
7525      || /^localhost:\\d+$/.test(host);
7526  }
7527
7528  function isInternal(url) {
7529    try {
7530      if (url.startsWith('#')) return false;
7531      // mailto:, tel:, blob:, javascript: → external (let the page handle them)
7532      if (/^[a-z]+:/i.test(url) && !url.startsWith('http')) return false;
7533      if (/^https?:\\/\\//i.test(url)) {
7534        var u = new URL(url);
7535        // The studio iframe's REAL host (studiojungle.ai) → user followed an
7536        // accidental absolute link back to the studio. Treat as internal so
7537        // we intercept it and stay inside the preview instead of bouncing.
7538        if (isStudioHost(u.host)) return true;
7539        if (u.host === window.location.host) return true;
7540        return false;
7541      }
7542      return true;
7543    } catch (e) { return false; }
7544  }
7545
7546  function postNav(href) {
7547    try {
7548      var u = new URL(href, SYNTHETIC_BASE);
7549      var path = u.pathname + u.search + u.hash;
7550      if (path === '/studio' || path.startsWith('/studio/')) path = '/';
7551      window.parent.postMessage({ type: 'sj-nav', path: path }, '*');
7552    } catch (err) {
7553      console.warn('[sj-nav] failed to compute path:', href, err);
7554    }
7555  }
7556
7557  var origOpen = window.open;
7558  window.open = function(url, target, features) {
7559    if (typeof url === 'string' && isInternal(url)) { postNav(url); return null; }
7560    return origOpen ? origOpen.call(window, url, target, features) : null;
7561  };
7562
7563  // 1. Anchor clicks (capture phase to beat any in-page handlers).
7564  document.addEventListener('click', function(e) {
7565    var el = e.target && e.target.closest && e.target.closest('a[href],[href],[to],[data-href],[data-to],[onclick]');
7566    if (!el) return;
7567    var href = el.getAttribute('href')
7568      || el.getAttribute('to')
7569      || el.getAttribute('data-href')
7570      || el.getAttribute('data-to')
7571      || '';
7572    if (!href) {
7573      var onclickAttr = el.getAttribute('onclick') || '';
7574      var locationMatch = onclickAttr.match(/(?:window\\.)?(?:location(?:\\.href)?|location\\.assign|location\\.replace)\\s*(?:=|\\()\\s*['"]([^'"]+)['"]/i);
7575      href = locationMatch ? locationMatch[1] : '';
7576    }
7577    if (!href || href.startsWith('#') || /^javascript:/i.test(href)) return;
7578    if (!isInternal(href)) {
7579      el.setAttribute('target', '_blank');
7580      el.setAttribute('rel', 'noopener noreferrer');
7581      return;
7582    }
7583    e.preventDefault();
7584    e.stopPropagation();
7585    postNav(href);
7586  }, true);
7587
7588  // 2. Form submits with internal action (login forms, search, etc.) — the AI
7589  // sometimes wires these instead of links. Block default and ask parent to
7590  // swap, append form data as query string for GET.
7591  document.addEventListener('submit', function(e) {
7592    var form = e.target;
7593    if (!form || form.tagName !== 'FORM') return;
7594    var action = form.getAttribute('action') || '';
7595    if (!action || !isInternal(action)) return;
7596    if ((form.getAttribute('method') || 'GET').toUpperCase() !== 'GET') return;
7597    e.preventDefault();
7598    e.stopPropagation();
7599    try {
7600      var fd = new FormData(form);
7601      var qs = new URLSearchParams();
7602      fd.forEach(function(v, k) { if (typeof v === 'string') qs.set(k, v); });
7603      var sep = action.includes('?') ? '&' : '?';
7604      postNav(action + (qs.toString() ? sep + qs.toString() : ''));
7605    } catch (err) {
7606      console.warn('[sj-nav] form submit intercept failed:', err);
7607    }
7608  }, true);
7609
7610  // 3. Programmatic navigation: window.location.assign / replace, and direct
7611  // assignment to .href / window.location. Apps written by the AI use
7612  // location.href = '/dashboard.html' a lot — without this hook those calls
7613  // would navigate the iframe to about:srcdoc/dashboard.html which the browser
7614  // resolves wrong, sometimes ending up on studiojungle.ai.
7615  try {
7616    var loc = window.location;
7617    var origAssign = loc.assign.bind(loc);
7618    var origReplace = loc.replace.bind(loc);
7619    loc.assign = function(url) {
7620      if (typeof url === 'string' && isInternal(url)) { postNav(url); return; }
7621      try { origAssign(url); } catch (e) {}
7622    };
7623    loc.replace = function(url) {
7624      if (typeof url === 'string' && isInternal(url)) { postNav(url); return; }
7625      try { origReplace(url); } catch (e) {}
7626    };
7627    var hrefDescriptor = Object.getOwnPropertyDescriptor(window.location, 'href');
7628    if (!hrefDescriptor || hrefDescriptor.configurable) {
7629      Object.defineProperty(window.location, 'href', {
7630        configurable: true,
7631        get: function() { return loc.toString(); },
7632        set: function(url) {
7633          if (typeof url === 'string' && isInternal(url)) { postNav(url); return; }
7634          try { origAssign(url); } catch (e) {}
7635        },
7636      });
7637    }
7638  } catch (e) {
7639    // Some browsers freeze Location. Click/form/assign/replace intercepts still work.
7640  }
7641})();
7642<\/script>
7643`,Gme=m.forwardRef(({html:e,projectId:t,visualEditorActive:r,onVisualEditClick:n,onVisualEditMulti:s,onVisualEditDrop:i},o)=>{const l=m.useRef(null),c=m.useMemo(()=>{const d=AD(e);return r?CD(d):d},[e,r]);m.useEffect(()=>{console.log("[visual-editor] LiveWebPreview html changed — iframe will re-render",{len:(e==null?void 0:e.length)??0})},[e]),m.useEffect(()=>{var h;const d=(h=l.current)==null?void 0:h.contentWindow;if(!d)return;const p={type:r?"sj:visual-editor-on":"sj:visual-editor-off"};console.log("[sj-visual-editor] parent → iframe",p),d.postMessage(p,"*")},[r,c]),m.useEffect(()=>{function d(p){var f,x,g,y,b;const h=p==null?void 0:p.data;if(!(!h||typeof h!="object")&&p.source===((f=l.current)==null?void 0:f.contentWindow)){if(h.type==="sj:visual-editor-ready"){console.log("[sj-visual-editor] iframe ready → replying with",r?"on":"off"),(x=p.source)==null||x.postMessage({type:r?"sj:visual-editor-on":"sj:visual-editor-off"},"*");return}if(h.type==="sj:visual-edit-clicked"){const v=(g=l.current)==null?void 0:g.getBoundingClientRect();if(!v)return;console.log("[sj-visual-editor] click captured",h.payload),n==null||n({...h.payload,iframeOffset:{top:v.top,left:v.left}})}if(h.type==="sj:visual-edit-multi"){const v=(y=l.current)==null?void 0:y.getBoundingClientRect();if(!v)return;const k={top:v.top,left:v.left};s==null||s(h.payload.items.map(N=>({...N,iframeOffset:k})))}if(h.type==="sj:visual-edit-drop"){const v=(b=l.current)==null?void 0:b.getBoundingClientRect();if(!v)return;const k={top:v.top,left:v.left};i==null||i({...h.payload.source,iframeOffset:k},{...h.payload.target,iframeOffset:k})}}}return window.addEventListener("message",d),()=>window.removeEventListener("message",d)},[n,s,i,r]);const u=m.useCallback(async()=>{var h,f,x;if(!((h=l.current)!=null&&h.contentWindow))return;try{const g=l.current.contentWindow.location.href||"";if((/\/studio(?:\/|$)/.test(g)||/studiojungle\.ai/i.test(g))&&g!=="about:srcdoc"){l.current.srcdoc=c;return}}catch{l.current.srcdoc=c;return}let d="",p="";if(t){try{const{data:g}=await G.from("project_cloud_config").select("env_vars").eq("project_id",t).maybeSingle();(f=g==null?void 0:g.env_vars)!=null&&f.SUPABASE_URL&&((x=g==null?void 0:g.env_vars)!=null&&x.SUPABASE_ANON_KEY)&&(d=g.env_vars.SUPABASE_URL,p=g.env_vars.SUPABASE_ANON_KEY)}catch{}if(!d)try{const{data:g}=await G.from("projects").select("custom_supabase_url, custom_supabase_anon_key").eq("id",t).single();d=(g==null?void 0:g.custom_supabase_url)||"",p=(g==null?void 0:g.custom_supabase_anon_key)||""}catch{}}if((!d||!p)&&(d="https://xfmlsevleobdlnjqxmdi.supabase.co",p="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"),d&&p){l.current.contentWindow.postMessage({type:"auth-config",url:d,anonKey:p},"*");try{l.current.contentWindow.localStorage.setItem("sj_auth_url",d),l.current.contentWindow.localStorage.setItem("sj_auth_key",p)}catch{}}},[t,c]);return a.jsx("iframe",{ref:l,srcDoc:c,className:"w-full h-full bg-white",sandbox:"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-storage-access-by-user-activation",title:"Ap
7643p Preview",onLoad:u})});Gme.displayName="LiveWebPreview";const Kme=m.forwardRef(({html:e,visualEditorActive:t,onVisualEditClick:r,onVisualEditMulti:n,onVisualEditDrop:s},i)=>{const o=m.useRef(null),l=m.useMemo(()=>{const c=AD(e);return t?CD(c):c},[e,t]);return m.useEffect(()=>{var u;const c=(u=o.current)==null?void 0:u.contentWindow;c&&c.postMessage({type:t?"sj:visual-editor-on":"sj:visual-editor-off"},"*")},[t,l]),m.useEffect(()=>{function c(u){var p,h,f,x,g;const d=u==null?void 0:u.data;if(!(!d||typeof d!="object")&&u.source===((p=o.current)==null?void 0:p.contentWindow)){if(d.type==="sj:visual-editor-ready"){(h=u.source)==null||h.postMessage({type:t?"sj:visual-editor-on":"sj:visual-editor-off"},"*");return}if(d.type==="sj:visual-edit-clicked"){const y=(f=o.current)==null?void 0:f.getBoundingClientRect();if(!y)return;r==null||r({...d.payload,iframeOffset:{top:y.top,left:y.left}})}if(d.type==="sj:visual-edit-multi"){const y=(x=o.current)==null?void 0:x.getBoundingClientRect();if(!y)return;const b={top:y.top,left:y.left};n==null||n(d.payload.items.map(v=>({...v,iframeOffset:b})))}if(d.type==="sj:visual-edit-drop"){const y=(g=o.current)==null?void 0:g.getBoundingClientRect();if(!y)return;
7643const b={top:y.top,left:y.left};s==null||s({...d.payload.source,iframeOffset:b},{...d.payload.target,iframeOffset:b})}}}return window.addEventListener("message",c),()=>window.removeEventListener("message",c)},[r,n,s,t]),a.jsxs("div",{className:"relative flex h-full w-full items-center justify-center overflow-auto py-4",style:{perspective:"1200px"},children:[a.jsx("div",{className:"absolute inset-0 pointer-events-none bg-[radial-gradient(circle_at_center,rgba(34,197,94,0.10),transparent_42%)]"}),a.jsxs("div",{className:"relative flex flex-col rounded-[3.2rem] border border-white/10 bg-gradient-to-b from-[#0d0d12] via-[#24242b] to-[#08080b] shadow-2xl",style:{width:"min(392px, calc(100vw - 96px))",height:"min(800px, calc(100vh - 160px))",minHeight:"640px",maxHeight:"calc(100vh - 160px)",padding:"12px 10px",boxShadow:"0 0 0 1px rgba(255,255,255,0.08) inset, 0 25px 60px -12px rgba(0,0,0,0.5), 0 8px 24px -4px rgba(0,0,0,0.3), -4px 0 12px -2px rgba(0,0,0,0.15), 4px 0 12px -2px rgba(0,0,0,0.15)"},children:[a.jsx("div",{className:"absolute -left-[3px] top-[120px] w-[3px] h-[32px] rounded-l-sm bg-gradient-to-b from-[#3a3a42] to-[#2a2a30]"}),a.jsx("div",{className:"absolute -left-[3px] top-[164px] w-[3px] h-[32px] rounded-l-sm bg-gradient-to-b from-[#3a3a42] to-[#2a2a30]"}),a.jsx("div",{className:"absolute -right-[3px] top-[148px] w-[3px] h-[48px] rounded-r-sm bg-gradient-to-b from-[#3a3a42] to-[#2a2a30]"}),a.jsxs("div",{className:"flex-1 flex flex-col rounded-[2.6rem] overflow-hidden bg-black relative",children:[a.jsxs("div",{className:"absolute top-[10px] left-1/2 -translate-x-1/2 z-20 flex items-center gap-2 bg-black rounded-full px-4 py-[5px]",style:{minWidth:"120px"},children:[a.jsx("div",{className:"w-[8px] h-[8px] rounded-full bg-[#1a1a2e] ring-1 ring-[#2a2a3a]"}),a.jsx("div",{className:"flex-1"}),a.jsx("div",{className:"w-[6px] h-[6px] rounded-full bg-[#0a3d0a]"})]}),a.jsxs("div",{className:"h-[52px] bg-black flex items-end justify-between px-8 pb-1 shrink-0 z-10",children:[a.jsx("span",{className:"text-[12px] font-semibold text-white/90 tabular-nums",children:"9:41"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("svg",{width:"16",height:"12",viewBox:"0 0 16 12",fill:"none",className:"text-white/90",children:[a.jsx("path",{d:"M1 8.5h1.5v3H1zM4 6.5h1.5v5H4zM7 4.5h1.5v7H7zM10 2h1.5v9.5H10z",fill:"
7643currentColor",opacity:"0.9"}),a.jsx("path",{d:"M13 0h1.5v11.5H13z",fill:"currentColor",opacity:"0.3"})]}),a.jsx("svg",{width:"16",height:"12",viewBox:"0 0 16 12",fill:"none",className:"text-white/90",children:a.jsx("path",{d:"M8 3.5c1.8 0 3.4.7 4.6 1.9l1.1-1.1C12.1 2.7 10.1 1.8 8 1.8S3.9 2.7 2.3 4.3l1.1 1.1C4.6 4.2 6.2 3.5 8 3.5zm0 3c1 0 1.9.4 2.6 1l1.1-1.1C10.6 5.4 9.3 4.8 8 4.8s-2.6.6-3.7 1.6l1.1 1.1c.7-.6 1.6-1 2.6-1zM8 9a1.5 1.5 0 100 3 1.5 1.5 0 000-3z",fill:"currentColor"})}),a.jsxs("svg",{width:"27",height:"13",viewBox:"0 0 27 13",fill:"none",className:"text-white/90",children:[a.jsx("rect",{x:"0.5",y:"1",width:"22",height:"11",rx:"3",stroke:"currentColor",opacity:"0.35"}),a.jsx("rect",{x:"2",y:"2.5",width:"16",height:"8",rx:"1.5",fill:"currentColor",opacity:"0.9"}),a.jsx("path",{d:"M24 5v3.5a2 2 0 000-3.5z",fill:"currentColor",opacity:"0.4"})]})]})]}),a.jsx("iframe",{ref:o,srcDoc:l,className:"flex-1 w-full bg-white",sandbox:"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-storage-access-by-user-activation",title:"Mobile Preview",onLoad:()=>{var c;if((c=o.current)!=null&&c.contentWindow)try{const u=o.current.contentWindow.location.href||"";(/\/studio(?:\/|$)/.test(u)||/studiojungle\.ai/i.test(u))&&u!=="about:srcdoc"&&(o.current.srcdoc=l)}catch{o.current.srcdoc=l}}}),a.jsx("div",{className:"h-[26px] bg-black flex items-center justify-center shrink-0",children:a.jsx("div",{className:"w-[120px] h-[4px] rounded-full bg-white/25"})})]})]})]})});Kme.displayName="LiveMobilePreview";function Yme({progress:e,filesCount:t}){const[r,n]=m.useState("");m.useEffect(()=>{const o=setInterval(()=>{n(l=>l.length>=3?"":l+".")},500);return()=>clearInterval(o)},[]);const s=[{label:"Analyzing your requirements",threshold:10},{label:"Designing the architecture",threshold:25},{label:"Generating components",threshold:50},{label:"Building the interface",threshold:75},{label:"Polishing the details",threshold:90},{label:"Almost ready",threshold:100}],i=s.find(o=>e<o.threshold)||s[s.length-1];return a.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gradient-to-br from-background via-background to-primary/5",children:a.jsxs("div",{className:"text-center space-y-6 max-w-sm px-6 relative",children:[a.jsxs("div",{className:"relative mx-auto w-16 h-16",children:[a.jsx("div",{className:"absolute inset-0 rounded-2xl bg-primary/10 animate-ping",style:{animationDuration:"2s"}}),a.jsx("div",{className:"relative w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center overflow-hidden",children:a.jsx(Dn,{className:"w-7 h-7 text-primary animate-pulse"})})]}),a.jsxs("div",{className:"space-y-1.5 relative",style:{minHeight:"3rem"},children:[a.jsxs("h2",{className:"text-lg font-bold text-foreground",children:["Building your app",r]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:i.label})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("div",{className:"h-1.5 bg-secondary rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full bg-gradient-to-r from-primary to-accent rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(5,e)}%`}})}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground",children:i.label}),a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground",children:[Math.round(e),"%"]})]})]}),t>0&&a.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-[11px] text-primary",children:[a.jsx(Nu,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t," file",t!==1?"s":""," generated"]})]}),a.jsx("div",{className:"space-y-1.5 text-left max-w-xs mx-auto",children:s.slice(0,Math.ceil(e/20)+1).map((o,l)=>{const c=e>=o.threshold,u=o===i;return a.jsxs("div",{className:L("flex items-center gap-2 text-[11px] transition-all duration-500",c?"text-primary":u?"text-foreground":"text-muted-foreground/40"),children:[c?a.jsx(mn,{className:"w-3.5 h-3.5 shrink-0"}):u?a.jsx(ze,{className:"w-3.5 h-3.5 shrink-0 animate-spin"}):a.jsx("div",{className:"w-3.5 h-3.5 rounded-full border border-muted-foreground
7643/30 shrink-0"}),a.jsx("span",{children:o.label})]},l)})})]})})}function i_(e){const t=e.toLowerCase();return/module compile error:.*node_modules\/vite\/dist\/client/i.test(t)?!0:/cannot find module|ts\d{4}|failed to resolve|syntaxerror|referenceerror|enoent|eresolve/i.test(t)?!1:/hmr disabled|reload-loop guard|hmr_loop_escalated|failed to connect to websocket|hmr connection|vite.*websocket|\[vite\]|sandbox.*not.*found|sandbox.*not.*running|vite dev server did not start|connection error: failed to fetch|preview runtime request failed/i.test(t)}const Jme=6e4;function Xme(){var _t;const{mode:e,target:t,previewHtml:r,setPreviewHtml:n,isBuilding:s,generatedBlockCount:i,buildProgress:o,liveStatus:l,generatedPages:c,setGeneratedPages:u,activePageId:d,setActivePageId:p,copilotData:h,copilotSql:f,copilotError:x,copilotLoading:g,currentWorkflow:y,project:b,triggerBuildRef:v,files:k,setFiles:N,saveProjectFiles:j,appendBuildError:w,lastBuildErrors:S,firstBuildDone:T}=gn(),C=m.useRef(k),A=m.useRef(r),P=m.useRef(c),E=m.useRef(d);m.useEffect(()=>{C.current=k},[k]),m.useEffect(()=>{A.current=r},[r]),m.useEffect(()=>{P.current=c},[c]),m.useEffect(()=>{E.current=d},[d]);const _=m.useRef(0),I=m.useRef(!1),D=m.useRef(!1),M=m.useRef(new Map),B=m.useRef(null),$=m.useRef([]),K=m.useRef(new Set),R=m.useRef(!1);m.useEffect(()=>{_.current=Date.now()+Jme,I.current=!1,D.current=!1,M.current.clear(),B.current=null,$.current=[],K.current.clear()},[b==null?void 0:b.id]),m.useEffect(()=>{s?D.current=!0:D.current&&(I.current=!0)},[s]);const Y=m.useMemo(()=>Bme(k),[k]),Z=m.useMemo(()=>{const z=new Set(Y.map(ee=>ee.path.replace(/^\/+/,"").replace(/\\/g,"/")));return z.has("package.json")&&(z.has("src/main.tsx")||z.has("src/main.jsx")||z.has("src/main.ts")||z.has("src/main.js"))},[Y]);m.useEffect(()=>{function z(ee){const de=ee==null?void 0:ee.data;if(!de||typeof de!="object"||de.type!=="sj-nav")return;const ge=String(de.path||"").split(/[?#]/)[0];if(!ge)return;const Se=ge.startsWith("/")?ge:`/${ge}`,Ie=P.current,De=At=>{if(!At)return"/";const Fn=At.split("#")[0].split("?")[0]||"/";let mr=Fn.startsWith("/")?Fn:`/${Fn}`;return mr=mr.replace(/\/+/g,"/"),mr==="/index"||mr==="/index.html"||(mr=mr.replace(/\/index\.html$/i,"").replace(/\.html$/i,""),mr.length>1&&(mr=mr.replace(/\/$/,"")),["/home","/homepage","/landing","/landing-page"].includes(mr.toLowerCase()))?"/":mr||"/"},Ce={"/products":["/shop","/store","/catalog","/items","/browse"],"/cart":["/basket","/shopping-cart","/bag"],"/checkout":["/payment","/pay","/order"],"/account":["/profile","/my-account","/user"],"/auth":["/login","/signin","/signup","/register"]},xn=De(Se),et=new Set([xn]);Object.entries(Ce).forEach(([At,Fn])=>{(At===xn||Fn.includes(xn))&&(et.add(At),Fn.forEach(mr=>et.add(mr)))});const wt=Ie.find(At=>et.has(De(At.id)))||Ie.find(At=>`/${At.filename}`===Se)||Ie.find(At=>et.has(De((At.name||"").toLowerCase().replace(/\s+/g,"-"))));wt?(p(wt.id),n(wt.html)):console.warn("[sj-nav] no matching page for path:",Se,"available:",Ie.map(At=>At.id))}return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},[p,n]);const[O,ne]=m.useState(t==="mobile"?"mobile":"web"),oe=m.useRef((b==null?void 0:b.id)??null),he=m.useRef(t);m.useEffect(()=>{const z=(b==null?void 0:b.id)??null,ee=oe.current!==z,de=he.current!==t;oe.current=z,he.current=t,!(!ee&&!de)&&(ve(!1),ne(t==="mobile"?"mobile":"web"))},[b==null?void 0:b.id,t]);const[ae,ve]=m.useState(!1);m.useEffect(()=>{if(ae||O!=="web")return;const z=(de,ge,Se="")=>{if(!de)return!1;for(const Ie of de){const De=Se?`${Se}/${Ie.name}`:Ie.name;if(Ie.type==="file"&&ge(Ie,De)||Ie.type==="folder"&&z(Ie.children,ge,De))return!0}return!1};z(k,(de,ge)=>ge==="src/content.types.ts")&&(ve(!0),console.log("[preview] substrate project detected — keeping instant Desktop preview; Build check stays manual"))},[k,O,ae]);const[re,se]=m.useState(!1),[le,te]=m.useState(!1),[We,Me]=m.useState(Pb),[Te,Ee]=m.useState(null),[st,xt]=m.useState([]),[on,Yt]=m.useState("#ff0000"),[mt,ln]=m.useState(""),[at,gt]=m.useState(16),$t=m.useCallback(()=>{xt([]),document.querySelectorAll("iframe").forEach(ee=>{var de;return(de=ee.contentWindow)==null?void 0:de.postMessage({type:"sj:clear-multi-select"},"*")})},[]),ue=m.useCallback(()=>
7643{if(!(b!=null&&b.id)){Me(Pb());return}Lme(b.id).then(z=>{Me(z??Pb())})},[b==null?void 0:b.id]);m.useEffect(()=>{ue()},[ue]),m.useEffect(()=>{const z=ee=>{const de=ee.detail;de!=null&&de.projectId&&de.projectId!==(b==null?void 0:b.id)||ue()};return window.addEventListener("sj:infra-changed",z),()=>window.removeEventListener("sj:infra-changed",z)},[b==null?void 0:b.id,ue]),m.useCallback((z,ee)=>{var wt,At;const de=((wt=z.sourceMarker)==null?void 0:wt.split(":")[0])||"",ge=((At=ee.sourceMarker)==null?void 0:At.split(":")[0])||"",Ie=de&&ge&&de===ge?de:de||ge||"",De=(z.text||"").slice(0,200),Ce=(ee.text||"").slice(0,200);if(!De&&!Ce){W.error("Drag-to-reorder needs visible text on both elements");return}const xn=Ie?`
7644Source file: \`${Ie}\``:"",et=["Reorder two adjacent elements in the source.","Element being moved (currently rendered first OR was being dragged):",`  text: "${De}"`,`  tag: <${z.tagName}>`,`  class: "${z.className}"`,"","Drop target (where the dragged element should now go — adjacent to it OR replacing its position):",`  text: "${Ce}"`,`  tag: <${ee.tagName}>`,`  class: "${ee.className}"`,xn,"","Use str_replace tools to physically swap the two elements' positions in the file.","Preserve all attributes, classes, and inner content. After the swap, reply with one short sentence."].join(`
7645`);window.dispatchEvent(new CustomEvent("sj:visual-edit-submit",{detail:{mode:"ai",instruction:et,elementText:z.text,tagName:z.tagName,className:z.className}})),W.success("Drag swap sent to AI",{description:Ie?`${z.tagName} ↔ ${ee.tagName} in ${Ie}`:`${z.tagName} ↔ ${ee.tagName}`})},[]);const[je,ct]=m.useState([]),[it,q]=m.useState([]),Nt=50;m.useEffect(()=>{ct([]),q([])},[b==null?void 0:b.id]);const U=m.useCallback(z=>{N(z.files),n(z.previewHtml),p(z.activePageId),u(z.generatedPages)},[N,n,p,u]),Ne=m.useCallback(()=>{ct(z=>{if(z.length===0)return W.message("Nothing to undo"),z;const ee=z[z.length-1],de=z.slice(0,-1);return q(ge=>[...ge,{files:C.current,previewHtml:A.current,activePageId:E.current,generatedPages:P.current,label:ee.label}].slice(-Nt)),U(ee),W.success("Undid: "+ee.label),de})},[U]),Ft=m.useCallback(()=>{q(z=>{if(z.length===0)return W.message("Nothing to redo"),z;const ee=z[z.length-1],de=z.slice(0,-1);return ct(ge=>[...ge,{files:C.current,previewHtml:A.current,activePageId:E.current,generatedPages:P.current,label:ee.label}].slice(-Nt)),U(ee),W.success("Redid: "+ee.label),de})},[U]);m.useEffect(()=>{function z(ee){var Ie,De,Ce;if(!le)return;const de=(De=(Ie=ee.target)==null?void 0:Ie.tagName)==null?void 0:De.toLowerCase();if(de==="input"||de==="textarea"||(Ce=ee.target)!=null&&Ce.isContentEditable||!(ee.metaKey||ee.ctrlKey))return;const Se=ee.key.toLowerCase();Se==="z"&&!ee.shiftKey?(ee.preventDefault(),Ne()):(Se==="z"&&ee.shiftKey||Se==="y")&&(ee.preventDefault(),Ft())}return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[le,Ne,Ft]);const Zt=m.useCallback(async(z,ee)=>{var Ic;if(z.kind==="ai"){window.dispatchEvent(new CustomEvent("sj:visual-edit-submit",{detail:{mode:"ai",instruction:z.instruction,elementText:ee.text,tagName:ee.tagName,className:ee.className,imgSrc:ee.imgSrc}})),W.success("Sent to Studio Jungle AI",{description:"Watch the chat for the change."}),Ee(null);return}const de=ee.text;if(!de){Ee(null);return}if(z.kind==="text"&&(!z.newText||z.newText===de)){Ee(null);return}const ge=z.kind==="text"?`Text edit "${de.slice(0,20)}…"`:z.kind==="color"?"Color change":z.kind==="visibility"?"Hide element":z.kind==="format"?"Format change":z.kind==="heading"?`Heading → ${z.level}`:z.kind==="image"?"Image swap":z.kind==="spacing"?"Spacing change":"Visual edit";ct(Ue=>[...Ue,{files:C.current,previewHtml:A.current,activePageId:E.current,generatedPages:P.current,label:ge}].slice(-Nt)),q([]);function Se(Ue,Bt){const ut=/\sstyle\s*=\s*"([^"]*)"/i,cn=Ue.match(ut);let Qn=[];cn&&(Qn=cn[1].split(";").map(Xe=>Xe.trim()).filter(Boolean));for(const[Xe,St]of Object.entries(Bt)){const Mn=Xe.toLowerCase();Qn=Qn.filter(Ir=>!Ir.toLowerCase().startsWith(Mn+":")),St&&Qn.push(`${Xe}: ${St}`)}const Ye=Qn.join("; "),pt=Ye?` style="${Ye}"`:"";return cn?Ue.replace(ut,pt):`${Ue}${pt}`}function Ie(Ue){const Bt=Ue.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(Bt.replace(/[\s ]+/g,"(?:&nbsp;|[\\s\\u00A0])+"))}function De(Ue,Bt,ut){const cn=Ie(Bt),Qn=Ue.match(cn);if(!Qn)return null;const Ye=Ue.indexOf(Qn[0]);if(Ye<0)return null;const pt=new RegExp(`<${ut}\\b([^>]*)>`,"gi");let Xe=null,St;for(;(St=pt.exec(Ue))!==null&&!(St.index>=Ye);)Xe=St;return Xe?{idx:Xe.index,full:Xe[0],attrs:Xe[1]||"",textIdx:Ye}:null}function Ce(Ue,Bt,ut,cn){const Qn=Ie(Bt).source,Ye=new RegExp(`<([a-zA-Z][a-zA-Z0-9]*)((?:\\s+[^>]*)?)>(${Qn})</\\1\\s*>`),pt=Ue.match(Ye);if(pt){const[Ir,gr,vr,ws]=pt,Ps=Se(vr||"",ut);return Ue.replace(Ir,`<${gr}${Ps}>${ws}</${gr}>`)}if(!cn)return null;const Xe=De(Ue,Bt,cn);if(!Xe)return null;const St=Se(Xe.attrs,ut),Mn=`<${cn}${St}>`;return Ue.slice(0,Xe.idx)+Mn+Ue.slice(Xe.idx+Xe.full.length)}const xn={h1:"2.5rem",h2:"2rem",h3:"1.5rem",h4:"1.25rem",h5:"1.125rem",h6:"1rem",p:"1rem"};function et(Ue,Bt,ut,cn){const Qn=Ie(Bt).source,Ye=new RegExp(`<([a-zA-Z][a-zA-Z0-9]*)((?:\\s+[^>]*)?)>(${Qn})</\\1\\s*>`),pt=Ue.match(Ye);if(pt){const[Ps,,ca,Jr]=pt,cr=Se(ca||"",{"font-size":xn[ut]});return Ue.replace(Ps,`<${ut}${cr}>${Jr}</${ut}>`)}if(!cn)return null;const Xe=De(Ue,Bt,cn);if(!Xe)return null;const St=new RegExp(`</${cn}\\s*>`,"gi");St.lastIndex=Xe.textIdx;const Mn=St.exec(Ue);if(!Mn)return null;const Ir=Se(Xe.attrs,{"font-size":xn[ut]}),gr=Ue.slice(0,Xe.idx),vr=Ue.slice(Xe.idx+Xe.full.length,Mn.index),ws=Ue.slice(Mn.index+Mn[0].length);return`${gr}<${ut}${Ir}>${vr}</${ut}>${ws}`}function wt(Ue,Bt,ut){if(!Bt)return null;const cn=Bt.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Qn=new RegExp(`(<img\\b[^>]*\\bsrc\\s*=\\s*["'])${cn}
7645(["'][^>]*>)`,"i");return Qn.test(Ue)?Ue.replace(Qn,`$1${ut}$2`):null}let At;if(z.kind==="text"){const Ue=z.newText;At=Bt=>{if(Bt.includes(de))return Bt.replace(de,Ue);const ut=Ie(de);return ut.test(Bt)?Bt.replace(ut,Ue):null}}else if(z.kind==="color"){const Ue={};z.textColor&&(Ue.color=z.textColor),z.bgColor&&(Ue["background-color"]=z.bgColor),At=Bt=>Ce(Bt,de,Ue,ee.tagName)}else if(z.kind==="visibility")At=Ue=>Ce(Ue,de,{display:"none"},ee.tagName);else if(z.kind==="format"){const Ue={};z.bold&&(Ue["font-weight"]="900"),z.italic&&(Ue["font-style"]="italic"),z.underline&&(Ue["text-decoration"]="underline"),At=Bt=>Ce(Bt,de,Ue,ee.tagName)}else if(z.kind==="heading")At=Ue=>et(Ue,de,z.level,ee.tagName);else if(z.kind==="image"){const Ue=z.src,Bt=ee.imgSrc||"";At=ut=>wt(ut,Bt,Ue)}else if(z.kind==="spacing"){const Ue={};z.padding!==void 0&&(Ue.padding=`${z.padding}px`),z.margin!==void 0&&(Ue.margin=`${z.margin}px`),At=Bt=>Ce(Bt,de,Ue,ee.tagName)}else At=()=>null;const Fn=[];function mr(Ue,Bt=""){for(const ut of Ue){const cn=Bt?`${Bt}/${ut.name}`:ut.name;if(ut.type==="folder"&&ut.children)mr(ut.children,cn);else if(ut.type==="file"&&typeof ut.content=="string"){if(qr&&cn!==qr&&!cn.endsWith("/"+qr))continue;const Qn=At(ut.content);Qn!=null&&Qn!==ut.content&&Fn.push({path:cn,node:ut,updated:Qn})}}}const ts=C.current,zi=A.current,Tc=P.current,Qs=E.current,qr=ee.sourceMarker?ee.sourceMarker.split(":")[0]:"";if(mr(ts),qr&&Fn.length===0){let Ue=function(Bt,ut=""){for(const cn of Bt){const Qn=ut?`${ut}/${cn.name}`:cn.name;if(cn.type==="folder"&&cn.children)Ue(cn.children,Qn);else if(cn.type==="file"&&typeof cn.content=="string"){const Ye=At(cn.content);Ye!=null&&Ye!==cn.content&&Fn.push({path:Qn,node:cn,updated:Ye})}}};Ue(ts)}const vs=(zi?At(zi):null)!=null,fi=Qs?Tc.find(Ue=>Ue.id===Qs):null,mi=(fi!=null&&fi.html?At(fi.html):null)!=null;console.log("[visual-editor] applying",{kind:z.kind,oldTextLen:de.length,fileMatches:Fn.map(Ue=>Ue.path),previewHasMatch:vs,activePageId:Qs,activePageHasMatch:mi});function xl(Ue){const Bt=Ue.find(cn=>/(?:^|\/)index\.html$/i.test(cn.path));if(Bt)return Bt;const ut=Ue.find(cn=>/\.html$/i.test(cn.path));return ut||Ue[0]}if(Fn.length===0&&!vs&&!mi){W.error("Could not find that element",{description:"The clicked element couldn't be located in any file or the preview HTML."}),Ee(null);return}if(mi&&fi){const Ue=fi.id;u(Bt=>Bt.map(ut=>{if(ut.id!==Ue)return ut;const cn=At(ut.html);return cn!=null?{...ut,html:cn}:ut}))}if(vs&&n(Ue=>Ue&&(At(Ue)??Ue)),Fn.length===0){Qs&&!mi&&vs&&p(null),W.success("Edited (preview only)",{description:"No source-file match."}),Ee(null);return}const Er=xl(Fn),Ec=Er.path;function Hs(Ue,Bt=""){return Ue.map(ut=>{const cn=Bt?`${Bt}/${ut.name}`:ut.name;return ut.type==="file"&&cn===Ec?{...ut,content:Er.updated}:ut.type==="folder"&&ut.children?{...ut,children:Hs(ut.children,cn)}:ut})}if(N(Hs(ts)),j){console.log("[visual-editor] saving to DB",{path:Er.path,name:Er.node.name,oldLen:((Ic=Er.node.content)==null?void 0:Ic.length)??0,newLen:Er.updated.length,firstDiff:(()=>{const Ue=Er.node.content||"",Bt=Er.updated;for(let ut=0;ut<Math.min(Ue.length,Bt.length);ut++)if(Ue[ut]!==Bt[ut])return`pos ${ut}: '${Ue.slice(ut,ut+60)}' → '${Bt.slice(ut,ut+60)}'`;return"lengths differ at end"})()});try{await j([{name:Er.node.name,path:Er.path,content:Er.updated}]),console.log("[visual-editor] saveProjectFiles SUCCEEDED for",Er.path)}catch(Ue){console.error("[visual-editor] saveProjectFiles failed",Ue),W.error("Saved locally, but failed to persist to cloud",{description:Ue.message})}}Qs&&!mi?vs?p(null):/\.html$/i.test(Er.path)&&(n(Er.updated),p(null)):!vs&&!mi&&/\.html$/i.test(Er.path)&&n(Er.updated);const yl=z.kind==="text"?"Edited":z.kind==="color"?"Color updated":z.kind==="visibility"?"Hidden":z.kind==="format"?"Formatted":z.kind==="heading"?"Heading changed":z.kind==="image"?"Image swapped":z.kind==="spacing"?"Spacing updated":"Updated";W.success(Fn.length>1?`${yl} (${Fn.length} files matched, picked one)`:yl,{description:Er.path}),Ee(null)},[p,N,n,u,j]),Ke=m.useCallback(async z=>{console.log("[visual-editor BULK] start",{count:st.length,targets:st.map(de=>({tag:de.tagName,text:de.text.slice(0,40),cls:de.className.slice(0,40)}))});let ee=0;for(const de of st){ee++;const ge=z(de);
7645if(console.log(`[visual-editor BULK] iter ${ee}/${st.length}`,{payload:ge,target:{tag:de.tagName,text:de.text.slice(0,40)}}),!ge){console.warn(`[visual-editor BULK] iter ${ee} skipped — no payload`);continue}try{await Zt(ge,de),await new Promise(Se=>setTimeout(Se,0)),console.log(`[visual-editor BULK] iter ${ee} done · filesRef len:`,C.current.length)}catch(Se){console.error(`[visual-editor BULK] iter ${ee} THREW`,Se)}}console.log("[visual-editor BULK] all done — clearing selection"),$t()},[st,Zt,$t]),ie=m.useCallback(z=>{if(!z)return"/";const ee=z.split("#")[0].split("?")[0]||"/";let de=ee.startsWith("/")?ee:`/${ee}`;return de=de.replace(/\/+/g,"/"),de==="/index"||de==="/index.html"||(de=de.replace(/\/index\.html$/i,"").replace(/\.html$/i,""),de.length>1&&(de=de.replace(/\/$/,"")),["/home","/homepage","/landing","/landing-page"].includes(de.toLowerCase()))?"/":de||"/"},[]),we=m.useMemo(()=>{const z=new Map;for(const ee of c){if(qf(ee.html))continue;const de=ie(ee.id),ge=z.get(de);if(!ge){z.set(de,ee);continue}const Se=ie(ge.id)===ge.id,Ie=ie(ee.id)===ee.id;!Se&&Ie&&z.set(de,ee)}return Array.from(z.values())},[c,ie]),Je=m.useMemo(()=>{const z=ny(k).find(ee=>ee.path==="src/content.ts");return z?pF(z.content).map(ee=>({id:ie(ee.id),name:ee.name,source:"react"})):[]},[k,ie]),ot=m.useMemo(()=>{const z=new Map,ee=Je.length>0;for(const De of Je)z.set(De.id,De);for(const De of we){const Ce=ie(De.id);ee&&Dk.has(Ce)||z.has(Ce)||z.set(Ce,{id:Ce,name:De.name||nw(Ce),source:"static"})}for(const De of Ume(k)){const Ce=ie(De.id);ee&&Dk.has(Ce)||z.has(Ce)||z.set(Ce,{...De,id:Ce,name:De.name||nw(Ce)})}const de=/^\/(?:auth[/_-]callback|oauth[/_-]?callback|callback|auth\/confirm|verify-email)\/?$/i,ge=/^\/(?:login|signin|signup|register|auth|forgot-password|reset-password|profile|account\/settings)\/?$/i,Se=Array.from(z.values()),Ie=Se.some(De=>!ge.test(De.id)&&!de.test(De.id));return Se.filter(De=>De.id!=="*"&&De.id!=="/*"&&!De.id.endsWith("/*")).filter(De=>!de.test(De.id)).filter(De=>!Ie||!ge.test(De.id)).sort((De,Ce)=>De.id==="/"?-1:Ce.id==="/"?1:De.name.localeCompare(Ce.name))},[Je,k,ie,we]),V=m.useMemo(()=>{var ee,de;if(ot.some(ge=>ge.id===d))return d||"";const z=ie(d);return((ee=ot.find(ge=>ie(ge.id)===z))==null?void 0:ee.id)||((de=ot[0])==null?void 0:de.id)||""},[d,ie,ot]),ye=m.useCallback(z=>{const ee=ie(z),de={"/products":["/shop","/store","/catalog","/items","/browse"],"/cart":["/basket","/shopping-cart","/bag"],"/checkout":["/payment","/pay","/order"],"/account":["/profile","/my-account","/user"],"/auth":["/login","/signin","/signup","/register"]},ge=new Set([ee]);return Object.entries(de).forEach(([Se,Ie])=>{(Se===ee||Ie.includes(ee))&&(ge.add(Se),Ie.forEach(De=>ge.add(De)))}),c.find(Se=>{const Ie=ie(Se.id),De=ie((Se.name||"").toLowerCase().replace(/\s+/g,"-"));return ge.has(Ie)||ge.has(De)})||null},[c,ie]);m.useEffect(()=>{t==="mobile"?ne("mobile"):t==="web"&&ne("web")},[t]),m.useEffect(()=>{if(!(S!=null&&S.length)||Date.now()<_.current||R.current||!S.some(PF))return;const z=PD(k),ee=z.find(Ce=>Ce.path==="src/main.tsx"||Ce.path==="src/main.jsx"),de=z.find(Ce=>Ce.path==="src/App.tsx"||Ce.path==="src/App.jsx");if(!ee||!de||!(b!=null&&b.id))return;const ge=MT(ee.content,de.content);if(!ge)return;R.current=!0;const Se=[];if(ge.mainContent&&ge.mainContent!==ee.content&&Se.push({path:ee.path,content:bm(ge.mainContent)}),ge.appContent&&ge.appContent!==de.content&&Se.push({path:de.path,content:ge.appContent}),Se.length===0){R.current=!1;return}console.info("[preview] applying deterministic router repair",Se.map(Ce=>Ce.path)),B.current="__router_repair__";const Ie=new Map(Se.map(Ce=>[Ce.path,Ce.content])),De=(Ce,xn="")=>Ce.map(et=>{const wt=xn?`${xn}/${et.name}`:et.name,At=wt.replace(/^\/+/,"").split("\\").join("/");return et.type==="file"&&Ie.has(At)?{...et,content:Ie.get(At)}:et.type==="folder"&&et.children?{...et,children:De(et.children,wt)}:et});N(De(k)),j==null||j(Se.map(Ce=>({name:Ce.path.split("/").pop()||Ce.path,path:Ce.path,content:Ce.content,language:Ce.path.endsWith(".tsx")?"tsx":"jsx"}))),Pr({action:"apply",projectId:b.id,files:Se}).finally(()=>{R.current=!1})},[S,k,b==null?void 0:b.id,j,N]),m.useEffect(()=>{if(!T||s||!v.current||!S||S.length===0||Date.now()<_.current)return;const z=S.filter(et=>!i_(et));if(z.length===0)return;const ee=z.slice(0,3).join(`
7646`);if(B.current===ee)return;const de=M.current.get(ee)||0;if(de>=1)return;const ge=2,Se=10*60*1e3,Ie=Date.now(),De=$.current;for(;De.length>0&&Ie-De[0]>Se;)De.shift();if(De.length>=ge)return;De.push(Ie),B.current=ee,M.current.set(ee,de+1);const Ce=z.slice(0,12).map((et,wt)=>`${wt+1}. ${et}`).join(`
7647`),xn=v.current;window.setTimeout(()=>{try{xn(`Fix these preview-runtime errors. EMIT-FIRST PROTOCOL.
7648
7649HARD RULES:
76501. Your FIRST tool call MUST be write_file or str_replace. Not read_file.
76512. Max 2 read_file calls total this turn. If you've read 2 files and haven't fixed it, GUESS and emit a write_file anyway. A wrong patch is better than no patch.
76523. NO prose, NO "I'll inspect…", NO "Let me check…", NO "The issue is…", NO commentary.
76534. If you cannot identify the file from the error message alone, write to the most likely file based on the error path/import name. The reconcile verifier will catch a wrong fix; an over-read turn just burns tokens.
7654
7655Errors:
7656${Ce}
7657
7658Common fixes (apply directly, don't narrate):
7659- TS2307 "Cannot find module './X'" — create X with a default export OR inline what it exported and remove the import.
7660- TS1005 / TS1128 near a string literal — single-quoted string contains an apostrophe; convert to double quotes or template literal.
7661- ENOENT / ERESOLVE / "Cannot find package" — drop the bad package import OR replace with a correct name. Don't blindly add deps.
7662- Vite plugin / config errors — vite.config.ts uses resolve.alias "@": "/src", not Node's path module.
7663- React Router errors — BrowserRouter basename is auto-injected, don't hardcode.
7664
7665End with a 5-word summary of the fix in ask_next_phase.intro. That is the ONLY text you write.`,{overrideModel:"claude-haiku-4-5",isAutoFix:!0})}catch{}},0)},[S,s,T]);const me=m.useRef(!1);m.useEffect(()=>{const z=me.current;if(me.current=s,!z||s||Date.now()<_.current)return;const ee=n1(Y);if(!l0(ee))return;const de=XE(ee,Y);if(de.length>0&&j&&(b!=null&&b.id)){console.log(`[dep-check] auto-stubbing ${de.length} missing import target(s)`,de.map(et=>et.path));for(const et of de)console.info("[stub-write]",{projectId:b.id,path:et.path,importer:et.triggeredBy.importer,spec:et.triggeredBy.spec});j(de.map(et=>({name:et.path.split("/").pop()||et.path,path:et.path,content:et.content}))).catch(et=>console.warn("[dep-check] stub persist failed:",et)),(async()=>{const et=de.map(wt=>wt.path).join(", ");try{const wt=await Pr({action:"apply_via_agent",projectId:b.id,files:de.map(At=>({path:At.path,content:At.content}))});if((wt==null?void 0:wt.ok)!==!1)return;throw console.warn("[dep-check] apply_via_agent returned non-ok:",wt),new Error("apply_via_agent returned non-ok")}catch(wt){console.warn("[dep-check] apply_via_agent failed, trying legacy apply:",wt==null?void 0:wt.message);try{const At=await Pr({action:"apply",projectId:b.id,files:de.map(Fn=>({path:Fn.path,content:Fn.content}))});if((At==null?void 0:At.ok)!==!1)return;throw new Error("legacy apply returned non-ok")}catch(At){const Fn=`Failed to write stub for missing import(s): ${et}. Sandbox file-sync failed (${(At==null?void 0:At.message)||"unknown"}).`;console.error("[dep-check] STUB_WRITE_FAILED:",Fn),w(`STUB_WRITE_FAILED: ${Fn}`)}}})()}const ge=new Set(de.map(et=>et.path)),Se=ee.missingFiles.filter(et=>![...ge].some(wt=>wt.endsWith(et.spec.split("/").pop()||""))),Ie={...ee,missingFiles:Se},Ce=[...new Set(Ie.missingPackages.map(et=>et.pkg))].filter(et=>sx[et]);if(Ce.length>0&&(b!=null&&b.id)&&j){const et=Y.find(wt=>wt.path.replace(/^\/+/,"")==="package.json");if(et){const{content:wt,added:At}=e1(et.content,Ce);if(At.length>0&&(console.log(`[dep-check] auto-merged package.json deps: ${At.join(", ")}`),j([{name:"package.json",path:"package.json",content:wt,language:"json"}]).catch(mr=>console.warn("[dep-check] package.json persist failed:",mr)),Pr({action:"add_deps",projectId:b.id,deps:At,files:[{path:"package.json",content:wt}]}).catch(mr=>console.warn("[dep-check] add_deps after dep patch failed:",mr)),Ie.missingPackages.filter(mr=>!At.includes(mr.pkg)).length===0&&Ie.missingFiles.length===0&&Ie.missingEntrypoints.length===0&&Ie.missingRoutes.length===0))return}}if(!l0(Ie)||!T)return;const xn=KE(Ie);console.log(`[dep-check] caught ${xn.length} unstubbed issue(s) after AI build:`,xn),xn.slice(0,12).forEach(et=>w(`DEP_CHECK: ${et}`))},[s,Y,w,j,b==null?void 0:b.id,T]);const _e=m.useCallback(z=>{const ee=vF(z);u([...c,ee]),p(z);const de=z.replace(/^\//,"").replace(/[-_]/g," ").replace(/\b\w/g,Se=>Se.toUpperCase()),ge=(b==null?void 0:b.description)||"";v.current&&v.current(`Generate the full "${de}" page (route: ${z}) for this project. ${ge?`Project context: ${ge}.`:""} Make it production-quality with real content, proper layout, and styling. NO prose preamble — begin with the first write_file tool call.`,{overrideModel:"claude-haiku-4-5",isAutoFix:!0})},[c,u,p,v,b]),[dt,kt]=m.useState([]),wn=m.useMemo(()=>s?[]:Z?d7(Y):c.length===0?[]:RT(c),[c,s,Z,Y]);m.useEffect(()=>{if(s){kt([]);return}const z=window.setTimeout(()=>{kt(wn)},3e3);return()=>window.clearTimeout(z)},[s,wn]);const kn=dt;m.useEffect(()=>{if(s||kn.length===0||!v.current||!I.current)return;const z=[...kn].sort().join("|");if(K.current.has(z))return;K.current.add(z);const ee=(b==null?void 0:b.description)||"",de=kn.map(ge=>`- ${ge}`).join(`
7666`);v.current(`These nav links exist but their page components weren't built. Generate all of them in this single turn so the customer doesn't see "Page not built yet" 404s.
7667
7668Routes to build:
7669${de}
7670
7671${ee?`Project context: ${ee}.
7672
7673`:""}For each route:
76741. Create src/pages/<RouteName>.tsx with production-quality content matching the existing design system
76752. Verify it's registered in src/App.tsx (add the Route entry if missing)
76763. Keep each page focused on ITS purpose — don't duplicate the home page
7677
7678NO prose preamble, NO commentary between files. Begin with the first write_file tool call. End with a 5-word ask_next_phase.intro 
7678summarizing what was added.`,{overrideModel:"claude-haiku-4-5",isAutoFix:!0})},[s,kn,v,b]),m.useEffect(()=>{se(!1)},[c.length]),m.useEffect(()=>{const z=async ee=>{var de,ge;if(!(!ee.data||typeof ee.data!="object")){if(ee.data.type==="nav-page"){const Se=ee.data.pageId,Ie=ye(Se);Ie?(p(Ie.id),n(Ie.html)):se(!1),ee.data.hash&&setTimeout(()=>{document.querySelectorAll("iframe").forEach(Ce=>{var xn;try{const et=(xn=Ce.contentDocument)==null?void 0:xn.querySelector(ee.data.hash);et&&et.scrollIntoView({behavior:"smooth"})}catch{}})},300)}if(ee.data.type==="request-auth-config"){const Se=b==null?void 0:b.id;if(Se){let Ie="",De="";const{data:Ce}=await G.from("project_cloud_config").select("env_vars").eq("project_id",Se).maybeSingle();if((de=Ce==null?void 0:Ce.env_vars)!=null&&de.SUPABASE_URL&&((ge=Ce==null?void 0:Ce.env_vars)!=null&&ge.SUPABASE_ANON_KEY))Ie=Ce.env_vars.SUPABASE_URL,De=Ce.env_vars.SUPABASE_ANON_KEY;else{const{data:xn}=await G.from("projects").select("custom_supabase_url, custom_supabase_anon_key").eq("id",Se).single();Ie=(xn==null?void 0:xn.custom_supabase_url)||"",De=(xn==null?void 0:xn.custom_supabase_anon_key)||""}Ie&&De?document.querySelectorAll("iframe").forEach(et=>{var wt;(wt=et.contentWindow)==null||wt.postMessage({type:"auth-config",url:Ie,anonKey:De},"*")}):document.querySelectorAll("iframe").forEach(et=>{var wt;(wt=et.contentWindow)==null||wt.postMessage({type:"auth-config-missing"},"*")})}}ee.data.type==="unresolved-route"&&se(!1),ee.data.type==="ai-bot-query"&&document.querySelectorAll("iframe").forEach(Ie=>{var De;(De=Ie.contentWindow)==null||De.postMessage({type:"ai-bot-response",content:"AI chat is not enabled for this project. Ask Studio Jungle to add an AI assistant so it can be wired through the metered AI proxy."},"*")})}};return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},[p,n,ye,b]);const Ae=d&&((_t=ye(d))==null?void 0:_t.html)||r,rt=m.useMemo(()=>{var ee,de;const z=V?(ee=ye(V))==null?void 0:ee.html:null;return z&&!qf(z)?z:((de=c.find(ge=>!qf(ge.html)))==null?void 0:de.html)||null},[c,ye,V]),fe=qf(Ae)?rt:Ae,lt=ie(V||d||"/"),yt=V?ye(V):null,zt=yt==null?void 0:yt.filename,Fe=m.useCallback(z=>{z.forEach(ee=>{i_(ee)||w([`ROUTE_SCOPE: ${lt}`,zt?`LIKELY_PAGE_FILE: ${zt}`:"",`ERROR: ${ee}`].filter(Boolean).join(`
7679`))})},[w,lt,zt]),Jt=(z=>a.jsx(fU,{viewport:z,files:Y,envVars:We,previewPath:lt,projectId:(b==null?void 0:b.id)||null,isBuilding:s,visualEditorActive:le,onVisualEditClick:Ee,onVisualEditMulti:xt,onBuildError:Fe}))(O==="mobile"?"mobile":"desktop");return e==="workflow"?a.jsx(Dme,{workflow:y}):e==="data-copilot"?a.jsx(Eme,{data:h,sql:f,error:x,isLoading:g}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsx("div",{className:"border-b shrink-0",children:a.jsxs("div",{className:"h-10 flex items-center px-3 gap-1",children:[$me.map(z=>a.jsxs("button",{onClick:()=>ne(z.id),title:z.tooltip,className:L("flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition-colors",O===z.id?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground"),children:[a.jsx(z.icon,{className:"w-3.5 h-3.5"}),z.label]},z.id)),(O==="web"||O==="mobile")&&a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:()=>{te(z=>!z),le&&Ee(null)},title:le?"Visual Editor is on — click any element in the preview to edit. Click here to turn off.":"Visual Editor ready — click to enable, then click any element in the preview to edit inline.",className:L("ml-1 flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition-all border",le?"bg-primary/15 text-primary border-primary/30 ring-1 ring-primary/20 shadow-sm":"bg-secondary/40 text-foreground border-border/60 hover:bg-secondary/70 hover:border-border"),children:[a.jsx(i6,{className:L("w-3.5 h-3.5 shrink-0",le?"text-primary":"text-muted-foreground")}),a.jsx("span",{children:"Visual Editor"}),a.jsx("span",{className:L("text-[9px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded-full shrink-0",le?"bg-primary/20 text-primary":"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"),children:le?"on":"ready"})]}),le&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:Ne,disabled:je.length===0,title:je.length?`Undo: ${je[je.length-1].label} (⌘Z)`:"Nothing to undo",className:L("ml-0.5 w-6 h-6 rounded-md flex items-center justify-center transition-colors",je.length===0?"text-muted-foreground
7679/40 cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-secondary"),"aria-label":"Undo last visual edit",children:a.jsx(T6,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:Ft,disabled:it.length===0,title:it.length?`Redo: ${it[it.length-1].label} (⌘⇧Z)`:"Nothing to redo",className:L("w-6 h-6 rounded-md flex items-center justify-center transition-colors",it.length===0?"text-muted-foreground/40 cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-secondary"),"aria-label":"Redo last visual edit",children:a.jsx(g6,{className:"w-3.5 h-3.5"})})]})]}),a.jsxs(B1,{children:[a.jsx(U1,{asChild:!0,children:a.jsx("button",{className:"ml-0.5 w-6 h-6 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors",title:"What's the difference between these modes?","aria-label":"Preview modes help",children:a.jsx(h$,{className:"w-3.5 h-3.5"})})}),a.jsxs(fx,{side:"bottom",align:"start",className:"w-[420px] p-0",children:[a.jsxs("div",{className:"px-4 py-3 border-b",children:[a.jsx("h3",{className:"text-sm font-semibold",children:"Preview modes"}),a.jsx("p",{className:"text-[11.5px] text-muted-foreground mt-0.5",children:"Three ways to see your app — each makes a different speed/fidelity trade-off."})]}),a.jsxs("div",{className:"divide-y",children:[a.jsxs("div",{className:"px-4 py-2.5 flex items-start gap-3",children:[a.jsx(Aw,{className:"w-4 h-4 text-primary mt-0.5 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("p",{className:"text-[12.5px] font-medium",children:["Desktop ",a.jsx("span",{className:"text-[10px] text-muted-foreground font-normal",children:"— live Vite preview"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed mt-0.5",children:"Uses the hosted dev server for real apps. Visual Editor temporarily uses the editable HTML preview."})]})]}),a.jsxs("div",{className:"px-4 py-2.5 flex items-start gap-3",children:[a.jsx(Nc,{className:"w-4 h-4 text-primary mt-0.5 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("p",{className:"text-[12.5px] font-medium",children:["Mobile ",a.jsx("span",{className:"text-[10px] text-muted-foreground font-normal",children:"— interactive phone preview"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed mt-0.5",children:"Renders the generated app inside Studio Jungle device chrome so tabs, forms, and tap-through flows can be checked at phone size."})]})]})]}),a.jsxs("div",{className:"px-4 py-2 border-t bg-secondary/30 text-[10.5px] text-muted-foreground",children:[a.jsx("strong",{className:"text-foreground/80",children:"Tip:"})," small edits sync into the live preview; dependencies install only when package.json changes."]})]})]}),ot.length>0&&a.jsxs("div",{className:"relative ml-2",children:[a.jsx("select",{value:V,onChange:z=>{const ee=z.target.value;p(ee);const de=ye(ee);de&&n(de.html)},className:"appearance-none bg-secondary/50 border rounded-md pl-2.5 pr-6 py-1 text-[11px] font-medium cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/30",children:ot.map(z=>{const ee=ie(z.id);return a.jsx("option",{value:z.id,children:`${z.name} (${ee})`},z.id)})}),a.jsx(Yr,{className:"absolute right-1.5 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground pointer-events-none"})]}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s&&a.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-primary",children:[a.jsx(zr,{className:"w-3 h-3 animate-spin"}),"Updating preview..."]}),i>0&&!s&&a.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[a.jsx(Nu,{className:"w-3 h-3"}),i," files"]}),a.jsx("button",{className:"text-muted-foreground hover:text-foreground transition-colors p-1 rounded hover:bg-secondary",title:"Open preview in new tab",onClick:()=>{const z=document.querySelector('iframe[title="Live preview"], iframe[title="Live preview (mobile)"]'),ee=z!=null&&z.src&&z.src!=="about:blank"?z.src:null;if(ee){window.open(ee,"_blank");return}if(fe){const de=new Blob([fe],{type:"text/html"}),ge=URL.createObjectURL(de);window.open(ge,"_blank");return}W.message("No preview available yet",{description:"Generate the project first, then try again."})},children:a.jsx(Is,{className:"w-3.5 h-3.5"})})]})]})}),!s&&kn.length>0&&!re&&a.jsx("div",{className:"border-b bg-primary/5 px-3 py-2 shrink-0",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Dn,{className:"w-3.5 h-3.5 text-primary mt-0.5 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate missing pages"}),a.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["These pages are linked but not yet built. Click to generate:"," ",a.jsx("span",{className:"inline-flex flex-wrap gap-1 mt-0.5",children:kn.map(z=>a.jsxs("button",{onClick:()=>_e(z),className:"inline-flex items-center gap-1 px-1.5 py-0.5 bg-primary/10 hover:bg-primary/20 text-primary rounded text-[10px] font-mono curs
7679or-pointer transition-colors border border-primary/20 hover:border-primary/30",children:[a.jsx("span",{children:"+"})," ",z]},z))})]})]}),a.jsx("button",{onClick:()=>se(!0),className:"text-muted-foreground hover:text-foreground p-0.5 shrink-0",children:a.jsx(qn,{className:"w-3 h-3"})})]})}),a.jsxs("div",{className:L("flex-1 flex items-center justify-center overflow-hidden relative",O==="web"?"p-0":"p-6 bg-secondary/20"),children:[(O==="web"||O==="mobile")&&a.jsx("div",{className:"h-full w-full min-w-0 self-stretch",children:Jt}),s&&!fe&&!Z&&a.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background pointer-events-none",children:a.jsx(Yme,{progress:o,filesCount:i})})]}),a.jsx(Mme,{target:Te,onApply:Zt,onClose:()=>Ee(null)}),st.length>0&&a.jsxs("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-[100] flex items-center gap-1.5 px-3 py-2 rounded-xl bg-card border shadow-2xl flex-wrap max-w-[760px]",children:[a.jsxs("span",{className:"font-mono text-[11px] uppercase tracking-wider text-muted-foreground pr-2 border-r mr-1 whitespace-nowrap",children:[st.length," selected"]}),a.jsx("input",{type:"color",value:on,onChange:z=>Yt(z.target.value),className:"w-7 h-6 p-0 border rounded cursor-pointer bg-transparent",title:"Color picker"}),a.jsx("button",{onClick:()=>Ke(()=>({kind:"color",textColor:on})),className:"px-2 py-1 rounded text-[11px] font-semibold bg-primary text-primary-foreground hover:bg-primary/90",children:"Color"}),a.jsx("span",{className:"w-px h-5 bg-border mx-0.5"}),a.jsx("button",{onClick:()=>Ke(()=>({kind:"format",bold:!0})),title:"Bold all",className:"w-7 h-6 rounded border bg-background text-xs font-bold text-foreground hover:bg-muted",children:"B"}),a.jsx("button",{onClick:()=>Ke(()=>({kind:"format",italic:!0})),title:"Italic all",className:"w-7 h-6 rounded border bg-background text-xs italic text-foreground hover:bg-muted",children:"I"}),a.jsx("button",{onClick:()=>Ke(()=>({kind:"format",underline:!0})),title:"Underline all",className:"w-7 h-6 rounded border bg-background text-xs underline text-foreground hover:bg-muted",children:"U"}),a.jsx("span",{className:"w-px h-5 bg-border mx-0.5"}),a.jsxs("select",{value:mt,onChange:z=>{const ee=z.target.value;ln(ee),ee&&Ke(()=>({kind:"heading",level:ee}))},className:"h-6 bg-background border rounded text-[11px] px-1 focus:outline-none focus:ring-1 focus:ring-primary/40",title:"Set heading level for all selected",children:[a.jsx("option",{value:"",children:"Head…"}),a.jsx("option",{value:"h1",children:"h1"}),a.jsx("option",{value:"h2",children:"h2"}),a.jsx("option",{value:"h3",children:"h3"}),a.jsx("option",{value:"h4",children:"h4"}),a.jsx("option",{value:"h5",children:"h5"}),a.jsx("option",{value:"h6",children:"h6"}),a.jsx("option",{value:"p",children:"p"})]}),a.jsx("span",{className:"w-px h-5 bg-border mx-0.5"}),a.jsx("input",{type:"number",value:at,onChange:z=>gt(Math.max(0,Math.min(96,Number(z.target.value)||0))),className:"w-12 h-6 bg-background border rounded text-[11px] px-1.5 text-right focus:outline-none focus:ring-1 focus:ring-primary/40",min:0,max:96,title:"Padding in pixels"}),a.jsx("button",{onClick:()=>Ke(()=>({kind:"spacing",padding:at})),className:"px-2 py-1 rounded text-[11px] font-semibold bg-muted text-foreground hover:bg-muted/80",title:"Apply padding to all selected",children:"Pad"}),a.jsx("span",{className:"w-px h-5 bg-border mx-0.5"}),a.jsx("button",{onClick:()=>Ke(()=>({kind:"visibility",hide:!0})),className:"px-2 py-1 rounded text-[11px] font-semibold bg-muted text-foreground hover:bg-muted/80",children:"Hide"}),a.jsx("span",{className:"w-px h-5 bg-border mx-0.5"}),a.jsx("button",{onClick:$t,className:"w-6 h-6 rounded hover:bg-muted flex items-center justify-center text-muted-foreground","aria-label":"Clear selection",children:a.jsx(qn,{className:"w-3.5 h-3.5"})})]})]})}const Zme=["A photography portfolio with a gallery and an about page","A coffee shop site with menu, hours, and a contact page","A personal tech blog with three sample posts","A yoga studio site with class schedule and pricing"];function Qme(e){const t=new TextEncoder().encode(e);let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ege(e){const t="https://xfmlsevleobdlnjqxmdi.supabase.co",r=Qme(JSON.stringify(e)),n=`${t}/functions/v1/wp-blueprint?b=${r}`;return`https://playground.wordpress.net/?blueprint-url=${encodeURIComponent(n)}`}function _D({onGoHome:e}){const[t,r]=m.useState(""),[n,s]=m.useState(!1),[i,o]=m.useState(null),[l,c]=m.useState(""),u=async p=>{const h=p.trim();if(!(!h||n)){s(!0),o(null);try{const{data:f,error:x}=await G.functions.invoke("wp-generate",{body:{prompt:h}});if(x)throw new Error(x.message||"Generation failed");if(!(f!=null&&f.blueprint))throw new Error((f==null?void 0:f.error)||"No blueprint returned");o(ege(f.blueprint)),c(h),W.success("Blueprint ready — click “Open WordPress site”.")}catch(f){W.error(`Couldn’t generate site: ${f.message}`)}finally{s(!1)}}},d=m.useRef(!1);return m.useEffect(()=>{if(d.current)return;d.current=!0;let p="";try{p=sessionStorage.getItem("sj_wp_initial_prompt")||"",p&&sessionStorage.removeItem("sj_wp_initial_prompt")}catch{}p.trim()&&(r(p),u(p))},[]),a.jsxs("div",{className:"flex h-full w-full flex-col",children:[a.jsxs("div",{className:"border-b border-border bg-card px-3 py-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[e&&a.jsx("button",{onClick:e,title:"Back to home",className:"inline-flex items-center rounded-md px-1.5 py-1 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground",children:a.jsx(ei,{className:"h-3.5 w-3.5"})}),a.jsx(b$,{className:"h-4 w-4 shrink-0 text-primary"}),a.jsx("input",{value:t,onChange:p=>r(p.target.value),onKeyDown:p=>{p.key==="Enter"&&u(t)},placeholder:"Describe a WordPress site to build…",disabled:n,className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground disabled:opacity-60"}),a.jsxs("button",{onClick:()=>u(t),disabled:n||!t.trim(),className:"inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-60",children:[n?a.jsx(ze,{className:"h-3.5 w-3.5 animate-spin"}):a.jsx(Dn,{className:"h-3.5 w-3.5"}),n?"Generating…":"Generate"]})]}),a.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:Zme.map(p=>a.jsx("button",{onClick:()=>{r(p),u(p)},disabled:n,className:"rounded-full border border-border px-2 py-0.5 text-[10.5px] text-muted-foreground hover:bg-secondary disabled:opacity-60",children:p},p))})]}),i&&!n?a.jsxs("div",{className:"flex flex-1 flex-col",children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-card px-3 py-1.5 text-xs",children:[a.jsx(Br,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),a.jsx("span",{className:"font-medium",children:"WordPress Preview"}),a.jsxs("span",{className:"truncate text-muted-foreground",children:["· “",l,"” · admin / password at /wp-admin"]}),a.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex shrink-0 items-center gap-1 text-primary hover:underline",children:["Open in new tab ",a.jsx(Is,{className:"h-3 w-3"})]})]}),a.jsx("iframe",{title:"WordPress Preview",src:`/wp-embed.html?u=${encodeURIComponent(i)}`,className:"w-full flex-1 border-0"})]}):a.jsx("div",{className:"flex flex-1 items-center justify-center p-6",children:n?a.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[a.jsx(ze,{className:"h-7 w-7 animate-spin text-primary"}),a.jsx("p",{className:"text-sm font-medium",children:"Generating your WordPress blueprint…"}),a.jsx("p",{className:"max-w-sm text-xs text-muted-foreground",children:"Studio Jungle is designing the site (theme, pages, content) as a WordPress Playground Blueprint."})]}):a.jsxs("div",{className:"flex max-w-md flex-col items-center gap-3 text-center text-muted-foreground",children:[a.jsx(Br,{className:"h-8 w-8 text-muted-foreground
7679/50"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Describe a WordPress site"}),a.jsx("p",{className:"text-xs",children:"Type a description above or pick an example. Studio Jungle generates a WordPress Blueprint and boots a real WordPress site right here — theme, pages, and content included. Build a NEW site (it can’t redesign an existing URL)."})]})})]})}const Xd={status:"loading",tables:[],functions:[],users:[],storage:[]};function zh(e){const[t,r]=m.useState(Xd),[n,s]=m.useState(!0),i=m.useCallback(async()=>{var o;if(!e){r({...Xd,status:"not_provisioned"}),s(!1);return}s(!0);try{const c=((o=(await G.auth.getSession()).data.session)==null?void 0:o.access_token)||"",u=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/fetch-project-infra",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"},body:JSON.stringify({projectId:e})}),d=await u.json();u.ok?d.status==="not_provisioned"?r({...Xd,status:"not_provisioned"}):r({status:"provisioned",project_ref:d.project_ref,project_url:d.project_url,project_status:d.project_status,tables:d.tables||[],functions:d.functions||[],users:d.users||[],storage:d.storage||[],fetched_at:d.fetched_at}):r({...Xd,status:"error",error:d.error})}catch(l){r({...Xd,status:"error",error:l.message})}finally{s(!1)}},[e]);return m.useEffect(()=>{i()},[i]),{infra:t,loading:n,refresh:i}}var ry="Collapsible",[tge,Eve]=sl(ry),[nge,qj]=tge(ry),TD=m.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:s,disabled:i,onOpenChange:o,...l}=e,[c,u]=ac({prop:n,defaultProp:s??!1,onChange:o,caller:ry});return a.jsx(nge,{scope:r,disabled:i,contentId:io(),open:c,onOpenToggle:m.useCallback(()=>u(d=>!d),[u]),children:a.jsx(En.div,{"data-state":Wj(c),"data-disabled":i?"":void 0,...l,ref:t})})});TD.displayName=ry;var ED="CollapsibleTrigger",ID=m.forwardRef((e,t)=>{const{__scopeCollapsible:r,...n}=e,s=qj(ED,r);return a.jsx(En.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":Wj(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...n,ref:t,onClick:vn(e.onClick,s.onOpenToggle)})});ID.displayName=ED;var Hj="CollapsibleContent",OD=m.forwardRef((e,t)=>{const{forceMount:r,...n}=e,s=qj(Hj,e.__scopeCollapsible);return a.jsx(Fa,{present:r||s.open,children:({present:i})=>a.jsx(rge,{...n,ref:t,present:i})})});OD.displayName=Hj;var rge=m.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:n,children:s,...i}=e,o=qj(Hj,r),[l,c]=m.useState(n),u=m.useRef(null),d=Tr(t,u),p=m.useRef(0),h=p.current,f=m.useRef(0),x=f.current,g=o.open||l,y=m.useRef(g),b=m.useRef(void 0);return m.useEffect(()=>{const v=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(v)},[]),Ii(()=>{const v=u.current;if(v){b.current=b.current||{transitionDuration:v.style.transitionDuration,animationName:v.style.animationName},v.style.transitionDuration="0s",v.style.animationName="none";const k=v.getBoundingClientRect();p.current=k.height,f.current=k.width,y.current||(v.style.transitionDuration=b.current.transitionDuration,v.style.animationName=b.current.animationName),c(n)}},[o.open,n]),a.jsx(En.div,{"data-state":Wj(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!g,...i,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":x?`${x}px`:void 0,...e.style},children:g&&s})});function Wj(e){return e?"open":"closed"}var sge=TD;const age=sge,ige=ID,oge=OD;function lge(e,t,r){const n=e.map(s=>{const i=s.display_name,o=i.replace(/_([a-z])/g,(u,d)=>d.toUpperCase()),c=s.columns.filter(u=>!["id","created_at","updated_at"].includes(u.name)).map(u=>`  ${u.name}${u.nullable?"?":""}: ${td(u.type)};`).join(`
7680`);return`
7681// ─── ${i.toUpperCase()} ────────────────────────────────────
7682
7683export interface ${Dr(o)} {
7684  id: string;
7685${s.columns.map(u=>`  ${u.name}: ${td(u.type)};`).join(`
7686`)}
7687}
7688
7689export interface ${Dr(o)}Insert {
7690${c}
7691}
7692
7693/** List all ${i} records */
7694export async function list${Dr(o)}(options?: { limit?: number; offset?: number; orderBy?: string; orderDir?: 'asc' | 'desc' }): Promise<${Dr(o)}[]> {
7695  const params = new URLSearchParams({
7696    limit: String(options?.limit ?? 100),
7697    offset: String(options?.offset ?? 0),
7698    order_by: options?.orderBy ?? 'created_at',
7699    order_dir: options?.orderDir ?? 'desc',
7700  });
7701  const res = await fetch(\`\${BASE_URL}/\${PROJECT_ID}/${i}?\${params}\`, {
7702    headers: authHeaders(),
7703  });
7704  if (!res.ok) throw new Error(await res.text());
7705  const data = await res.json();
7706  return data.rows;
7707}
7708
7709/** Create a new ${i} record */
7710export async function create${Dr(o)}
7710(record: ${Dr(o)}Insert): Promise<${Dr(o)}> {
7711  const res = await fetch(\`\${BASE_URL}/\${PROJECT_ID}/${i}\`, {
7712    method: 'POST',
7713    headers: { ...authHeaders(), 'Content-Type': 'application/json' },
7714    body: JSON.stringify(record),
7715  });
7716  if (!res.ok) throw new Error(await res.text());
7717  const data = await res.json();
7718  return data.rows[0];
7719}
7720
7721/** Update a ${i} record by ID */
7722export async function update${Dr(o)}(id: string, fields: Partial<${Dr(o)}Insert>): Promise<${Dr(o)}> {
7723  const res = await fetch(\`\${BASE_URL}/\${PROJECT_ID}/${i}\`, {
7724    method: 'PUT',
7725    headers: { ...authHeaders(), 'Content-Type': 'application/json' },
7726    body: JSON.stringify({ id, ...fields }),
7727  });
7728  if (!res.ok) throw new Error(await res.text());
7729  const data = await res.json();
7730  return data.rows[0];
7731}
7732
7733/** Delete a ${i} record by ID */
7734export async function delete${Dr(o)}(id: string): Promise<void> {
7735  const params = new URLSearchParams({ id });
7736  const res = await fetch(\`\${BASE_URL}/\${PROJECT_ID}/${i}?\${params}\`, {
7737    method: 'DELETE',
7738    headers: authHeaders(),
7739  });
7740  if (!res.ok) throw new Error(await res.text());
7741}`}).join(`
7742`);return`// ══════════════════════════════════════════════════════
7743// Auto DB SDK — Fetch
7744// Generated ${new Date().toISOString().split("T")[0]}
7745// ══════════════════════════════════════════════════════
7746
7747const BASE_URL = '${t}';
7748const PROJECT_ID = '${r}';
7749
7750// Replace with your auth token logic
7751function authHeaders(): Record<string, string> {
7752  const token = localStorage.getItem('auth_token') || '';
7753  return { Authorization: \`Bearer \${token}\` };
7754}
7755${n}
7756`}function cge(e,t,r){const n=e.map(s=>{const i=s.display_name,o=i.replace(/_([a-z])/g,(u,d)=>d.toUpperCase()),c=s.columns.filter(u=>!["id","created_at","updated_at"].includes(u.name)).map(u=>`  ${u.name}${u.nullable?"?":""}: ${td(u.type)};`).join(`
7757`);return`
7758// ─── ${i.toUpperCase()} ────────────────────────────────────
7759
7760export interface ${Dr(o)} {
7761  id: string;
7762${s.columns.map(u=>`  ${u.name}: ${td(u.type)};`).join(`
7763`)}
7764}
7765
7766export interface ${Dr(o)}Insert {
7767${c}
7768}
7769
7770export const ${o} = {
7771  async list(options?: { limit?: number; offset?: number; orderBy?: string; orderDir?: 'asc' | 'desc' }): Promise<${Dr(o)}[]> {
7772    const { data } = await api.get(\`/\${PROJECT_ID}/${i}\`, {
7773      params: { limit: options?.limit ?? 100, offset: options?.offset ?? 0, order_by: options?.orderBy ?? 'created_at', order_dir: options?.orderDir ?? 'desc' },
7774    });
7775    return data.rows;
7776  },
7777
7778  async create(record: ${Dr(o)}Insert): Promise<${Dr(o)}> {
7779    const { data } = await api.post(\`/\${PROJECT_ID}/${i}\`, record);
7780    return data.rows[0];
7781  },
7782
7783  async update(id: string, fields: Partial<${Dr(o)}Insert>): Promise<${Dr(o)}> {
7784    const { data } = await api.put(\`/\${PROJECT_ID}/${i}\`, { id, ...fields });
7785    return data.rows[0];
7786  },
7787
7788  async delete(id: string): Promise<void> {
7789    await api.delete(\`/\${PROJECT_ID}/${i}\`, { params: { id } });
7790  },
7791};`}).join(`
7792`);return`// ══════════════════════════════════════════════════════
7793// Auto DB SDK — Axios
7794// Generated ${new Date().toISOString().split("T")[0]}
7795// ══════════════════════════════════════════════════════
7796
7797import axios from 'axios';
7798
7799const BASE_URL = '${t}';
7800const PROJECT_ID = '${r}';
7801
7802const api = axios.create({
7803  baseURL: BASE_URL,
7804  headers: {
7805    'Content-Type': 'application/json',
7806  },
7807});
7808
7809// Add auth interceptor — replace with your auth logic
7810api.interceptors.request.use((config) => {
7811  const token = localStorage.getItem('auth_token') || '';
7812  config.headers.Authorization = \`Bearer \${token}\`;
7813  return config;
7814});
7815${n}
7816`}function uge(e,t){const r=t.replace(/-/g,"").slice(0,12),n=e.map(s=>{const i=s.display_name,o=`dyn_${r}_${i}`,l=i.replace(/_([a-z])/g,(d,p)=>p.toUpperCase()),u=s.columns.filter(d=>!["id","created_at","updated_at"].includes(d.name)).map(d=>`  ${d.name}${d.nullable?"?":""}: ${td(d.type)};`).join(`
7817`);return`
7818// ─── ${i.toUpperCase()} ────────────────────────────────────
7819// Real table name: ${o}
7820
7821export interface ${Dr(l)} {
7822  id: string;
7823${s.columns.map(d=>`  ${d.name}: ${td(d.type)};`).join(`
7824`)}
7825}
7826
7827export interface ${Dr(l)}Insert {
7828${u}
7829}
7830
7831export const ${l} = {
7832  async list(options?: { limit?: number; orderBy?: string; ascending?: boolean }) {
7833    let query = supabase.from('${o}').select('*');
7834    if (options?.orderBy) query = query.order(options.orderBy, { ascending: options.ascending ?? false });
7835    if (options?.limit) query = query.limit(options.limit);
7836    const { data, error } = await query;
7837    if (error) throw error;
7838    return data as ${Dr(l)}[];
7839  },
7840
7841  async create(record: ${Dr(l)}Insert) {
7842    const { data, error } = await supabase.from('${o}').insert(record).select().single();
7843    if (error) throw error;
7844    return data as ${Dr(l)};
7845  },
7846
7847  async update(id: string, fields: Partial<${Dr(l)}Insert>) {
7848    const { data, error } = await supabase.from('${o}').update(fields).eq('id', id).select().single();
7849    if (error) throw error;
7850    return data as ${Dr(l)};
7851  },
7852
7853  async delete(id: string) {
7854    const { error } = await supabase.from('${o}').delete().eq('id', id);
7855    if (error) throw error;
7856  },
7857};`}).join(`
7858`);return`// ══════════════════════════════════════════════════════
7859// Auto DB SDK — Supabase JS (Direct)
7860// Generated ${new Date().toISOString().split("T")[0]}
7861// Use this if your app connects directly to the same
7862// Supabase instance (BYOS or managed).
7863// ══════════════════════════════════════════════════════
7864
7865import { createClient } from '@supabase/supabase-js';
7866
7867const SUPABASE_URL = 'YOUR_SUPABASE_URL';
7868const SUPABASE_ANON_KEY = 'YOUR_SUPABASE_ANON_KEY';
7869
7870const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
7871${n}
7872`}function td(e){const t=e.toUpperCase();return t.includes("INT")||t.includes("NUMERIC")||t.includes("FLOAT")||t.includes("DOUBLE")?"number":t.includes("BOOL")?"boolean":t.includes("JSON")?"Record<string, any>":"string"}function Dr(e){return e.charAt(0).toUpperCase()+e.slice(1)}function dge({tables:e,projectId:t,baseUrl:r}){const[n,s]=m.useState("fetch"),[i,o]=m.useState(!1),[l,c]=m.useState(new Set),u=m.useMemo(()=>{switch(n){case"fetch":return lge(e,r,t);case"axios":return cge(e,r,t);case"supabase-js":return uge(e,t)}},[n,e,r,t]),d=()=>{navigator.clipboard.writeText(u),o(!0),W.success("SDK code copied to clipboard!"),setTimeout(()=>o(!1),2e3)},p=f=>{const x=u.split(`
7873`),g=x.findIndex(v=>v.includes(`─── ${f.toUpperCase()} ─`));if(g===-1)return;const y=x.findIndex((v,k)=>k>g+1&&v.includes("─── ")),b=x.slice(g,y===-1?void 0:y).join(`
7874`);navigator.clipboard.writeText(b),W.success(`${f} SDK copied!`)},h=f=>{c(x=>{const g=new Set(x);return g.has(f)?g.delete(f):g.add(f),g})};return e.length===0?a.jsxs("div",{className:"p-6 text-center text-muted-foreground text-xs",children:[a.jsx(hp,{className:"w-8 h-8 mx-auto mb-2 text-muted-foreground/40"}),a.jsx("p",{children:"Create Auto DB tables to generate SDK code"})]}):a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx(hp,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs font-medium text-foreground",children:"Client SDK"}),a.jsx("div",{className:"flex-1"}),a.jsxs(Ns,{value:n,onValueChange:f=>s(f),children:[a.jsx(hs,{className:"h-6 text-[11px] w-[110px]",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"fetch",children:"Fetch"}),a.jsx(Dt,{value:"axios",children:"Axios"}),a.jsx(Dt,{value:"supabase-js",children:"Supabase JS"})]})]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"h-6 text-[11px] gap-1",onClick:d,children:[i?a.jsx(Wn,{className:"w-3 h-3"}):a.jsx(gs,{className:"w-3 h-3"}),i?"Copied!":"Copy All"]})]}),a.jsxs($r,{className:"flex-1",children:[a.jsx("div",{className:"p-2 space-y-1",children:e.map(f=>{const x=l.has(f.display_name),g=f.display_name.replace(/_([a-z])/g,(y,b)=>b.toUpperCase());return a.jsxs(age,{open:x,onOpenChange:()=>h(f.display_name),children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(ige,{asChild:!0,children:a.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs gap-1.5 flex-1 justify-start font-mono",children:[x?a.jsx(Yr,{className:"w-3 h-3"}):a.jsx(ia,{className:"w-3 h-3"}),f.display_name,a.jsxs(Ge,{variant:"secondary",className:"text-[9px] ml-auto",children:[f.columns.length," cols"]})]})}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>p(f.display_name),children:a.jsx(gs,{className:"w-3 h-3 text-muted-foreground"})})]}),a.jsx(oge,{children:a.jsx("div",{className:"mt-1 mb-2 rounded-md bg-muted/50 border overflow-hidden",children:a.jsx("pre",{className:"p-3 text-[11px] leading-relaxed font-mono text-foreground overflow-x-auto whitespace-pre",children:`// Available methods:
7875${g}.list({ limit: 10, orderBy: 'created_at' })
7876${g}.create({ ${f.columns.filter(y=>!["id","created_at","updated_at"].includes(y.name)).map(y=>`${y.name}: ...`).join(", ")} })
7877${g}.update(id, { ... })
7878${g}.delete(id)`})})})]},f.id)})}),a.jsxs("div",{className:"border-t",children:[a.jsxs("div",{className:"px-3 py-1.5 bg-muted/30 flex items-center gap-1.5",children:[a.jsx(hp,{className:"w-3 h-3 text-muted-foreground"}),a.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:"Full SDK Code"}),a.jsx(Ge,{variant:"outline",className:"text-[9px] ml-auto",children:n==="fetch"?"Native Fetch":n==="axios"?"Axios":"Supabase JS"})]}),a.jsx("pre",{className:"p-3 text-[11px] leading-relaxed font-mono text-foreground overflow-x-auto whitespace-pre bg-muted/20",children:u})]})]})]})}function pge(e,t,r){const n={};for(const s of e){const i={},o=[];for(const c of s.columns){const u={TEXT:{type:"string"},INTEGER:{type:"integer"},BIGINT:{type:"integer",format:"int64"},NUMERIC:{type:"number"},"DOUBLE PRECISION":{type:"number",format:"double"},BOOLEAN:{type:"boolean"},UUID:{type:"string",format:"uuid"},JSONB:{type:"object"},DATE:{type:"string",format:"date"},"TIMESTAMP WITH TIME ZONE":{type:"string",format:"date-time"}};i[c.name]=u[c.type]||{type:"string"},!c.nullable&&!c.is_primary&&o.push(c.name)}const l=`/${r}/${s.display_name}`;n[l]={get:{summary:`List ${s.display_name}`,operationId:`list_${s.display_name}`,tags:[s.display_name],parameters:[{name:"limit",in:"query",required:!1,schema:{type:"integer",default:100}},{name:"offset",in:"query",required:!1,schema:{type:"integer",default:0}},{name:"order_by",in:"query",required:!1,schema:{type:"string",default:"created_at"}},{name:"order_dir",in:"query",required:!1,schema:{type:"string",enum:["asc","desc"],default:"desc"}}],responses:{200:{description:"List of records",content:{"application/json":{schema:{type:"object",properties:{rows:{type:"array",items:{type:"object",properties:i}},rowCount:{type:"integer"}}}}}}}},post:{summary:`Create ${s.display_name}`,operationId:`create_${s.display_name}`,tags:[s.display_name],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:i,required:o.length>0?o:void 0}}}},responses:{201:{description:"Created record"}}},put:{summary:`Update ${s.display_name}`,operationId:`update_${s.display_name}`,tags:[s.display_name],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",format:"uuid"},...i}}}}},responses:{200:{description:"Updated record"}}},delete:{summary:`Delete ${s.display_name}`,operationId:`delete_${s.display_name}`,tags:[s.display_name],parameters:[{name:"id",in:"query",required:!0,schema:{type:"string",format:"uuid"},description:"Record ID to delete"}],responses:{200:{description:"Deleted"}}}}}return{openapi:"3.0.3",info:{title:"Auto DB API",version:"1.0.0",description:"Live CRUD API for your Auto DB tables. All endpoints execute against your real database."},servers:[{url:t,description:"Auto DB REST Proxy"}],paths:n}}function hge(e,t,r){const n={};for(const s of t.tables){const i=`/${s.name}`,o={},l=[];for(const c of s.columns){const u={UUID:{type:"string",format:"uuid"},TEXT:{type:"string"},VARCHAR:{type:"string"},STRING:{type:"string"},INTEGER:{type:"integer"},INT:{type:"integer"},BIGINT:{type:"integer",format:"int64"},SERIAL:{type:"integer"},NUMBER:{type:"number"},FLOAT:{type:"number",format:"float"},NUMERIC:{type:"number"},DECIMAL:{type:"number"},BOOLEAN:{type:"boolean"},BOOL:{type:"boolean"},TIMESTAMP:{type:"string",format:"date-time"},TIMESTAMPTZ:{type:"string",format:"date-time"},DATE:{type:"string",format:"date"},JSONB:{type:"object"},JSON:{type:"object"},OBJECTID:{type:"string"},ARRAY:{type:"array",format:void 0},OBJECT:{type:"object"}},d=c.type.split("(")[0].split(" ")[0];o[c.name]=u[d]||{type:"string"},!c.isNullable&&!c.isPrimaryKey&&l.push(c.name)}n[i]={get:{summary:`List ${s.name}`,operationId:`list_${s.name}`,tags:[s.name],parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string",default:e.id},description:"DB Connection ID"},{name:"table",in:"query",required:!0,schema:{type:"string",default:s.name},description:"Table name"},{name:"limit",in:"query",required:!1,schema:{type:"integer",default:100}},{name:"offset",in:"query",required:!1,schema:{type:"integer",default:0}}],responses:{200:{description:"List of records",content:{"application/json":{schema:{type:"object",properties:{rows:{type:"array",items:{type:"object",properties:o}},rowCount:{type:"integer"}}}}}}}},post:{summary:`Create ${s.name}`,operationId:`create_${s.name}`,tags:[s.name],parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string",default:e.id}},{name:"table",in:"query",required:!0,schema:{type:"string",default:s.name}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:o,required:l.length>0?l:void 0}}}},responses:{200:{description:"Created record"}}},put:{summary:`Update ${s.name}`,operationId:`update_${s.name}`,tags:[s.name],parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string",default:e.id}},{name:"table",in:"query",required:!0,schema:{type:"string",default:s.name}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},...o}}}}},responses:{200:{description:"Updated record"}}},delete:{summary:`Delete ${s.name}`,operationId:`delete_${s.name}`,tags:[s.name],parameters:[{name:"connectionId",in:"query",required:!0,schema:{type:"string",default:e.id}},{name:"table",in:"query",required:!0,schema:{type:"string",default:s.name}},{name:"id",in:"query",required:!0,schema:{type:"string"},description:"Record ID to delete"}],responses:{200:{description:"Deleted"}}}}}return{openapi:"3.0.3",info:{title:`${e.name} API`,version:"1.0.0",description:`Live CRUD API for ${e.name} (${e.db_type}). All endpoints are real and execute against your connected database.`},servers:[{url:r,description:"Database CRUD Proxy"}],paths:n}}
7878function fge(e){const t={};for(const r of e){t[r.path]||(t[r.path]={});const n=(r.params||[]).map(s=>({name:s,in:r.path.includes(`:${s}`)||r.path.includes(`{${s}}`)?"path":"query",required:r.path.includes(`:${s}`)||r.path.includes(`{${s}}`),schema:{type:"string"}}));t[r.path][r.method.toLowerCase()]={summary:r.description,operationId:`${r.method.toLowerCase()}_${r.path.replace(/[^a-zA-Z0-9]/g,"_")}`,tags:[r.filename||"default"],parameters:n.length>0?n:void 0,responses:{200:{description:"Successful response"}}}}return{openapi:"3.0.3",info:{title:"Generated API (Mock)",version:"1.0.0",description:"Auto-detected API endpoints from generated code. These are not live — connect a database to get real CRUD endpoints."},paths:t}}function mge(){var E;const{apis:e,project:t,files:r}=gn(),n=(t==null?void 0:t.id)||null,{connections:s,loadConnections:i}=Rh(n),{tables:o,loadTables:l}=mx(n),{infra:c}=zh(n),u=m.useMemo(()=>{const _=[...e],I=new Set(_.map(M=>M.path));for(const M of c.functions||[]){const B=`/functions/v1/${M.name}`;I.has(B)||(_.push({id:`infra-${M.name}`,method:"POST",path:B,description:`${M.name} (deployed)`,filename:`supabase/functions/${M.name}/index.ts`}),I.add(B))}const D=(M,B="")=>{for(const $ of M){const K=B?`${B}/${$.name}`:$.name;if($.type==="folder"&&$.children)D($.children,K);else if($.type==="file"&&/^supabase\/functions\/[^/]+\/index\.ts$/.test(K)){const R=K.split("/")[2],Y=`/functions/v1/${R}`;I.has(Y)||(_.push({id:`file-${R}`,method:"POST",path:Y,description:`${R} (in files)`,filename:K}),I.add(Y))}}};return D(r),_},[e,c.functions,r]),[d,p]=m.useState("autodb"),[h,f]=m.useState("swagger");m.useState(null);const[x,g]=m.useState(0),[y,b]=m.useState({status:"idle"});m.useEffect(()=>{n&&(i(),l())},[n,i,l,x]),m.useEffect(()=>{if(!n)return;const _=setInterval(()=>{l(),i()},5e3);return()=>clearInterval(_)},[n,l,i]);const v=async()=>{var I,D,M,B;b({status:"testing"});const _=Date.now();try{const{data:{session:$}}=await G.auth.getSession();if(!$)throw new Error("Not authenticated — please log in first");if(k==="autodb"&&o.length>0){const K=o[0],R=`${S}/${n}/${K.display_name}?limit=5`,Y=await fetch(R,{headers:{Authorization:`Bearer ${$.access_token}`,"Content-Type":"application/json"}}),Z=await Y.json(),O=Date.now()-_;if(!Y.ok)throw new Error(Z.error||`HTTP ${Y.status}`);b({status:"success",message:`Connected! Table "${K.display_name}" responded OK.`,latency:O,rowCount:Z.rowCount??((I=Z.rows)==null?void 0:I.length)??0})}else if(k==="external"&&N){const K=`${w}?connectionId=${N.id}&table=${((M=(D=j==null?void 0:j.tables)==null?void 0:D[0])==null?void 0:M.name)||"test"}&limit=5`,R=await fetch(K,{headers:{Authorization:`Bearer ${$.access_token}`,"Content-Type":"application/json"}}),Y=await R.json(),Z=Date.now()-_;if(!R.ok)throw new Error(Y.error||`HTTP ${R.status}`);b({status:"success",message:`Connected! External DB "${N.name}" responded OK.`,latency:Z,rowCount:Y.rowCount??((B=Y.rows)==null?void 0:B.length)??0})}else throw new Error("No live data source selected. Create Auto DB tables or connect an external DB first.")}catch($){b({status:"error",message:$.message,latency:Date.now()-_})}},k=d==="autodb"?"autodb":d!=null&&d.startsWith("conn_")?"external":"mock",N=k==="external"?s.find(_=>_.id===d.replace("conn_","")):null,j=N==null?void 0:N.cached_schema,w="https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/db-crud",S="https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/autodb-rest",T=o.length>0,C=N&&j&&((E=j.tables)==null?void 0:E.length)>0,A=m.useMemo(()=>k==="autodb"&&T&&n?pge(o,S,n):k==="external"&&C&&N&&j?hge(N,j,w):u.length>0?fge(u):null,[k,T,o,S,n,C,N,j,w,u]);return T||s.length>0||u.length>0?a.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx(Hn,{className:"w-4 h-4 text-primary shrink-0"}),a.jsxs(Ns,{value:d,onValueChange:p,children:[a.jsx(hs,{className:"h-7 text-xs flex-1",children:a.jsx(ks,{placeholder:"Select data source..."})}),a.jsxs(fs,{children:[T&&a.jsx(Dt,{value:"autodb",children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Op,{className:"w-3 h-3"}),"Auto DB (",o.length," tables)"]})}),s.map(_=>a.jsxs(Dt,{value:`conn_${_.id}`,children:[_.name," (",_.db_type,")"]},_.id)),u.length>0&&a.jsxs(Dt,{value:"mock",children:["Mock APIs (",u.length," endpoints)"]})]})]}),k==="autodb"&&T&&a.jsx(Ge,{variant:"outline",className:"text-[10px] bg-primary/10 text-primary border-primary/30",children:"Live"}),k==="external"&&C&&a.jsx(Ge,{variant:"outline",className:"text-[10px] bg-primary/10 text-primary border-primary/30",children:"Live"}),k==="mock"&&a.jsx(Ge,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground border-border",children:"Mock"}),a.jsxs("div",{className:"flex items-center border rounded-md overflow-hidden ml-1",children:[a.jsx("button",{onClick:()=>f("swagger"),className:L("px-2 py-1 text-[10px] font-medium transition-colors",h==="swagger"?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),children:"Docs"}),a.jsxs("button",{onClick:()=>f("sdk"),className:L("px-2 py-1 text-[10px] font-medium transition-colors flex items-center gap-1",h==="sdk"?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),children:[a.jsx(hp,{className:"w-3 h-3"}),"SDK"]}),a.jsxs("button",{onClick:()=>f("test"),className:L("px-2 py-1 text-[10px] font-medium transition-colors flex items-center gap-1",h==="test"?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),children:[a.jsx(hr,{className:"w-3 h-3"}),"Test"]})]}),a.jsx("button",{onClick:()=>{g(_=>_+1)},className:"p-1 rounded hover:bg-muted transition-colors",title:"Refresh data sources",children:a.jsx(zr,{className:"w-3.5 h-3.5 text-muted-foreground"})})]}),k==="mock"&&h==="swagger"&&a.jsxs("div",{className:"px-3 py-1.5 bg-muted border-b flex items-center gap-1.5 text-[11px] text-muted-foreground shrink-0",children:[a.jsx(is,{className:"w-3.5 h-3.5 shrink-0"}),"Mock APIs — create Auto DB tables for live endpoints"]}),h==="test"?a.jsx($r,{className:"flex-1",children:a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"API Connection Test"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify your API endpoints are connected and working by sending a test request to the database."})]}),a.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"space-y-1",children:[a.jsx("p",{className:"text-xs font-medium text-foreground",children:k==="autodb"?"Auto DB REST Endpoint":k==="external"?`Exter
7878nal DB: ${N==null?void 0:N.name}`:"Mock API (no live test)"}),a.jsx("p",{className:"text-[10px] text-muted-foreground font-mono truncate max-w-[300px]",children:k==="autodb"?S:k==="external"?w:"N/A"})]}),a.jsx("button",{onClick:v,disabled:y.status==="testing"||k==="mock",className:L("px-3 py-1.5 rounded-md text-xs font-medium transition-colors flex items-center gap-1.5",y.status==="testing"?"bg-muted text-muted-foreground cursor-wait":"bg-primary text-primary-foreground hover:bg-primary/90"),children:y.status==="testing"?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"})," Testing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(hr,{className:"w-3 h-3"})," Run Test"]})})]}),y.status==="success"&&a.jsxs("div",{className:"bg-green-500/10 border border-green-500/30 rounded-md p-3 space-y-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(mn,{className:"w-4 h-4 text-green-600"}),a.jsx("span",{className:"text-xs font-semibold text-green-700",children:"Connected & Working"})]}),a.jsx("p",{className:"text-[11px] text-green-700",children:y.message}),a.jsxs("div",{className:"flex gap-4 text-[10px] text-green-600",children:[a.jsxs("span",{children:["Latency: ",y.latency,"ms"]}),a.jsxs("span",{children:["Rows returned: ",y.rowCount]})]})]}),y.status==="error"&&a.jsxs("div",{className:"bg-destructive/10 border border-destructive/30 rounded-md p-3 space-y-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(aa,{className:"w-4 h-4 text-destructive"}),a.jsx("span",{className:"text-xs font-semibold text-destructive",children:"Connection Failed"})]}),a.jsx("p",{className:"text-[11px] text-destructive/80",children:y.message}),y.latency&&a.jsxs("span",{className:"text-[10px] text-destructive/60",children:["Response time: ",y.latency,"ms"]})]})]}),a.jsxs("div",{className:"border rounded-lg divide-y",children:[a.jsx("div",{className:"px-3 py-2 bg-secondary/30",children:a.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Available Data Sources"})}),a.jsxs("div",{className:"px-3 py-2 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Op,{className:"w-3.5 h-3.5 text-primary"}),a.jsx("span",{className:"text-xs",children:"Auto DB Tables"})]}),a.jsxs(Ge,{variant:T?"default":"secondary",className:"text-[10px]",children:[o.length," table",o.length!==1?"s":""]})]}),a.jsxs("div",{className:"px-3 py-2 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Hn,{className:"w-3.5 h-3.5 text-primary"}),a.jsx("span",{className:"text-xs",children:"External DBs"})]}),a.jsxs(Ge,{variant:s.length>0?"default":"secondary",className:"text-[10px]",children:[s.length," connection",s.length!==1?"s":""]})]}),a.jsxs("div",{className:"px-3 py-2 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Br,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-xs",children:"Mock APIs"})]}),a.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[u.length," endpoint",u.length!==1?"s":""]})]})]})]})}):h==="sdk"?a.jsx(dge,{tables:o,projectId:n||"",baseUrl:S}):a.jsx($r,{className:"flex-1",children:A?a.jsx(gge,{spec:A}):a.jsx("div",{className:"p-8 text-center text-muted-foreground text-sm",children:"Select a data source to see live APIs"})})]}):a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(Br,{className:"w-10 h-10 text-muted-foreground/40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No APIs available"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Create Auto DB tables or connect an external database to get live CRUD APIs"})]})}function gge({spec:e}){const[t,r]=m.useState(null),[n,s]=m.useState(null);return m.useEffect(()=>{Promise.all([ju(()=>import("./vendor-swagger-Bf7V8oR3.js").then(i=>i.O),__vite__mapDeps([3,2,4])),ju(()=>import("./vendor-swagger-Bf7V8oR3.js").then(i=>i.Q),__vite__mapDeps([3,2,4]))]).then(([i])=>r(()=>i.default)).catch(i=>{console.error("Failed to load SwaggerUI:",i),s(i.message)})},[]),n?a.jsxs("div",{className:"p-8 text-center space-y-2",children:[a.jsx(is,{className:"w-8 h-8 text-destructive mx-auto"}),a.jsx("p",{className:"text-sm text-destructive font-medium",children:"Failed to load API viewer"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:n})]}):t?a.jsxs("div",{className:"swagger-ui-wrapper",children:[a.jsx("style",{children:`
7879        .swagger-ui-wrapper .swagger-ui { font-family: inherit; }
7880        .swagger-ui-wrapper .swagger-ui .topbar { display: none; }
7881        .swagger-ui-wrapper .swagger-ui .info { margin: 12px 0; padding: 0 16px; }
7882        .swagger-ui-wrapper .swagger-ui .info .title { font-size: 16px; }
7883        .swagger-ui-wrapper .swagger-ui .scheme-container { display: none; }
7884        .swagger-ui-wrapper .swagger-ui .opblock-tag { font-size: 13px; border-bottom-color: hsl(var(--border)); padding: 8px 16px; }
7885        .swagger-ui-wrapper .swagger-ui .opblock { border-radius: 8px; margin: 4px 16px 8px; border: 1px solid hsl(var(--border)); box-shadow: none; }
7886        .swagger-ui-wrapper .swagger-ui .opblock .opblock-summary { border: none; padding: 8px 12px; }
7887        .swagger-ui-wrapper .swagger-ui .opblock .opblock-summary-method { font-size: 11px; border-radius: 4px; padding: 4px 10px; min-width: 60px; text-align: center; }
7888        .swagger-ui-wrapper .swagger-ui .opblock .opblock-summary-path { font-size: 12px; }
7889        .swagger-ui-wrapper .swagger-ui .btn { border-radius: 6px; font-size: 12px; }
7890        .swagger-ui-wrapper .swagger-ui .btn.execute { background: hsl(var(--primary)); border-color: hsl(var(--primary)); }
7891        .swagger-ui-wrapper .swagger-ui .btn.execute:hover { background: hsl(var(--primary) / 0.9); }
7892        .swagger-ui-wrapper .swagger-ui table tbody tr td { padding: 8px 0; }
7893        .swagger-ui-wrapper .swagger-ui .responses-wrapper { padding: 12px; }
7894        .swagger-ui-wrapper .swagger-ui .response-col_description { font-size: 12px; }
7895        .swagger-ui-wrapper .swagger-ui .parameter__name { font-size: 12px; }
7896        .swagger-ui-wrapper .swagger-ui .parameter__type { font-size: 11px; }
7897        .swagger-ui-wrapper .swagger-ui input[type=text] { border-radius: 6px; font-size: 12px; padding: 4px 8px; }
7898        .swagger-ui-wrapper .swagger-ui textarea { border-radius: 6px; font-size: 12px; }
7899        .swagger-ui-wrapper .swagger-ui .opblock-body pre { font-size: 11px; border-radius: 6px; }
7900        .swagger-ui-wrapper .swagger-ui .wrapper { padding: 0; }
7901      `}),a.jsx(t,{spec:e,docExpansion:"list",defaultModelsExpandDepth:-1,requestInterceptor:async i=>{try{const{data:{session:o}}=await G.auth.getSession();o!=null&&o.access_token&&(i.headers.Authorization=`Bearer ${o.access_token}`)}catch{const o="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo";i.headers.Authorization=`Bearer ${o}`}return i}})]}):a.jsx("div",{className:"p-8 text-center text-muted-foreground text-sm",children:"Loading API documentation..."})}const Ab=[{id:"postgresql",label:"PostgreSQL",icon:Hn,defaultPort:"5432",color:"bg-blue-500/15 text-blue-600 border-blue-500/30"},{id:"mysql",label:"MySQL",icon:sa,defaultPort:"3306",color:"bg-orange-500/15 text-orange-600 border-orange-500/30"},{id:"mongodb",label:"MongoDB",icon:fu,defaultPort:"27017",color:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"},{id:"sqlite",label:"SQLite",icon:Pw,defaultPort:"",color:"bg-cyan-500/15 text-cyan-600 border-cyan-500/30"}],o_={type:"postgresql",name:"",host:"localhost",port:"5432",database:"",username:"",password:"",ssl:!1};function l_({open:e,onOpenChange:t,onConnect:r,onTestConnection:n}){const[s,i]=m.useState(1),[o,l]=m.useState(o_),[c,u]=m.useState(!1),[d,p]=m.useState(!1),[h,f]=m.useState(null),[x,g]=m.useState(""),[y,b]=m.useState(null),[v,k]=m.useState(!1),N=Ab.find(A=>A.id===o.type),j=A=>{const P=Ab.find(E=>E.id===A);l(E=>({...E,type:A,port:P.defaultPort,name:E.name||`${P.label} Connection`})),i(2)},w=async()=>{u(!0);const A=await r(o);u(!1),A&&(b(A),i(3))},S=async()=>
7901{if(!(!y||!n)){p(!0),f(null),g("");try{const A=await n(y);f(A.success?"success":"error"),A.success||g(A.error||"Connection failed")}catch(A){f("error"),g(A.message||"Connection failed")}p(!1)}},T=()=>{i(1),l(o_),f(null),g(""),b(null),t(!1)},C=o.type==="sqlite"?!!(o.filePath||o.connectionString):o.type==="mongodb"&&o.connectionString?!!o.connectionString:!!(o.host&&o.port&&o.database&&o.username);return a.jsx(yo,{open:e,onOpenChange:T,children:a.jsxs(Fi,{className:"sm:max-w-md",children:[a.jsxs(Bi,{children:[a.jsxs(La,{className:"flex items-center gap-2",children:[a.jsx(Hn,{className:"w-5 h-5 text-primary"}),"Connect Database"]}),a.jsxs(ol,{children:[s===1&&"Choose your database type",s===2&&`Configure ${N.label} connection`,s===3&&"Test and finish"]})]}),a.jsx("div",{className:"flex items-center gap-1 px-1",children:[1,2,3].map(A=>a.jsx("div",{className:L("h-1 rounded-full flex-1 transition-colors",A<=s?"bg-primary":"bg-muted")},A))}),s===1&&a.jsx("div",{className:"grid grid-cols-2 gap-2",children:Ab.map(A=>a.jsxs("button",{onClick:()=>j(A.id),className:L("flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all hover:scale-[1.02]",o.type===A.id?`${A.color} border-current`:"border-border hover:border-primary/30 bg-card"),children:[a.jsx(A.icon,{className:"w-8 h-8"}),a.jsx("span",{className:"text-sm font-medium",children:A.label})]},A.id))}),s===2&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Connection Name"}),a.jsx(Cn,{value:o.name,onChange:A=>l(P=>({...P,name:A.target.value})),placeholder:"My Database",className:"mt-1 h-9 text-sm"})]}),o.type==="sqlite"?a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"LibSQL / Turso URL"}),a.jsx(Cn,{value:o.connectionString||o.filePath||"",onChange:A=>l(P=>({...P,connectionString:A.target.value,filePath:A.target.value})),placeholder:"libsql://your-db.turso.io",className:"mt-1 h-9 text-sm font-mono"}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"SQLite requires a remote URL (e.g., Turso/LibSQL)"})]}):o.type==="mongodb"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Connection String"}),a.jsx(Cn,{value:o.connectionString||"",onChange:A=>l(P=>({...P,connectionString:A.target.value})),placeholder:"mongodb+srv://user:[email protected]/db",className:"mt-1 h-9 text-sm font-mono"}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Or fill the fields below"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Host"}),a.jsx(Cn,{value:o.host,onChange:A=>l(P=>({...P,host:A.target.value})),className:"mt-1 h-9 text-sm"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Port"}),a.jsx(Cn,{value:o.port,onChange:A=>l(P=>({...P,port:A.target.value})),className:"mt-1 h-9 text-sm"})]})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Database"}),a.jsx(Cn,{value:o.database,onChange:A=>l(P=>({...P,database:A.target.value})),className:"mt-1 h-9 text-sm"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Username"}),a.jsx(Cn,{value:o.username,onChange:A=>l(P=>({...P,username:A.target.value})),className:"mt-1 h-9 text-sm"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Password"}),a.jsxs("div",{className:"relative mt-1",children:[a.jsx(Cn,{type:v?"text":"password",value:o.password,onChange:A=>l(P=>({...P,password:A.target.value})),className:"h-9 text-sm pr-9"}),a.jsx("button",{onClick:()=>k(!v),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:v?a.jsx(ku,{className:"w-3.5 h-3.5"}):a.jsx(ys,{className:"w-3.5 h-3.5"})})]})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[a.jsxs("div",{className:"col-span-2",children:[a.jsx($n,{className:"text-xs",children:"Host"}),a.jsx(Cn,{value:o.host,onChange:A=>l(P=>({...P,host:A.target.value})),className:"mt-1 h-9 text-sm",placeholder:"localhost"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Port"}),a.jsx(Cn,{value:o.port,onChange:A=>l(P=>({...P,port:A.target.value})),className:"mt-1 h-9 text-sm"})]})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Database"}),a.jsx(Cn,{value:o.database,onChange:A=>l(P=>({...P,database:A.target.value})),className:"mt-1 h-9 text-sm",placeholder:"mydb"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Username"}),a.jsx(Cn,{value:o.username,onChange:A=>l(P=>({...P,username:A.target.value})),className:"mt-1 h-9 text-sm"})]}),a.jsxs("div",{children:[a.jsx($n,{className:"text-xs",children:"Password"}),a.jsxs("div",{className:"relative mt-1",children:[a.jsx(Cn,{type:v?"text":"password",value:o.password,onChange:A=>l(P=>({...P,password:A.target.value})),className:"h-9 text-sm pr-9"}),a.jsx("button",{onClick:()=>k(!v),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:v?a.jsx(ku,{className:"w-3.5 h-3.5"}):a.jsx(ys,{className:"w-3.5 h-3.5"})})]})]})]}),a.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:o.ssl,onChange:A=>l(P=>({...P,ssl:A.target.checked})),className:"rounded border-border"}),"Use SSL"]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>i(1),className:"gap-1",children:[a.jsx(ei,{className:"w-3.5 h-3.5"})," Back"]}),a.jsx(Q,{size:"sm",onClick:w,disabled:!C||c,className:"gap-1 ml-auto",children:c?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"})," Saving..."]}):a.jsxs(a.Fragment,{children:["Save & Test ",a.jsx(Sh,{className:"w-3.5 h-3.5"})]})})]})]}),s===3&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"rounded-lg border bg-secondary/30 p-3 space-y-2 text-sm",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(N.icon,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"font-semibold",children:o.name}),a.jsx("span",{className:L("text-[10px] px-1.5 py-0.5 rounded font-semibold",N.color),children:N.label})]}),a.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground",children:o.type==="sqlite"?a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"URL"}),a.jsx("span",{className:"text-foreground font-mono text-[11px] truncate",children:o.connectionString||o.filePath})]}):o.type==="mongodb"&&o.connectionString?a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"URI"}),a.jsx("span",{className:"text-foreground font-mono text-[11px] truncate",children:o.connectionString.replace(/:([^@]+)@/,":***@")})]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"Host"}),a.jsxs("span",{className:"text-foreground font-mono",children:[o.host,":",o.port]}),a.jsx("span",{children:"Database"}),a.jsx("span",{className:"text-foreground",children:o.database}),a.jsx("span",{children:"User"}),a.jsx("span",{className:"text-foreground",children:o.username}),a.jsx("span",{children:"SSL"}),a.jsx("span",{className:"text-foreground",children:o.ssl?"Yes":"No"})]})})]}),a.jsx(Q,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:S,disabled:d,children:d?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"})," Testing..."]}):h==="success"?a.jsxs(a.Fragment,{children:[a.jsx(Wn,{className:"w-3.5 h-3.5 text-emerald-500"})," Connection Successful"]}):"Test Connection"}),h==="error"&&a.jsx("p",{className:"text-xs text-destructive",children:x||"Connection failed. Check your credentials."}),a.jsxs("div",{className:"flex gap-2 pt-1",children:[a.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>{i(2),f(null),b(null)},className:"gap-1",children:[a.jsx(ei,{className:"w-3.5 h-3.5"})," Back"]}),a.jsxs(Q,{size:"sm",onClick:T,className:"gap-1 ml-auto",children:[a.jsx(Wn,{className:"w-3.5 h-3.5"})," Done"]})]})]})]})})}function xge({type:e}){const t=e.replace(/\s*WITH\s+TIME\s+ZONE/i,"TZ"),r={UUID:"bg-purple-500/15 text-purple-600",TEXT:"bg-emerald-500/15 text-emerald-600",VARCHAR:"bg-emerald-500/15 text-emerald-600",INTEGER:"bg-blue-500/15 text-blue-600",INT:"bg-blue-500/15 text-blue-600",BIGINT:"bg-blue-500/15 text-blue-600",SERIAL:"bg-blue-500/15 text-blue-600",BOOLEAN:"bg-amber-500/15 text-amber-600",BOOL:"bg-amber-500/15 text-amber-600",TIMESTAMP:"bg-rose-500/15 text-rose-600",TIMESTAMPTZ:"bg-rose-500/15 text-rose-600",DATE:"bg-rose-500/15 text-rose-600",JSONB:"bg-cyan-500/15 text-cyan-600",JSON:"bg-cyan-500/15 text-cyan-600",NUMERIC:"bg-indigo-500/15 text-indigo-600",DECIMAL:"bg-indigo-500/15 text-indigo-600",FLOAT:"bg-indigo-500/15 text-indigo-600"},n=t.split("(")[0].split(" ")[0],s=r[n]||"bg-muted text-muted-foreground";return a.jsx("span",{className:L("px-1.5 py-0.5 rounded text-[10px] font-mono font-medium",s),children:t})}function yge({table:e,isExpanded:t,onToggle:r,relationships:n,source:s}){const i=n.filter(c=>c.fromTable===e.name||c.toTable===e.name),o=e.columns.filter(c=>c.isPrimaryKey).length,l=e.columns.filter(c=>c.isForeignKey).length;return a.jsxs("div",{className:L("border rounded-lg overflow-hidden transition-all",t?"border-primary/30 shadow-sm":"border-border hover:border-primary/20"),children:[a.jsxs("button",{onClick:r,className:"w-full flex items-center gap-2.5 px-3 py-2.5 text-left bg-secondary/30 hover:bg-secondary/50 transition-colors",children:[a.jsx(Di,{className:"w-4 h-4 text-primary shrink-0"}),a.jsx("span",{className:"text-sm font-semibold text-foreground flex-1",children:e.name}),s&&a.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-accent/10 text-accent font-medium",children:s}),a.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-muted-foreground",children:[a.jsxs("span",{children:[e.columns.length," cols"]}),o>0&&a.jsxs("span",{className:"flex items-center gap-0.5",children:[a.jsx(Ql,{className:"w-3 h-3 text-amber-500"}),o]}),l>0&&a.jsxs("span",{className:"flex items-center gap-0.5",children:[a.jsx(Yo,{className:"w-3 h-3 text-blue-500"}),l]})]})]}),t&&a.jsxs("div",{className:"divide-y divide-border/50",children:[e.columns.map((c,u)=>a.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-secondary/20 transition-colors",children:[a.jsx("span",{className:"w-4 flex justify-center shrink-0",children:c.isPrimaryKey?a.jsx(Ql,{className:"w-3.5 h-3.5 text-amber-500"}):c.isForeignKey?a.jsx(Yo,{className:"w-3.5 h-3.5 text-blue-500"}
7901):a.jsx(X$,{className:"w-3 h-3 text-muted-foreground/40"})}),a.jsx("span",{className:L("font-mono flex-1 truncate",c.isPrimaryKey?"font-semibold text-foreground":"text-foreground/80"),children:c.name}),a.jsx(xge,{type:c.type}),!c.isNullable&&a.jsx("span",{className:"text-[9px] text-rose-500/70 font-semibold",children:"NOT NULL"})]},u)),i.length>0&&a.jsxs("div",{className:"px-3 py-2 bg-secondary/20",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Relationships"}),a.jsx("div",{className:"mt-1 space-y-1",children:i.map(c=>{const u=c.fromTable===e.name;return a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[a.jsx(Yo,{className:"w-3 h-3 text-blue-500 shrink-0"}),a.jsx("span",{className:"font-mono",children:u?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-foreground/70",children:c.fromColumn})," → ",a.jsx("span",{className:"text-primary font-medium",children:c.toTable}),".",c.toColumn]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-primary font-medium",children:c.fromTable}),".",c.fromColumn," → ",a.jsx("span",{className:"text-foreground/70",children:c.toColumn})]})})]},c.id)})})]})]})]})}const bge={postgresql:Hn,mysql:sa,mongodb:fu,sqlite:Pw};function vge({conn:e,onIntrospect:t,onDelete:r,introspecting:n}){var i;const s=bge[e.db_type]||Hn;return a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-secondary/20 text-xs",children:[a.jsx(s,{className:"w-4 h-4 text-primary shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"font-medium text-foreground truncate block",children:e.name}),a.jsxs("span",{className:"text-muted-foreground text-[10px]",children:[e.db_type," • ",e.host||((i=e.connection_string)==null?void 0:i.slice(0,30))]})]}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:t,disabled:n,children:n?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(zr,{className:"w-3 h-3"})}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive hover:text-destructive",onClick:r,children:a.jsx(oa,{className:"w-3 h-3"})})]})}function wge(){const{schema:e,project:t}=gn(),[r,n]=m.useState(null),[s,i]=m.useState(""),[o,l]=m.useState(!1),[c,u]=m.useState(null),[d,p]=m.useState({}),h=(t==null?void 0:t.id)||null,{connections:f,loadConnections:x,addConnection:g,deleteConnection:y,testConnection:b,introspect:v}=Rh(h),{infra:k}=zh(h);m.useEffect(()=>{h&&x()},[h,x]),m.useEffect(()=>{var I;const _={};for(const D of f)D.cached_schema&&((I=D.cached_schema.tables)==null?void 0:I.length)>0&&(_[D.id]=D.cached_schema);Object.keys(_).length>0&&p(D=>({...D,..._}))},[f]);const N=m.useCallback(async _=>{const I=await g({name:_.name,db_type:_.type,host:_.host,port:_.port,database_name:_.database,username:_.username,password:_.password,connection_string:_.connectionString,ssl:_.ssl});if(!I)return W.error("Failed to save connection"),null;W.success("Connection saved");try{u(I.id);const D=await v(I.id);p(M=>({...M,[I.id]:D})),W.success(`Discovered ${D.tables.length} tables`)}catch(D){W.error(`Introspection failed: ${D.message}`)}finally{u(null)}return I.id},[g,v]),j=m.useCallback(async _=>b(_),[b]),w=m.useCallback(async _=>{u(_);try{const I=await v(_);p(D=>({...D,[_]:I})),W.success(`Refreshed: ${I.tables.length} tables found`)}catch(I){W.error(`Introspection failed: ${I.message}`)}finally{u(null)}},[v]),S=m.useCallback(async _=>{await y(_),p(I=>{const D={...I};return delete D[_],D}),W.success("Connection removed")},[y]),T=[],C=new Set;for(const _ of k.tables||[]){const I=Array.isArray(_.column_details)?_.column_details.map(D=>({name:D.name,type:D.type,nullable:!!D.nullable,isPrimaryKey:!!D.is_pk})):[];T.push({id:`live-${_.name}`,name:_.name,columns:I,filename:"Connected Supabase",source:"Live (Supabase)"}),C.add(_.name)}for(const _ of e.tables)C.has(_.name)||(T.push({..._,source:"AI Generated"}),C.add(_.name));const A=[...e.relationships];for(const[_,I]of Object.entries(d)){const D=f.find(B=>B.id===_),M=(D==null?void 0:D.name)||"External DB";for(const B of I.tables)T.push({id:`ext-${_}-${B.name}`,name:B.name,columns:B.columns,filename:M,source:M});for(const B of I.relationships)A.push({...B,type:"one-to-many"})}const P=T.filter(_=>
7901_.name.toLowerCase().includes(s.toLowerCase())||_.columns.some(I=>I.name.toLowerCase().includes(s.toLowerCase())));return!(T.length>0)&&f.length===0?a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(Hn,{className:"w-10 h-10 text-muted-foreground/40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No schema detected"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Database tables will appear here when the AI generates SQL or you connect an external database"}),a.jsxs(Q,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:()=>l(!0),children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," Connect Database"]}),a.jsx(l_,{open:o,onOpenChange:l,onConnect:N,onTestConnection:j})]}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(ja,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground"}),a.jsx("input",{type:"text",value:s,onChange:_=>i(_.target.value),placeholder:"Filter tables...",className:"w-full pl-8 pr-3 py-1.5 text-xs rounded-md border bg-secondary/50 placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"})]}),a.jsxs("span",{className:"text-[10px] text-muted-foreground font-medium shrink-0",children:[P.length," table",P.length!==1?"s":""]})]}),a.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-1.5 border-b shrink-0",children:[a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-primary/10 text-primary",children:[a.jsx(Di,{className:"w-3 h-3"})," ",T.length," tables"]}),A.length>0&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-600",children:[a.jsx(Yo,{className:"w-3 h-3"})," ",A.length," relationships"]}),f.length>0&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-accent/10 text-accent",children:[a.jsx(Hn,{className:"w-3 h-3"})," ",f.length," DB",f.length>1?"s":""]}),a.jsxs(Q,{variant:"ghost",size:"sm",className:"ml-auto h-6 text-[10px] gap-1 px-2",onClick:()=>l(!0),children:[a.jsx(Kr,{className:"w-3 h-3"})," Connect DB"]})]}),f.length>0&&a.jsx("div",{className:"px-3 py-2 space-y-1.5 border-b shrink-0",children:f.map(_=>a.jsx(vge,{conn:_,onIntrospect:()=>w(_.id),onDelete:()=>S(_.id),introspecting:c===_.id},_.id))}),a.jsx(l_,{open:o,onOpenChange:l,onConnect:N,onTestConnection:j}),a.jsx($r,{className:"flex-1",children:a.jsx("div",{className:"p-3 space-y-2",children:P.map(_=>a.jsx(yge,{table:_,isExpanded:r===_.id,onToggle:()=>n(r===_.id?null:_.id),relationships:A,source:_.source},_.id))})})]})}function jge(){const{project:e}=gn(),t=(e==null?void 0:e.id)||null,{connections:r,loadConnections:n,runQuery:s}=Rh(t),{infra:i}=zh(t),o=i.status==="provisioned"&&!!i.project_ref,[l,c]=m.useState(null),[u,d]=m.useState(""),[p,h]=m.useState(!1),[f,x]=m.useState(null),[g,y]=m.useState(null),b=m.useRef(null);m.useEffect(()=>{t&&n()},[t,n]),m.useEffect(()=>{r.length>0&&!l&&c(r[0].id)},[r,l]);const v=m.useCallback(async()=>{if(!(!l||!u.trim())){h(!0),y(null),x(null);try{const S=await s(l,u.trim());x(S)}catch(S){y(S.message||"Query failed")}finally{h(!1)}}},[l,u,s]),k=m.useCallback(async()=>{if(!(!t||!u.trim())){h(!0),y(null),x(null);try{const{data:{session:S}}=await G.auth.getSession();if(!S)throw new Error("Not authenticated");const T=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/run-byos-sql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S.access_token}`},body:JSON.stringify({projectId:t,query:u.trim()})}),C=await T.json();if(!T.ok||C.error)throw new Error(C.error||C.details||`Query failed (${T.status})`);x({rows:C.rows||[],rowCount:C.rowCount||0})}catch(S){y(S.message||"Query failed")}finally{h(!1)}}},[t,u]),N=S=>{(S.metaKey||S.ctrlKey)&&S.key==="Enter"&&(S.preventDefault(),v())},j=r.find(S=>S.id===l),w=f&&f.rows.length>0?Object.keys(f.rows[0]):[];return r.length===0&&!o?a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(Hn,{className:"w-10 h-10 text-muted-foreground
7901/40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No databases connected"}),a.jsxs("p",{className:"text-xs text-muted-foreground mt-1 text-center max-w-sm",children:["Connect Supabase via the ",a.jsx("strong",{children:"Cloud"})," tab (auto-provisions a project DB) or add a custom external DB in the ",a.jsx("strong",{children:"Schema"})," tab to run queries."]})]}):r.length===0&&o?a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsxs("div",{className:"px-2.5 py-1 rounded-md bg-secondary/50 text-xs font-medium flex items-center gap-1.5",children:[a.jsx(Hn,{className:"w-3 h-3"})," Connected database"]}),a.jsxs(Q,{size:"sm",onClick:k,disabled:!u.trim()||p,className:"h-7 gap-1.5 text-[11px] ml-auto",children:[p?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(Oi,{className:"w-3 h-3"}),"Run (⌘↵)"]})]}),a.jsx("textarea",{ref:b,value:u,onChange:S=>d(S.target.value),onKeyDown:S=>{(S.metaKey||S.ctrlKey)&&S.key==="Enter"&&(S.preventDefault(),k())},placeholder:"SELECT * FROM profiles LIMIT 10;",className:"px-4 py-3 text-xs font-mono bg-background border-b focus:outline-none resize-none min-h-[120px]"}),a.jsxs("div",{className:"flex-1 overflow-auto",children:[g&&a.jsx("div",{className:"m-3 p-3 rounded-lg border border-rose-500/30 bg-rose-500/5 text-[11px] text-rose-700 font-mono whitespace-pre-wrap break-all",children:g}),f&&f.rows.length===0&&!g&&a.jsx("div",{className:"p-6 text-center text-xs text-muted-foreground",children:"Query executed — 0 rows returned."}),f&&f.rows.length>0&&a.jsxs("table",{className:"w-full text-[11px] font-mono",children:[a.jsx("thead",{className:"bg-secondary/50 sticky top-0",children:a.jsx("tr",{children:Object.keys(f.rows[0]).map(S=>a.jsx("th",{className:"px-3 py-1.5 text-left font-semibold text-muted-foreground border-b",children:S},S))})}),a.jsx("tbody",{children:f.rows.map((S,T)=>a.jsx("tr",{className:"hover:bg-secondary/30",children:Object.keys(f.rows[0]).map(C=>a.jsx("td",{className:"px-3 py-1.5 border-b border-border/30 truncate max-w-xs",children:S[C]===null?a.jsx("span",{className:"text-muted-foreground italic",children:"null"}):String(S[C])},C))},T))})]})]})]}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:l||"",onChange:S=>c(S.target.value),className:"appearance-none bg-secondary/50 border rounded-md pl-2.5 pr-6 py-1.5 text-xs font-medium cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/30",children:r.map(S=>a.jsxs("option",{value:S.id,children:[S.name," (",S.db_type,")"]},S.id))}),a.jsx(Yr,{className:"absolute right-1.5 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground pointer-events-none"})]}),a.jsxs(Q,{size:"sm",className:"gap-1.5 h-7 text-xs",onClick:v,disabled:p||!u.trim(),children:[p?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(Oi,{className:"w-3 h-3"}),p?"Running...":"Run"]}),a.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto",children:"⌘+Enter to run"})]}),a.jsx("div",{className:"border-b shrink-0",children:a.jsx("textarea",{ref:b,value:u,onChange:S=>d(S.target.value),onKeyDown:N,placeholder:(j==null?void 0:j.db_type)==="mongodb"?'{"collection":"users","action":"find","filter":{}}':"SELECT * FROM users LIMIT 10;",className:"w-full h-28 px-3 py-2 text-xs font-mono bg-secondary/20 resize-none focus:outline-none placeholder:text-muted-foreground/60",spellCheck:!1})}),a.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[g&&a.jsxs("div",{className:"px-3 py-2 bg-destructive/10 border-b text-xs text-destructive flex items-center gap-2",children:[a.jsx(qn,{className:"w-3 h-3 shrink-0"}),g]}),f&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"px-3 py-1.5 border-b flex items-center gap-2 shrink-0 bg-secondary/20",children:[a.jsx(Di,{className:"w-3 h-3 text-muted-foreground"}),a.jsxs("span",{className:"text-[10px] text-muted-foreground font-medium",children:[f.rowCount," row",f.rowCount!==1?"s":""," returned"]})]}),a.jsx($r,{className:"flex-1",children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsx("tr",{className:"border-b bg-secondary/30",children:w.map(S=>a.jsx("th",{className:"px-3 py-2 text-left font-semibold text-foreground whitespace-nowrap",children:S},S))})}),a.jsx("tbody",{children:f.rows.map((S,T)=>a.jsx("tr",{className:"border-b hover:bg-secondary/20 transition-colors",children:w.map(C=>
7901a.jsx("td",{className:"px-3 py-1.5 text-foreground/80 whitespace-nowrap max-w-[300px] truncate font-mono",children:typeof S[C]=="object"?JSON.stringify(S[C]):String(S[C]??"")},C))},T))})]})})})]}),!f&&!g&&a.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:a.jsx("p",{className:"text-xs",children:"Write a query and press Run to see results"})})]})]})}function Nge(){const{schema:e,project:t}=gn(),{infra:r}=zh((t==null?void 0:t.id)||null),n=m.useMemo(()=>{var A;const S=[],T=new Set,C=[...e.relationships];for(const P of r.tables||[]){const E=Array.isArray(P.column_details)?P.column_details:[],_=E.map(I=>({name:I.name,type:I.type,nullable:!!I.nullable,isPrimaryKey:!!I.is_pk}));S.push({id:`live-${P.name}`,name:P.name,columns:_,filename:"Live (Supabase)"}),T.add(P.name);for(const I of E)I.is_fk&&((A=I.fk_target)!=null&&A.table)&&C.push({id:`live-fk-${P.name}-${I.name}`,fromTable:P.name,fromColumn:I.name,toTable:I.fk_target.table,toColumn:I.fk_target.column||"id",type:"one-to-many"})}for(const P of e.tables)T.has(P.name)||(S.push(P),T.add(P.name));return{tables:S,relationships:C}},[r.tables,e.tables,e.relationships]),s=m.useRef(null),[i,o]=m.useState({}),[l,c]=m.useState(null),[u,d]=m.useState({x:0,y:0}),[p,h]=m.useState(1),[f,x]=m.useState({x:0,y:0}),[g,y]=m.useState(!1),b=m.useRef({x:0,y:0});m.useEffect(()=>{if(n.tables.length===0)return;const S=Math.ceil(Math.sqrt(n.tables.length)),T=240,C=180,A=60,P=60,E={};n.tables.forEach((_,I)=>{const D=I%S,M=Math.floor(I/S);E[_.id]={x:40+D*(T+A),y:40+M*(C+P)}}),o(E)},[n.tables]);const v=m.useCallback((S,T)=>{S.stopPropagation();const C=i[T]||{x:0,y:0};c(T),d({x:S.clientX/p-C.x-f.x,y:S.clientY/p-C.y-f.y})},[i,p,f]),k=m.useCallback(S=>{l?o(T=>({...T,[l]:{x:S.clientX/p-u.x-f.x,y:S.clientY/p-u.y-f.y}})):g&&(x({x:f.x+(S.clientX-b.current.x)/p,y:f.y+(S.clientY-b.current.y)/p}),b.current={x:S.clientX,y:S.clientY})},[l,u,p,f,g]),N=m.useCallback(()=>{c(null),y(!1)},[]),j=m.useCallback(S=>{(S.target===s.current||S.target.dataset.canvas)&&(y(!0),b.current={x:S.clientX,y:S.clientY})},[]),w=m.useMemo(()=>n.relationships.map(S=>{const T=n.tables.find(D=>D.name===S.fromTable),C=n.tables.find(D=>D.name===S.toTable);if(!T||!C)return null;const A=i[T.id],P=i[C.id];if(!A||!P)return null;const E=220,_=40+(T.columns.length>5?5:T.columns.length)*22,I=40+(C.columns.length>5?5:C.columns.length)*22;return{id:S.id,x1:A.x+E,y1:A.y+_/2,x2:P.x,y2:P.y+I/2,label:`${S.fromColumn} → ${S.toColumn}`}}).filter(Boolean),[e,i]);return n.tables.length===0?a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(Hn,{className:"w-10 h-10 text-muted-foreground/40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No schema to visualize"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Generate SQL or connect a database to see the diagram"})]}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-1.5 flex items-center gap-1.5 shrink-0",children:[a.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>h(S=>Math.min(S+.15,2)),children:a.jsx(CT,{className:"w-3.5 h-3.5"})}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>h(S=>Math.max(S-.15,.3)),children:a.jsx(PT,{className:"w-3.5 h-3.5"})}),a.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:[Math.round(p*100),"%"]}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 ml-1",onClick:()=>{h(1),x({x:0,y:0})},children:a.jsx(xT,{className:"w-3.5 h-3.5"})}),a.jsxs("span",{className:"text-[10px] text-muted-foreground ml-auto",children:[n.tables.length," tables • Drag to move"]})]}),a.jsx("div",{ref:s,"data-canvas":"true",className:"flex-1 overflow-hidden relative bg-[radial-gradient(circle,hsl(var(--border))_1px,transparent_1px)] [background-size:20px_20px] cursor-grab",style:{cursor:g?"grabbing":l?"move":"grab"},onMouseDown:j,onMouseMove:k,onMouseUp:N,onMouseLeave:N,children:a.jsxs("div",{style:{transform:`scale(${p}) translate(${f.x}px, ${f.y}px)`,transformOrigin:"0 0"},className:"absolute inset-0",children:[a.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",style:{overflow:"visible"},children:[a.jsx("defs",{children:a.jsx("marker",{id:"arrowhead",markerWidth:"8",markerHeight:"6",refX:"8",refY:"3",orient:"auto",children:a.jsx("polygon",{points:"0 0, 8 3, 0 6",fill:"hsl(var(--primary))",opacity:"0.5"})})}),w.map(S=>{const T=(S.x1+S.x2)/2;return a.jsx("g",{children:a.jsx("path",{d:`M ${S.x1} ${S.y1} C ${T} ${S.y1}, ${T} ${S.y2}, ${S.x2} ${S.y2}`,fill:"none",stroke:"hsl(var(--primary))",strokeWidth:"1.5",strokeOpacity:"0.35",markerEnd:"url(#arrowhead)"})},S.id)})]}),n.tables.map(S=>{const T=i[S.id];if(!T)return null;const C=S.columns.slice(0,6),A=S.columns.length>6;return a.jsxs("div",{className:L("absolute w-[220px] rounded-lg border shadow-md bg-card select-none transition-shadow",l===S.id?"shadow-lg ring-2 ring-primary/30 z-10":"hover:shadow-lg"),style:{left:T.x,top:T.y},onMouseDown:P=>v(P,S.id),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-primary/5 rounded-t-lg border-b",children:[a.jsx(Hn,{className:"w-3.5 h-3.5 text-primary"}),a.jsx("span",{className:"text-xs font-bold text-foreground truncate",children:S.name})]}),a.jsxs("div",{className:"divide-y divide-border/50",children:[C.map((P,E)=>a.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 text-[11px]",children:[P.isPrimaryKey?a.jsx(Ql,{className:"w-3 h-3 text-amber-500 shrink-0"}):P.isForeignKey?a.jsx(Yo,{className:"w-3 h-3 text-blue-500 shrink-0"}):a.jsx("span",{className:"w-3 h-3 shrink-0"}
7901),a.jsx("span",{className:"font-mono text-foreground/80 flex-1 truncate",children:P.name}),a.jsx("span",{className:"text-[9px] text-muted-foreground font-mono",children:P.type.split("(")[0].split(" ")[0]})]},E)),A&&a.jsxs("div",{className:"px-3 py-1 text-[10px] text-muted-foreground text-center",children:["+",S.columns.length-6," more columns"]})]})]},S.id)})]})})]})}function kge(e){const[t,r]=m.useState([]),[n,s]=m.useState(!1),i=m.useCallback(async()=>{if(!e)return;s(!0);const{data:u}=await G.from("project_workflows").select("*").eq("project_id",e).order("updated_at",{ascending:!1});r(u||[]),s(!1)},[e]);m.useEffect(()=>{e&&i()},[e,i]);const o=m.useCallback(async(u,d)=>{if(!e)return null;if(d){const{data:p,error:h}=await G.from("project_workflows").update({name:u.name,description:u.description,definition:u}).eq("id",d).select().single();if(h)return console.error("Failed to update workflow:",h),null;const f=p;return r(x=>x.map(g=>g.id===d?f:g)),f}else{const{data:p,error:h}=await G.from("project_workflows").insert({project_id:e,name:u.name,description:u.description,definition:u}).select().single();if(h)return console.error("Failed to save workflow:",h),null;const f=p;return r(x=>[f,...x]),f}},[e]),l=m.useCallback(async u=>{await G.from("project_workflows").delete().eq("id",u),r(d=>d.filter(p=>p.id!==u))},[]),c=m.useCallback(async(u,d)=>{await G.from("project_workflows").update({is_active:d}).eq("id",u),r(p=>p.map(h=>h.id===u?{...h,is_active:d}:h))},[]);return{workflows:t,loading:n,loadWorkflows:i,saveWorkflow:o,deleteWorkflow:l,toggleActive:c}}function Sge(){const{project:e,currentWorkflow:t,setCurrentWorkflow:r,setActiveWorkspaceTab:n}=gn(),s=(e==null?void 0:e.id)||null,{workflows:i,loading:o,saveWorkflow:l,deleteWorkflow:c,toggleActive:u}=kge(s),{execution:d,run:p,cancel:h,reset:f}=SD(s),[x,g]=m.useState(null),y=async()=>{if(!t){W.error("No workflow to save. Generate one first using the AI chat.");return}const j=await l(t,x||void 0);j?(g(j.id),W.success(`Workflow "${j.name}" saved!`)):W.error("Failed to save workflow")},b=j=>{r(j.definition),g(j.id),W.success(`Loaded "${j.name}"`)},v=async j=>{await c(j.id),x===j.id&&g(null),W.success(`Deleted "${j.name}"`)},k=()=>{r(null),g(null)},N=j=>new Date(j).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx(mT,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs font-semibold flex-1",children:"Workflow Library"}),a.jsxs(Q,{size:"sm",variant:"ghost",className:"h-7 text-xs gap-1",onClick:k,children:[a.jsx(Kr,{className:"w-3 h-3"})," New"]}),a.jsxs(Q,{size:"sm",className:"h-7 text-xs gap-1",onClick:y,disabled:!t,children:[a.jsx(Kg,{className:"w-3 h-3"})," Save"]})]}),a.jsx($r,{className:"flex-1",children:a.jsxs("div",{className:"p-2 space-y-1.5",children:[i.length===0&&!o&&a.jsxs("div",{className:"text-center py-8",children:[a.jsx(Ri,{className:"w-8 h-8 text-muted-foreground/30 mx-auto mb-2"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"No saved workflows yet"}),a.jsx("p",{className:"text-[10px] text-muted-foreground/70 mt-1",children:"Generate a workflow with AI, then click Save"})]}),i.map(j=>{var w,S;return a.jsxs("div",{className:L("border rounded-lg p-3 cursor-pointer transition-all group hover:shadow-sm",x===j.id?"border-primary/30 bg-primary/5":"border-border hover:border-primary/20"),children:[a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("div",{className:L("w-7 h-7 rounded-md flex items-center justify-center shrink-0",j.is_active?"bg-emerald-500/10 text-emerald-600":"bg-muted text-muted-foreground"),children:a.jsx(hr,{className:"w-3.5 h-3.5"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:j.name}),j.description&&a.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5 line-clamp-2",children:j.description}),a.jsxs("div",{className:"flex items-center gap-2 mt-1.5 text-[10px] text-muted-foreground flex-wrap",children:[a.jsxs("span",{className:"font-mono text-amber-600/70",title:"Workflow ID",children:["W#",j.id.slice(0,6)]}),a.jsxs("span",{className:"flex items-center gap-0.5",children:[a.jsx(Lr,{className:"w-2.5 h-2.5"})," ",N(j.updated_at)]}),a.jsxs("span",{children:[((S=(w=j.definition)==null?void 0:w.steps)==null?void 0:S.length)||0," steps"]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-1 mt-2 pt-2 border-t opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsxs(Q,{size:"sm",variant:"ghost",className:"h-6 text-[10px] gap-1 flex-1",onClick:()=>b(j),children:[a.jsx(cc,{className:"w-3 h-3"})," Load"]}),a.jsxs(Q,{size:"sm",variant:"ghost",className:"h-6 text-[10px] gap-1 text-primary hover:text-primary",onClick:()=>{r(j.definition),g(j.id),n("preview"),p(j.definition),W.info(`Running "${j.name}"...`)},children:[a.jsx(Es,{className:"w-3 h-3"})," Run"]}),a.jsxs(Q,{size:"sm",variant:"ghost",className:L("h-6 text-[10px] gap-1",j.is_active?"text-emerald-600":""),onClick:()=>u(j.id,!j.is_active),children:[j.is_active?a.jsx(vT,{className:"w-3 h-3"}):a.jsx(Oi,{className:"w-3 h-3"}),j.is_active?"Disable":"Enable"]}),a.jsx(Q,{size:"sm",variant:"ghost",className:"h-6 text-[10px] gap-1 text-destructive hover:text-destructive",onClick:()=>v(j),children:a.jsx(oa,{className:"w-3 h-3"})})]})]},j.id)})]})})]})}function Cge({onAdd:e,onCancel:t}){const[r,n]=m.useState(""),[s,i]=m.useState(""),[o,l]=m.useState("none"),[c,u]=m.useState("");return a.jsxs("div",{className:"border rounded-lg p-3 bg-secondary/30 space-y-2.5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Add MCP Server"}),a.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:a.jsx(qn,{
7901className:"w-3.5 h-3.5"})})]}),a.jsx("input",{value:r,onChange:d=>n(d.target.value),placeholder:"Server name (e.g. n8n Production)",className:"w-full text-xs bg-background border rounded-md px-2.5 py-1.5 placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"}),a.jsx("input",{value:s,onChange:d=>i(d.target.value),placeholder:"MCP endpoint URL (e.g. https://my-n8n.cloud/mcp-server/http)",className:"w-full text-xs bg-background border rounded-md px-2.5 py-1.5 font-mono placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:o,onChange:d=>l(d.target.value),className:"text-xs bg-background border rounded-md px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-primary/30",children:[a.jsx("option",{value:"none",children:"No Auth"}),a.jsx("option",{value:"bearer",children:"Bearer Token"}),a.jsx("option",{value:"api-key",children:"API Key"})]}),o!=="none"&&a.jsx("input",{value:c,onChange:d=>u(d.target.value),placeholder:o==="bearer"?"Bearer token...":"API key...",type:"password",className:"flex-1 text-xs bg-background border rounded-md px-2.5 py-1.5 font-mono placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"})]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Q,{size:"sm",className:"h-7 text-xs gap-1 flex-1",onClick:()=>e(r,s,o,c),disabled:!r.trim()||!s.trim(),children:[a.jsx(Kr,{className:"w-3 h-3"})," Connect"]})})]})}function Pge({tool:e}){var n;const[t,r]=m.useState(!1);return a.jsxs("div",{className:"border rounded-md p-2 bg-background/50",children:[a.jsxs("button",{onClick:()=>r(!t),className:"w-full flex items-center gap-2 text-left",children:[a.jsx(al,{className:"w-3 h-3 text-primary shrink-0"}),a.jsx("span",{className:"text-[11px] font-medium text-foreground flex-1 truncate",children:e.name}),a.jsx(Yr,{className:L("w-3 h-3 text-muted-foreground transition-transform",t&&"rotate-180")})]}),t&&a.jsxs("div",{className:"mt-1.5 pl-5",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground leading-relaxed",children:e.description}),((n=e.inputSchema)==null?void 0:n.properties)&&a.jsx("div",{className:"mt-1.5 space-y-0.5",children:Object.entries(e.inputSchema.properties).map(([s,i])=>{var o;return a.jsxs("div",{className:"text-[10px] font-mono flex gap-1",children:[a.jsx("span",{className:"text-primary/70",children:s}),a.jsxs("span",{className:"text-muted-foreground",children:[": ",i.type]}),((o=e.inputSchema.required)==null?void 0:o.includes(s))&&a.jsx("span",{className:"text-destructive",children:"*"})]},s)})})]})]})}function Age(){const{project:e}=gn(),t=(e==null?void 0:e.id)||null,{connections:r,loading:n,addConnection:s,deleteConnection:i,discoverTools:o}=z1(t),[l,c]=m.useState(!1),[u,d]=m.useState(null),p=async(f,x,g,y)=>{const b=await s({name:f,url:x,auth_type:g,auth_token:y});if(b){c(!1),W.success(`Connected to "${f}"`),d(b.id);try{const v=await o(b);W.success(`Discovered ${v.length} tools from "${f}"`)}catch(v){W.error(`Tool discovery failed: ${v.message}`)}finally{d(null)}}},h=async f=>{d(f.id);try{const x=await o(f);W.success(`Refreshed: ${x.length} tools from "${f.name}"`)}catch(x){W.error(`Failed to refresh: ${x.message}`)}finally{d(null)}};return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx(Ma,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs font-semibold flex-1",children:"MCP Servers"}),a.jsxs(Q,{size:"sm",variant:"ghost",className:"h-7 text-xs gap-1",onClick:()=>c(!l),children:[a.jsx(Kr,{className:"w-3 h-3"})," Add"]})]}),a.jsx($r,{className:"flex-1",children:a.jsxs("div",{className:"p-2 space-y-2",children:[l&&a.jsx(Cge,{onAdd:p,onCancel:()=>c(!1)}),r.length===0&&!l&&!n&&a.jsxs("div",{className:"text-center py-8",children:[a.jsx(sa,{className:"w-8 h-8 text-muted-foreground/30 mx-auto mb-2"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"No MCP servers connected"}
7901),a.jsx("p",{className:"text-[10px] text-muted-foreground/70 mt-1",children:"Connect to external MCP servers like n8n to extend AI capabilities"})]}),r.map(f=>a.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 bg-secondary/30",children:[a.jsx("div",{className:L("w-5 h-5 rounded-full flex items-center justify-center",f.last_connected_at?"bg-emerald-500/10 text-emerald-600":"bg-muted text-muted-foreground"),children:f.last_connected_at?a.jsx(mn,{className:"w-3 h-3"}):a.jsx(is,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:f.name}),a.jsx("p",{className:"text-[10px] text-muted-foreground font-mono truncate",children:f.url})]}),a.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[a.jsx(Q,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:()=>h(f),disabled:u===f.id,children:u===f.id?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(zr,{className:"w-3 h-3"})}),a.jsx(Q,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive hover:text-destructive",onClick:()=>i(f.id),children:a.jsx(oa,{className:"w-3 h-3"})})]})]}),f.cached_tools&&f.cached_tools.length>0&&a.jsxs("div",{className:"px-2 py-1.5 space-y-1 border-t",children:[a.jsxs("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider px-1",children:[f.cached_tools.length," Tools Available"]}),f.cached_tools.map(x=>a.jsx(Pge,{tool:x},x.name))]})]},f.id))]})})]})}function _ge({open:e,onOpenChange:t,projectId:r,currentConfig:n,onSaved:s}){const[i,o]=m.useState({url:(n==null?void 0:n.url)||"",anonKey:(n==null?void 0:n.anonKey)||"",serviceKey:(n==null?void 0:n.serviceKey)||""}),[l,c]=m.useState(!1),[u,d]=m.useState(null),[p,h]=m.useState(!1),[f,x]=m.useState("idle"),g=!!(n!=null&&n.url&&(n!=null&&n.anonKey)),y=!!(i.url.trim()&&i.anonKey.trim()),b=async()=>{if(!i.url.trim()||!i.anonKey.trim()){W.error("URL and Anon Key are required");return}c(!0),d(null);try{const j=i.url.replace(/\/$/,"");if(!(await fetch(`${j}/rest/v1/rpc/`,{method:"HEAD",headers:{apikey:i.anonKey,Authorization:`Bearer ${i.anonKey}`}})).ok){const S=await fetch(`${j}/rest/v1/__test_connection?limit=0`,{headers:{apikey:i.anonKey,Authorization:`Bearer ${i.anonKey}`}});if(S.status===401||S.status===403){d("error"),W.error("Authentication failed — check your Publishable Key");return}}d("success"),W.success("Connection successful!")}catch(j){d("error"),W.error("Connection failed: "+j.message)}finally{c(!1)}},v=async(j,w)=>{const S=`
7902CREATE OR REPLACE FUNCTION public.exec_sql(sql_text text)
7903RETURNS jsonb
7904LANGUAGE plpgsql
7905SECURITY DEFINER
7906SET search_path TO 'public'
7907AS $$
7908DECLARE result JSONB;
7909BEGIN
7910  EXECUTE sql_text;
7911  RETURN '{"success": true}'::JSONB;
7912EXCEPTION WHEN OTHERS THEN
7913  RETURN jsonb_build_object('error', SQLERRM);
7914END;
7915$$;
7916    `.trim();try{return(await fetch(`${j.replace(/\/$/,"")}/rest/v1/rpc/exec_sql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,apikey:w},body:JSON.stringify({sql_text:"SELECT 1"})})).ok?!0:!(await fetch(`${j.replace(/\/$/,"")}/rest/v1/rpc/exec_sql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,apikey:w},body:JSON.stringify({sql_text:S})})).ok&&!(await fetch(`${j.replace(/\/$/,"")}/pg/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,apikey:w},body:JSON.stringify({query:S})})).ok?(console.warn("Auto-setup: pg/query failed, function may need manual creation"),!1):!0}catch(T){return console.warn("Auto-setup exec_sql failed:",T),!1}},k=async()=>{h(!0);try{if(i.url.trim()&&i.serviceKey.trim()){x("running");const w=await v(i.url.trim(),i.serviceKey.trim());x(w?"done":"failed"),w||W.warning("Auto-setup: exec_sql function could not be created automatically. You may need to create it manually in your Supabase SQL editor.")}const{error:j}=await G.from("projects").update({custom_supabase_url:i.url.trim()||null,custom_supabase_anon_key:i.anonKey.trim()||null,custom_supabase_service_key:i.serviceKey.trim()||null}).eq("id",r);
7916if(j)throw j;W.success(i.url.trim()?"BYOS configuration saved!":"Switched back to managed database"),s(),t(!1)}catch(j){W.error("Failed to save: "+j.message)}finally{h(!1),x("idle")}},N=async()=>{o({url:"",anonKey:"",serviceKey:""}),h(!0);try{const{error:j}=await G.from("projects").update({custom_supabase_url:null,custom_supabase_anon_key:null,custom_supabase_service_key:null}).eq("id",r);if(j)throw j;W.success("Disconnected — using managed database"),s(),t(!1)}catch(j){W.error("Failed: "+j.message)}finally{h(!1)}};return a.jsx(yo,{open:e,onOpenChange:t,children:a.jsxs(Fi,{className:"max-w-lg",children:[a.jsxs(Bi,{children:[a.jsxs(La,{className:"flex items-center gap-2",children:[a.jsx(sa,{className:"w-4 h-4 text-primary"}),"Bring Your Own Supabase"]}),a.jsx(ol,{className:"text-xs",children:"Connect your own Supabase project to store all Auto DB tables there instead of the managed database."})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:L("flex items-center gap-2 rounded-lg px-3 py-2 text-xs",g?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:g?a.jsxs(a.Fragment,{children:[a.jsx(Wn,{className:"w-3.5 h-3.5"}),"Connected to custom Supabase"]}):a.jsxs(a.Fragment,{children:[a.jsx(os,{className:"w-3.5 h-3.5"}),"Using managed database (default)"]})}),a.jsxs("div",{children:[a.jsxs("label",{className:"text-xs font-medium text-foreground mb-1 flex items-center gap-1.5",children:[a.jsx(Is,{className:"w-3 h-3 text-muted-foreground"}),"Supabase Project URL"]}),a.jsx(Cn,{value:i.url,onChange:j=>{o(w=>({...w,url:j.target.value})),d(null)},placeholder:"https://your-project.supabase.co",className:"text-xs font-mono"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"text-xs font-medium text-foreground mb-1 flex items-center gap-1.5",children:[a.jsx(Ql,{className:"w-3 h-3 text-muted-foreground"}),"Anon / Publishable Key"]}),a.jsx(Cn,{value:i.anonKey,onChange:j=>{o(w=>({...w,anonKey:j.target.value})),d(null)},placeholder:"eyJhbGciOiJIUzI1NiIs...",className:"text-xs font-mono",type:"password"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"text-xs font-medium text-foreground mb-1 flex items-center gap-1.5",children:[a.jsx(os,{className:"w-3 h-3 text-muted-foreground"}),"Service Role Key ",a.jsx("span",{className:"text-muted-foreground font-normal",children:"(required for DDL)"})]}),a.jsx(Cn,{value:i.serviceKey,onChange:j=>o(w=>({...w,serviceKey:j.target.value})),placeholder:"eyJhbGciOiJIUzI1NiIs...",className:"text-xs font-mono",type:"password"}),a.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1 flex items-start gap-1",children:[a.jsx(Ar,{className:"w-3 h-3 shrink-0 mt-0.5"}),"Service key has full database access. It's stored encrypted and only used server-side for table operations."]})]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:b,disabled:!y||l,children:[l?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):u==="success"?a.jsx(Wn,{className:"w-3 h-3 text-green-500"}):u==="error"?a.jsx(qn,{className:"w-3 h-3 text-destructive"}):a.jsx(sa,{className:"w-3 h-3"}),l?"Testing...":u==="success"?"Connection OK":u==="error"?"Test Failed — Retry":"Test Connection"]})]}),a.jsxs(Ch,{className:"gap-2 sm:gap-0",children:[g&&a.jsx(Q,{variant:"destructive",size:"sm",onClick:N,disabled:p,className:"mr-auto text-xs",children:"Disconnect"}),a.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),a.jsxs(Q,{size:"sm",onClick:k,disabled:p,className:"gap-1.5",children:[p?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(Wn,{className:"w-3 h-3"}),p&&f==="running"?"Setting up DB...":p?"Saving...":"Save & Setup"]})]})]})})}const Tge=[{value:"text",label:"Text"},{value:"integer",label:"Integer"},{value:"float",label:"Float"},{value:"boolean",label:"Boolean"},{value:"uuid",label:"UUID"},{value:"timestamp",label:"Timestamp"},{value:"jsonb",label:"JSON"},{value:"date",label:"Date"}],Ege=[{id:"us-east-1",label:"🇺🇸 US East",city:"Virginia"},{id:"us-west-1",label:"🇺🇸 US West",city:"Oregon"},{id:"eu-central-1",label:"🇪🇺 Europe",city:"Frankfurt"},{id:"ap-southeast-1",label:"🇸🇬 Asia",city:"Singapore"},{id:"ap-northeast-1",label:"🇯🇵 Japan",city:"Tokyo"}];function Ige({open:e,onOpenChange:t,onSubmit:r,creating:n}){const[s,i]=m.useState(""),[o,l]=m.useState("us-east-1"),[c,u]=m.useState([{name:"",type:"text",nullable:!0}]),d=()=>u([...c,{name:"",type:"text",nullable:!0}]),p=x=>u(c.filter((g,y)=>y!==x)),h=(x,g,y)=>{u(c.map((b,v)=>v===x?{...b,[g]:y}:b))},f=()=>{const x=c.filter(g=>g.name.trim());if(!s.trim()||x.length===0){W.error("Table name and at least one column required");return}r(s.trim(),x,o)};return a.jsx(yo,{open:e,onOpenChange:t,children:a.jsxs(Fi,{className:"max-w-lg",children:[a.jsx(Bi,{children:a.jsxs(La,{className:"flex items-center gap-2",children:[a.jsx(Hn,{className:"w-4 h-4 text-primary"})," Create Table"]})}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-1 block",children:"Table Name"}),a.jsx(Cn,{value:s,onChange:x=>i(x.target.value.replace(/[^a-zA-Z0-9_]/g,"")),placeholder:"e.g. users, orders, products",className:"text-sm"}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Letters, numbers, underscores only. Auto-adds id, created_at, updated_at."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-2 block",children:"Region"}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ege.map(x=>a.jsx("button",{onClick:()=>l(x.id),className:L("px-2.5 py-1 rounded-md text-[11px] font-medium transition-all border",o===x.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:border-primary/30"),children:x.label},x.id))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-2 block",children:"Columns"}),a.jsx("div",{className:"space-y-2",children:c.map((x,g)=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Cn,{value:x.name,onChange:y=>h(g,"name",y.target.value.replace(/[^a-zA-Z0-9_]/g,"")),placeholder:"column_name",className:"text-xs flex-1 font-mono"}),a.jsxs(Ns,{value:x.type,onValueChange:y=>h(g,"type",y),children:[a.jsx(hs,{className:"w-28 text-xs",children:a.jsx(ks,{})}),a.jsx(fs,{children:Tge.map(y=>a.jsx(Dt,{value:y.value,className:"text-xs",children:y.label},y.value))})]}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive",onClick:()=>
7916p(g),disabled:c.length<=1,children:a.jsx(qn,{className:"w-3 h-3"})})]},g))}),a.jsxs(Q,{variant:"ghost",size:"sm",className:"mt-2 text-xs gap-1",onClick:d,children:[a.jsx(q$,{className:"w-3 h-3"})," Add Column"]})]})]}),a.jsxs(Ch,{children:[a.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),a.jsxs(Q,{size:"sm",onClick:f,disabled:n,className:"gap-1.5",children:[n?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(Kr,{className:"w-3 h-3"}),n?"Creating...":"Create Table"]})]})]})})}function Oge({table:e,onClose:t}){const{project:r}=gn(),{selectRows:n,insertRow:s,deleteRows:i}=mx((r==null?void 0:r.id)||null),[o,l]=m.useState([]),[c,u]=m.useState(!0),d=e.display_name,p=e.columns.filter(y=>!["id","created_at","updated_at"].includes(y.name)),h=m.useCallback(async()=>{u(!0);try{const y=await n(d,{limit:100});l(y.data||[])}catch(y){W.error(`Failed to load data: ${y.message}`)}finally{u(!1)}},[d,n]);m.useEffect(()=>{h()},[h]);const f=async()=>{const y={};for(const b of p)b.type.includes("TEXT")?y[b.name]=`sample_${Date.now()}`:b.type.includes("INTEGER")||b.type.includes("NUMERIC")?y[b.name]=0:b.type.includes("BOOLEAN")&&(y[b.name]=!1);try{await s(d,y),W.success("Row inserted"),h()}catch(b){W.error(b.message)}},x=async y=>{try{await i(d,{id:y}),W.success("Row deleted"),h()}catch(b){W.error(b.message)}},g=e.columns;return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:t,children:"← Back"}),a.jsx(Di,{className:"w-3.5 h-3.5 text-primary"}),a.jsx("span",{className:"text-xs font-semibold",children:d}),a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[o.length," rows"]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"ml-auto h-6 text-[10px] gap-1",onClick:f,children:[a.jsx(Kr,{className:"w-3 h-3"})," Insert Row"]})]}),c?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsx(ze,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):o.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground",children:[a.jsx("p",{className:"text-xs",children:"No data yet"}),a.jsxs(Q,{variant:"outline",size:"sm",className:"mt-2 text-xs gap-1",onClick:f,children:[a.jsx(Kr,{className:"w-3 h-3"})," Insert Sample Row"]})]}):a.jsx($r,{className:"flex-1",children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b bg-secondary/30",children:[g.map(y=>a.jsx("th",{className:"px-3 py-2 text-left font-semibold whitespace-nowrap",children:y.name},y.name)),a.jsx("th",{className:"px-2 py-2 w-8"})]})}),a.jsx("tbody",{children:o.map((y,b)=>a.jsxs("tr",{className:"border-b hover:bg-secondary/20 transition-colors",children:[g.map(v=>a.jsx("td",{className:"px-3 py-1.5 font-mono max-w-[200px] truncate",children:typeof y[v.name]=="object"?JSON.stringify(y[v.name]):String(y[v.name]??"")},v.name)),a.jsx("td",{className:"px-2 py-1.5",children:a.jsx(Q,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-destructive",onClick:()=>x(y.id),children:a.jsx(oa,{className:"w-3 h-3"})})})]},b))})]})})})]})}function Rge(){const{project:e,activeWorkspaceTab:t}=gn(),r=(e==null?void 0:e.id)||null,{tables:n,loading:s,loadTables:i,createTable:o,dropTable:l}=mx(r);m.useEffect(()=>{t==="autodb"&&r&&i()},[t,r,i]);const[c,u]=m.useState(!1),[d,p]=m.useState(!1),[h,f]=m.useState(null),[x,g]=m.useState(!1),[y,b]=m.useState({}),v=m.useRef(0);m.useEffect(()=>{r&&(i(),v.current=Date.now(),G.from("projects").select("custom_supabase_url, custom_supabase_anon_key, custom_supabase_service_key").eq("id",r).single().then(({data:w})=>{w&&b({url:w.custom_supabase_url,anonKey:w.custom_supabase_anon_key,serviceKey:w.custom_supabase_service_key})}))},[r,i]),m.useEffect(()=>{if(!r)return;const w=()=>{!document.hidden&&Date.now()-v.current>3e3&&(i(),v.current=Date.now())};document.addEventListener("visibilitychange",w);const S=setInterval(()=>{Date.now()-v.current>1e4&&(i(),v.current=Date.now())},1e4);return()=>{document.removeEventListener("visibilitychange",w),clearInterval(S)}},[r,i]);const k=async(w,S,T)=>{p(!0);try{await o({tableName:w,displayName:w,columns:S.map(C=>({name:C.name,type:C.type,nullable:C.nullable}))}),W.success(`Table "${w}" created`),u(!1)}catch(C){W.error(C.message)}finally{p(!1)}},N=async w=>{if(confirm(`Delete table "${w.display_name}"? This cannot be undone.`))try{await l(w.display_name),W.success(`Table "${w.display_name}" dropped`)}catch(S){W.error(S.message)}},j=!!(y.url&&y.anonKey);return h?a.jsx(Oge,{table:h,onClose:()=>f(null)}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"border-b px-3 py-2 flex items-center gap-2 shrink-0",children:[a.jsx(Hn,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Auto DB"}),j&&a.jsx("span",{className:"text-[9px] font-semibold text-primary bg-primary/10 px-1.5 py-0.5 rounded",children:"BYOS"}),a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[n.length," table",n.length!==1?"s":""]}),a.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[j?a.jsxs(Q,{variant:"ghost",size:"sm",className:"h-6 text-[10px] gap-1 text-primary",onClick:()=>g(!0),title:"Connected to your Supabase — click to manage",children:[a.jsx(Wn,{className:"w-3 h-3"}),a.jsx("span",{className:"max-w-[100px] truncate",children:new URL(y.url).hostname.split(".")[0]}),a.jsx(ni,{className:"w-3 h-3 text-muted-foreground"})]}):a.jsxs(Q,{variant:"ghost",size:"sm",className:"h-6 text-[10px] gap-1",onClick:()=>g(!0),title:"Bring Your Own Supabase",children:[a.jsx(sa,{className:"w-3.5 h-3.5"}),"BYOS"]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"h-6 text-[10px] gap-1",onClick:()=>u(!0),children:[a.jsx(Kr,{className:"w-3 h-3"})," New Table"]})]})]}),s?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsx(ze,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):n.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(Hn,{className:"w-10 h-10 text-muted-foreground
7916/40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No tables yet"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Create your first table to start storing data. Each project gets its own isolated database."}),a.jsxs(Q,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:()=>u(!0),children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," Create Table"]})]}):a.jsx($r,{className:"flex-1",children:a.jsx("div",{className:"p-3 space-y-2",children:n.map(w=>a.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[a.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-2.5 bg-secondary/30 hover:bg-secondary/50 transition-colors",children:[a.jsx(Di,{className:"w-4 h-4 text-primary shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-sm font-semibold text-foreground block",children:w.display_name}),a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[w.columns.length," columns • RLS ",w.rls_enabled?"on":"off"]})]}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>f(w),children:a.jsx(ys,{className:"w-3 h-3"})}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive hover:text-destructive",onClick:()=>N(w),children:a.jsx(oa,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"divide-y divide-border/50",children:w.columns.map((S,T)=>a.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 text-xs",children:[a.jsx(uT,{className:"w-3 h-3 text-muted-foreground/40 shrink-0"}),a.jsx("span",{className:L("font-mono flex-1 truncate",S.is_primary&&"font-semibold"),children:S.name}),a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-secondary text-muted-foreground font-mono",children:S.type})]},T))})]},w.id))})}),a.jsx(Ige,{open:c,onOpenChange:u,onSubmit:k,creating:d}),r&&a.jsx(_ge,{open:x,onOpenChange:g,projectId:r,currentConfig:y,onSaved:()=>{G.from("projects").select("custom_supabase_url, custom_supabase_anon_key, custom_supabase_service_key").eq("id",r).single().then(({data:w})=>{w&&b({url:w.custom_supabase_url,anonKey:w.custom_supabase_anon_key,serviceKey:w.custom_supabase_service_key})})}})]})}const Dge={github:to,vercel:ya,cloud:ya,netlify:ya,docker:ya},Mge={success:{icon:mn,cls:"text-emerald-600 bg-emerald-500/10",label:"Success"},failed:{icon:aa,cls:"text-rose-600 bg-rose-500/10",label:"Failed"},pending:{icon:Lr,cls:"text-amber-600 bg-amber-500/10 animate-pulse",label:"Pending"}};function Lge({projectId:e,className:t}){const[r,n]=m.useState([]),[s,i]=m.useState(!1),o=m.useCallback(async()=>{if(!e){n([]);return}i(!0);const{data:l,error:c}=await G.from("project_deployments").select("id, target, status, commit_sha, branch, pr_number, pr_url, deploy_url, error_message, metadata, created_at, updated_at").eq("project_id",e).order("created_at",{ascending:!1}).limit(50);!c&&l&&n(l),i(!1)},[e]);return m.useEffect(()=>{if(o(),!e)return;const l=setInterval(o,15e3);return()=>clearInterval(l)},[e,o]),e?a.jsxs("div",{className:L("rounded-xl border bg-card",t),children:[a.jsxs("div",{className:"px-4 py-2.5 border-b flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-semibold",children:"Deployments"}),a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[r.length," total"]})]}),a.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 px-2 gap-1",onClick:o,disabled:s,children:[a.jsx(zr,{className:L("w-3 h-3",s&&"animate-spin")}),a.jsx("span",{className:"text-[11px]",children:"Refresh"})]})]}),a.jsx("div",{className:"max-h-[420px] overflow-y-auto divide-y",children:r.length===0?a.jsx("div",{className:"px-4 py-8 text-center text-xs text-muted-foreground",children:"No deployments yet. Push to GitHub or publish to Cloud to see entries here."}):r.map(l=>{const c=Dge[l.target]||ya,u=Mge[l.status],d=u.icon;return a.jsxs("div",{className:"px-4 py-3 flex items-start gap-3",children:[a.jsx("div",{className:"shrink-0 w-8 h-8 rounded-lg bg-muted flex items-center justify-center",children:a.jsx(c,{className:"w-4 h-4 text-foreground
7916/70"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("span",{className:"text-xs font-semibold capitalize",children:l.target}),l.branch&&a.jsx("code",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono",children:l.branch}),l.commit_sha&&a.jsx("code",{className:"text-[10px] text-muted-foreground font-mono",children:l.commit_sha.slice(0,7)}),a.jsxs("span",{className:L("inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium",u.cls),children:[a.jsx(d,{className:"w-2.5 h-2.5"}),u.label]}),a.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto",children:$s(new Date(l.created_at),{addSuffix:!0})})]}),a.jsxs("div",{className:"mt-1.5 flex items-center gap-3 flex-wrap",children:[l.deploy_url&&a.jsxs("a",{href:l.deploy_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-primary hover:underline",children:[a.jsx(Is,{className:"w-3 h-3"}),"View commit"]}),l.pr_url&&a.jsxs("a",{href:l.pr_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-primary hover:underline",children:[a.jsx(T$,{className:"w-3 h-3"}),"PR #",l.pr_number]})]}),l.error_message&&a.jsx("p",{className:"mt-1.5 text-[11px] text-rose-600 bg-rose-500/5 rounded px-2 py-1 line-clamp-2",children:l.error_message})]})]},l.id)})})]}):a.jsx("div",{className:L("p-4 rounded-xl border bg-muted/20 text-center",t),children:a.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a project to view its deployment history."})})}var RD="AlertDialog",[$ge,Ive]=sl(RD,[s5]),jo=s5(),DD=e=>{const{__scopeAlertDialog:t,...r}=e,n=jo(t);return a.jsx(v5,{...n,...r,modal:!0})};DD.displayName=RD;var Fge="AlertDialogTrigger",Bge=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=jo(r);return a.jsx(mB,{...s,...n,ref:t})});Bge.displayName=Fge;var Uge="AlertDialogPortal",MD=e=>{const{__scopeAlertDialog:t,...r}=e,n=jo(t);return a.jsx(w5,{...n,...r})};MD.displayName=Uge;var zge="AlertDialogOverlay",LD=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=jo(r);return a.jsx(Uw,{...s,...n,ref:t})});LD.displayName=zge;var vu="AlertDialogContent",[qge,Hge]=$ge(vu),Wge=LL("AlertDialogContent"),$D=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,children:n,...s}=e,i=jo(r),o=m.useRef(null),l=Tr(t,o),c=m.useRef(null);return a.jsx(dB,{contentName:vu,titleName:FD,docsSlug:"alert-dialog",children:a.jsx(qge,{scope:r,cancelRef:c,children:a.jsxs(zw,{role:"alertdialog",...i,...s,ref:l,onOpenAutoFocus:vn(s.onOpenAutoFocus,u=>{var d;u.preventDefault(),(d=c.current)==null||d.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[a.jsx(Wge,{children:n}),a.jsx(Gge,{contentRef:o})]})})})});$D.displayName=vu;var FD="AlertDialogTitle",BD=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=jo(r);return a.jsx(qw,{...s,...n,ref:t})});BD.displayName=FD;var UD="AlertDialogDescription",zD=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=jo(r);return a.jsx(Hw,{...s,...n,ref:t})});zD.displayName=UD;var Vge="AlertDialogAction",qD=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,s=jo(r);return a.jsx(Ww,{...s,...n,ref:t})});qD.displayName=Vge;var HD="AlertDialogCancel",WD=m.forwardRef((e,t)=>{const{__scopeAlertDialog:r,...n}=e,{cancelRef:s}=Hge(HD,r),i=jo(r),o=Tr(t,s);return a.jsx(Ww,{...i,...n,ref:o})});WD.displayName=HD;var Gge=({contentRef:e})=>{const t=`\`${vu}\` requires a description for the component to be accessible for screen reader users.
7917
7918You can add a description to the \`${vu}\` by passing a \`${UD}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
7919
7920Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${vu}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
7921
7922For more information, see https://radix-ui.com/primitives/docs/components/
7922alert-dialog`;return m.useEffect(()=>{var n;document.getElementById((n=e.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},Kge=DD,Yge=MD,VD=LD,GD=$D,KD=qD,YD=WD,JD=BD,XD=zD;const Jge=Kge,Xge=Yge,ZD=m.forwardRef(({className:e,...t},r)=>a.jsx(VD,{className:L("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:r}));ZD.displayName=VD.displayName;const QD=m.forwardRef(({className:e,...t},r)=>a.jsxs(Xge,{children:[a.jsx(ZD,{}),a.jsx(GD,{ref:r,className:L("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));QD.displayName=GD.displayName;const eM=({className:e,...t})=>a.jsx("div",{className:L("flex flex-col space-y-2 text-center sm:text-left",e),...t});eM.displayName="AlertDialogHeader";const tM=({className:e,...t})=>a.jsx("div",{className:L("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});tM.displayName="AlertDialogFooter";const nM=m.forwardRef(({className:e,...t},r)=>a.jsx(JD,{ref:r,className:L("text-lg font-semibold",e),...t}));nM.displayName=JD.displayName;const rM=m.forwardRef(({className:e,...t},r)=>a.jsx(XD,{ref:r,className:L("text-sm text-muted-foreground",e),...t}));rM.displayName=XD.displayName;const sM=m.forwardRef(({className:e,...t},r)=>a.jsx(KD,{ref:r,className:L(H_(),e),...t}));sM.displayName=KD.displayName;const aM=m.forwardRef(({className:e,...t},r)=>a.jsx(YD,{ref:r,className:L(H_({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));aM.displayName=YD.displayName;function Zge(e){return e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"studio-project":`studio-project-${Date.now().toString(36)}`}function Qge(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Imported Project"}function exe(e,t){return!e||e.length<=t?e:`${e.slice(0,t).trim()}...`}function txe(e,t,r){const n=e.support.supported?"Supported":"Needs review",s=e.dbHints.length?e.dbHints.slice(0,3).map(o=>`- ${o.type}: ${o.recommendation}`).join(`
7923`):"- No database layer detected yet. I can help connect Supabase, Postgres, Prisma, Mongo, or another backend when you are ready.",i=e.skipped.length?`
7924
7925**Skipped files**
7926${e.skipped.slice(0,4).map(o=>`- ${o.path}: ${o.reason}`).join(`
7927`)}${e.skipped.length>4?`
7928- ${e.skipped.length-4} more skipped`:""}`:"";return`✅ **Imported ${e.repo.full_name} as ${t}**
7929
7930I scanned this GitHub repository and opened it as a fresh Studio Jungle project. The previous project was left unchanged.
7931
7932**Repo snapshot**
7933- Stack: ${e.support.stack||"Unknown"}
7934- Support: ${n}${e.support.reason?` — ${e.support.reason}`:""}
7935- Branch: ${e.branch||e.repo.default_branch||"main"}
7936- Files imported: ${r}
7937- Files scanned: ${e.scanned_files}
7938
7939**What I found**
7940${exe(e.blueprint,900)}
7941
7942**Database / backend**
7943${s}${i}
7944
7945**Good next checks**
79461. Preview is opened first so Studio Jungle can run the app and surface dependency/build issues.
79472. If dependencies or scripts are missing, use Fix build and I will repair only the relevant files.
79483. Ask me to explain the codebase, wire auth/data, connect the detected database, or prepare it for publish.`}function nxe(e){var n;const t=(n=e.split(".").pop())==null?void 0:n.toLowerCase();return{css:"css",html:"html",js:"javascript",json:"json",jsx:"javascript",md:"markdown",mjs:"javascript",sql:"sql",svg:"xml",ts:"typescript",tsx:"typescript",txt:"text",xml:"xml",yaml:"yaml",yml:"yaml"}[t||""]||"text"}function iM(e){return[...e].map(t=>t.type==="folder"?{...t,children:iM(t.children||[])}:t).sort((t,r)=>t.type!==r.type?t.type==="folder"?-1:1:t.name.localeCompare(r.name))}function rxe(e){const t=[];
7948for(const r of e){const n=r.path.split("/").filter(Boolean);if(!n.length)continue;let s=t;n.forEach((i,o)=>{if(o===n.length-1){const u=s.find(d=>d.type==="file"&&d.name===i);u?u.content=r.content:s.push({name:i,type:"file",content:r.content});return}let c=s.find(u=>u.type==="folder"&&u.name===i);c||(c={name:i,type:"folder",children:[]},s.push(c)),c.children||(c.children=[]),s=c.children})}return iM(t)}function sxe(e,t){return`studiojungle/${(e||"studio-update").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,36)||"studio-update"}-${(t||Date.now().toString(36)).slice(0,8)}`}function Hf(e){return{owner:`github-owner::${e}`,repo:`github-repo::${e}`,branch:`github-branch::${e}`,repoUrl:`github-repo-url::${e}`,repoFullName:`github-repo-full-name::${e}`}}function oM({embedded:e=!1,onBack:t,onImported:r}={}){var Zt,Ke;const{files:n,project:s,setFiles:i,setActiveWorkspaceTab:o,createProject:l,switchProject:c}=gn(),{user:u}=Us(),d=(s==null?void 0:s.id)??null,[p,h]=m.useState(""),[f,x]=m.useState(null),[g,y]=m.useState(!1),[b,v]=m.useState(!1),[k,N]=m.useState(!1),[j,w]=m.useState(null),[S,T]=m.useState(null),[C,A]=m.useState(!1),[P,E]=m.useState(!1),[_,I]=m.useState(null),[D,M]=m.useState(null),[B,$]=m.useState(!1),[K,R]=m.useState(!1),[Y,Z]=m.useState([]),[O,ne]=m.useState(!1),[oe,he]=m.useState(""),[ae,ve]=m.useState(!1),[re,se]=m.useState(null),[le,te]=m.useState(!1),[We,Me]=m.useState("main"),Te=Zge(s==null?void 0:s.name),Ee=m.useCallback(async()=>{if(!d)return null;const{data:ie,error:we}=await G.from("projects").select("github_owner, github_repo, github_branch, github_auto_push, github_auto_pr").eq("id",d).single();return we?(console.warn("[github] DB read failed:",we.message),null):ie},[d]),st=m.useCallback(async ie=>{if(!d)return;const{error:we}=await G.from("projects").update(ie).eq("id",d);we&&console.warn("[github] DB write failed:",we.message)},[d]);m.useEffect(()=>{const ie=Dh(u==null?void 0:u.id);ie.token&&ie.user?(h(ie.token),x({login:ie.user.login,name:ie.user.name||ie.user.login,avatar_url:ie.user.avatar_url||""}),v(!0)):(h(""),x(null),v(!1))},[u==null?void 0:u.id]),m.useEffect(()=>{if(!d){N(!1),T(null),w(null),$(!1),R(!1),Me("main");return}(async()=>{const ie=Hf(d),we=await Ee();if(we&&we.github_owner===null&&we.github_repo===null){const Je=localStorage.getItem(ie.owner),ot=localStorage.getItem(ie.repo);if(Je&&ot){const V=localStorage.getItem(ie.branch)||"main",ye=localStorage.getItem(`github-auto-push::${d}`)==="true",me=localStorage.getItem(`github-auto-pr::${d}`)==="true";await st({github_owner:Je,github_repo:ot,github_branch:V,github_auto_push:ye,github_auto_pr:me}),console.log(`[github] migrated localStorage → DB for project ${d}`),[ie.owner,ie.repo,ie.branch,ie.repoFullName,ie.repoUrl].forEach(dt=>localStorage.removeItem(dt));const _e=await Ee();xt(_e,ie);return}}xt(we,ie)})()},[d]);function xt(ie,we){if(!ie){T(null),w(null),N(!1),Me("main"),$(!1),R(!1);return}const Je=ie.github_owner,ot=ie.github_repo;if(Je&&ot){const V=`${Je}/${ot}`,ye=ie.github_branch||"main",me=`https://github.com/${V}`;T(V),w(me),N(!0),Me(ye),localStorage.setItem(we.owner,Je),localStorage.setItem(we.repo,ot),localStorage.setItem(we.branch,ye),localStorage.setItem(we.repoFullName,V),localStorage.setItem(we.repoUrl,me)}else T(null),w(null),N(!1),Me("main"),[we.owner,we.repo,we.branch,we.repoFullName,we.repoUrl].forEach(V=>localStorage.removeItem(V));$(!!ie.github_auto_push),R(!!ie.github_auto_pr)}m.useEffect(()=>{const ie=me=>{if(me.type==="github-oauth-success"&&me.access_token){if(!(u!=null&&u.id)){Mt({title:"Sign in required",description:"Sign in to Studio Jungle before connecting GitHub.",variant:"destructive"}),y(!1);return}h(me.access_token),TX(u.id,me.access_token),Yt(me.access_token)}else me.type==="github-oauth-error"&&(Mt({title:"GitHub auth failed",description:me.error,variant:"destructive"}),y(!1))};let we=!1;const Je=me=>{we||(we=!0,ie(me))},ot=me=>{var _e,dt;(dt=(_e=me.data)==null?void 0:_e.type)!=null&&dt.startsWith("github-oauth-")&&Je(me.data)};window.addEventListener("message",ot);const V=me=>{if(me.key==="github-oauth-result"&&me.newValue)try{Je(JSON.parse(me.newValue)),localStorage.removeItem("github-oauth-result")}catch{}};window.addEventListener("storage",V);let ye=null;try{ye=new BroadcastChannel("github-oauth"),ye.onmessage=me=>{var _e,dt;(dt=(_e=me.data)==null?void 0:_e.type)!=null&&dt.startsWith("github-oauth-")&&Je(me.data)}}catch{}try{const me=localStorage.getItem("github-oauth-result");me&&(Je(JSON.parse(me)),localStorage.removeItem("github-oauth-result"))}catch{}return()=>{window.removeEventListener("message",ot),window.removeEventListener("storage",V),ye&&ye.close()}},[u==null?void 0:u.id]);const on=m.useCallback(async(ie,we,Je={})=>{const{data:ot,error:V}=await G.functions.invoke("github-push",{body:{action:ie,token:we,...Je}});if(V)throw new Error(V.message);if(ot!=null&&ot.error)throw new Error(ot.error);return ot},[]),Yt=async ie=>{try{const we=await on("user-info",ie);x(we),v(!0),EX(u==null?void 0:u.id,{login:we.login,name:we.name||we.login,avatar_url:we.avatar_url||""})}catch(we){const Je=we instanceof Error?we.message:"Unknown error";Mt({title:"Connection failed",description:Je,variant:"destructive"})}finally{y(!1)}},mt=m.useCallback(async(ie=p)=>{var we;if(ie){ne(!0);try{const Je=await on("list-repos",ie);Z(Je||[]),!oe&&((we=Je==null?void 0:Je[0])!=null&&we.full_name)&&he(Je[0].full_name)}catch(Je){Mt({title:"Could not load repositories",description:Je instanceof Error?Je.message:"Unknown error",variant:"destructive"})}finally{ne(!1)}}},[on,oe,p]);m.useEffect(()=>{b&&p&&Y.length===0&&mt(p)},[b,mt,Y.length,p]);const ln=async()=>{y(!0);try{const{data:ie,error:we}=await G.functions.invoke("github-oauth-callback",{body:{action:"get-auth-url",appOrigin:window.location.origin,callbackPath:pp.GITHUB_OAUTH_CALLBACK}});if(we)throw new Error(we.message);if(ie!=null&&ie.error)throw new Error(ie.error);const Je=600,ot=700,V=window.screenX+(window.outerWidth-Je)/2,ye=window.screenY+(window.outerHeight-ot)/2,me=window.open(ie.auth_url,"github-oauth",`width=${Je},height=${ot}
7948,left=${V},top=${ye},popup=yes`);if(!me){Mt({title:"Popup blocked",description:"Please allow popups to connect GitHub.",variant:"destructive"}),y(!1);return}const _e=setInterval(()=>{me.closed&&(clearInterval(_e),y(!1))},500)}catch(ie){Mt({title:"Failed to start OAuth",description:ie instanceof Error?ie.message:"Unknown error",variant:"destructive"}),y(!1)}},at=()=>{const ie=[],we=(Je,ot="")=>{for(const V of Je){const ye=ot?`${ot}/${V.name}`:V.name;V.type==="folder"&&V.children?we(V.children,ye):V.type==="file"&&V.content&&ie.push({path:ye,content:V.content})}};return we(n),ie},gt=async(ie,we,Je)=>{const ot=at();if(ot.length===0)throw new Error("No files to push");let V;if(s!=null&&s.id){const{data:{user:ye}}=await G.auth.getUser();if(ye){const{data:me}=await G.from("project_deployments").insert({project_id:s.id,user_id:ye.id,target:"github",status:"pending",branch:We,metadata:{owner:ie,repo:we,file_count:ot.length,manual:!0}}).select("id").single();V=me==null?void 0:me.id}}try{const ye=await on("push",p,{owner:ie,repo:we,files:ot,commitMessage:Je,branch:We,committer:{name:"StudioJungle Bot",email:"[email protected]"}});return V&&await G.from("project_deployments").update({status:"success",commit_sha:ye.commit_sha,deploy_url:ye.html_url}).eq("id",V),ye}catch(ye){throw V&&await G.from("project_deployments").update({status:"failed",error_message:ye instanceof Error?ye.message:String(ye)}).eq("id",V),ye}},$t=async(ie,we,Je,ot,V)=>{const ye=Hf(ie),{error:me}=await G.from("projects").update({github_owner:we,github_repo:Je,github_branch:ot}).eq("id",ie);me&&console.warn("[github] DB write failed:",me.message);const _e=`${we}/${Je}`;localStorage.setItem(ye.owner,we),localStorage.setItem(ye.repo,Je),localStorage.setItem(ye.branch,ot),localStorage.setItem(ye.repoFullName,_e),localStorage.setItem(ye.repoUrl,V)},ue=async(ie,we,Je,ot)=>{d&&await $t(d,ie,we,Je,ot)},je=async(ie,we)=>{const Je=we.map(V=>({project_id:ie,name:V.path.split("/").pop()||V.path,path:V.path,content:V.content||null,language:nxe(V.path)}));await G.from("project_files").delete().eq("project_id",ie);const{error:ot}=await G.from("project_files").upsert(Je,{onConflict:"project_id,path"});if(ot)throw ot},ct=async()=>{if(!oe)return;ve(!0),se(null);const ie=(s==null?void 0:s.name)||"Your current project";try{const[we,Je]=oe.split("/"),ot=Y.find(kn=>kn.full_name===oe),V=await on("inspect-repo",p,{owner:we,repo:Je,branch:(ot==null?void 0:ot.default_branch)||"main"});if(se(V),!V.support.supported){Mt({title:"Repo scanned, but not imported",description:V.support.reason,variant:"destructive"});return}const ye=[...V.files,{path:".sj/blueprint.md",content:V.blueprint}],me=Qge(V.repo.full_name.split("/")[1]||Je),_e=await l(me,`Imported from GitHub: ${V.repo.full_name}`);if(!(_e!=null&&_e.id))throw new Error("Could not create a new Studio Jungle project for this import.");await je(_e.id,ye),await G.from("project_messages").insert({project_id:_e.id,role:"ai",content:txe(V,me,ye.length)}),i(rxe(ye));const[dt,kt]=V.repo.full_name.split("/"),wn=V.branch||V.repo.default_branch||"main";await $t(_e.id,dt,kt,wn,V.repo.html_url),await c(_e.id),T(V.repo.full_name),w(V.repo.html_url),Me(wn),N(!0),o("preview"),r==null||r(),Mt({title:"Imported as a new project",description:`${ie} was left unchanged. Opening Preview for ${me} so dependencies/build can run.`})}catch(we){Mt({title:"Import failed",description:we instanceof Error?we.message:"Unknown error",variant:"destructive"})}finally{ve(!1)}},it=async()=>{E(!0);try{const ie=(f==null?void 0:f.login)||"";let we;try{const dt=await on("get-repo",p,{owner:ie,repo:Te});we=dt,Mt({title:"Using existing repository",description:dt.full_name})}catch{we=await on("create-repo",p,{repoName:Te,isPrivate:C})}const Je=we.full_name,[ot,V]=Je.split("/"),ye=we.default_branch||"main",me=we.html_url||`https://github.com/${Je}`;T(Je),w(me),N(!0),Me(ye),await ue(ot,V,ye,me);const _e=await gt(ot,V,`Initial commit from StudioJungle — ${(s==null?void 0:s.name)||"project"}`);M(_e.html_url),I(new Date().toLocaleTimeString()),Mt({title:"🎉 Repository ready & code pushed!",description:Je})}catch(ie){Mt({title:"Failed",description:ie instanceof Error?ie.message:"Unknown error",variant:"destructive"})}finally{E(!1)}},q=async()=>
7948{if(S){E(!0);try{const[ie,we]=S.split("/"),Je=await gt(ie,we,`Update from StudioJungle — ${new Date().toISOString()}`);M(Je.html_url),I(new Date().toLocaleTimeString()),Mt({title:"Code pushed!",description:`Committed to ${S}`})}catch(ie){Mt({title:"Push failed",description:ie instanceof Error?ie.message:"Unknown error",variant:"destructive"})}finally{E(!1)}}},Nt=async ie=>{$(ie),d&&(await st({github_auto_push:ie}),d&&localStorage.setItem(`github-auto-push::${d}`,String(ie))),Mt({title:ie?"Auto-push enabled":"Auto-push disabled"})},U=async ie=>{R(ie);let we=We;if(ie&&(We==="main"||We==="master")&&(we=sxe(s==null?void 0:s.name,d),Me(we)),d){await st({github_auto_pr:ie,github_branch:we});const Je=Hf(d);localStorage.setItem(Je.branch,we),localStorage.setItem(`github-auto-pr::${d}`,String(ie))}Mt({title:ie?"Auto-PR enabled":"Auto-PR disabled",description:ie?`Auto-push will use ${we} and open a PR to main.`:void 0})},Ne=async()=>{if(await st({github_owner:null,github_repo:null,github_branch:null,github_auto_push:!1,github_auto_pr:!1}),d){const ie=Hf(d);[ie.owner,ie.repo,ie.branch,ie.repoFullName,ie.repoUrl,`github-auto-push::${d}`,`github-auto-pr::${d}`].forEach(we=>localStorage.removeItem(we))}N(!1),T(null),w(null),M(null),I(null),$(!1),R(!1),Me("main"),Mt({title:"Disconnected from GitHub"})},Ft=()=>{Ne(),IX(u==null?void 0:u.id),h(""),x(null),v(!1)};return a.jsxs("div",{className:e?"min-h-full flex flex-col":"h-full flex flex-col",children:[a.jsxs("div",{className:"h-11 border-b flex items-center px-4 gap-2 shrink-0",children:[a.jsxs("button",{onClick:()=>{if(t){t();return}o("preview")},className:"flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[a.jsx(ei,{className:"w-3.5 h-3.5"}),"Back"]}),a.jsx("div",{className:"h-4 w-px bg-border"}),a.jsx(to,{className:"w-4 h-4 text-foreground"}),a.jsx("span",{className:"text-sm font-semibold",children:"GitHub"}),k&&a.jsxs(Ge,{variant:"secondary",className:"ml-auto text-[10px] gap-1",children:[a.jsx(Wn,{className:"w-2.5 h-2.5"})," Connected"]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-8 overflow-y-auto",children:a.jsxs("div",{className:"w-full max-w-3xl space-y-6",children:[!b&&a.jsxs("div",{className:"text-center space-y-6",children:[a.jsx("div",{className:"w-20 h-20 rounded-2xl bg-foreground
7948/5 flex items-center justify-center mx-auto",children:a.jsx(to,{className:"w-10 h-10 text-foreground"})}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-bold text-foreground",children:"Connect to GitHub"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Push Studio Jungle code to GitHub, or import an existing repository so the editor can inspect it first and create a blueprint."})]}),a.jsxs(Q,{onClick:ln,disabled:g,size:"lg",className:"gap-2 w-full",children:[g?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(to,{className:"w-4 h-4"}),g?"Connecting...":"Sign in with GitHub"]})]}),b&&(e||!k)&&a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"flex items-center gap-3 p-4 rounded-xl bg-secondary/50 border",children:f&&a.jsxs(a.Fragment,{children:[a.jsx("img",{src:f.avatar_url,alt:"",className:"w-10 h-10 rounded-full"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:f.name||f.login}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:["@",f.login]})]}),a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 px-2.5 py-1 rounded-full",children:[a.jsx(Wn,{className:"w-3 h-3"}),"Connected"]})]})}),a.jsxs("div",{className:"rounded-2xl border bg-card overflow-hidden",children:[a.jsxs("div",{className:"p-4 border-b bg-muted/20 flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center shrink-0",children:a.jsx(Ak,{className:"w-5 h-5"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Import an existing repository"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Studio Jungle scans the code, checks whether the stack is supported, writes a blueprint, then opens Preview so dependencies can install and the app can run."})]}),a.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>mt(),disabled:O,className:"gap-1.5",children:[O?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(zr,{className:"w-3.5 h-3.5"}),"Refresh"]})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto]",children:[a.jsxs("select",{value:oe,onChange:ie=>he(ie.target.value),className:"h-10 rounded-lg border bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-primary",disabled:O||ae,children:[Y.length===0&&a.jsx("option",{value:"",children:"No repositories loaded"}),Y.map(ie=>a.jsxs("option",{value:ie.full_name,children:[ie.full_name," · ",ie.default_branch]},ie.full_name))]}),a.jsxs(Q,{onClick:()=>te(!0),disabled:!oe||ae,className:"gap-2",children:[ae?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(c6,{className:"w-4 h-4"}),ae?"Inspecting...":"Inspect & Import"]})]}),a.jsx(Jge,{open:le,onOpenChange:te,children:a.jsxs(QD,{children:[a.jsxs(eM,{children:[a.jsx(nM,{children:"Import this repository as a new project?"}),a.jsxs(rM,{children:["Studio Jungle will scan ",a.jsx("span",{className:"font-medium text-foreground",children:oe||"this repository"}),", create a separate editor project if the stack is supported, and leave",a.jsxs("span",{className:"font-medium text-foreground",children:[" ",(s==null?void 0:s.name)||"your current project"]})," unchanged."]})]}),a.jsxs("div",{className:"rounded-xl border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Unsupported stacks stop after the scan. Supported imports open as a new project in Preview with a generated",a.jsx("code",{className:"mx-1 rounded bg-background px-1",children:".sj/blueprint.md"}),"and a Studio Jungle AI summary in chat before any edits happen."]}),a.jsxs(tM,{children:[a.jsx(aM,{disabled:ae,children:"Cancel"}),a.jsxs(sM,{onClick:ct,disabled:!oe||ae,className:"gap-2",children:[ae?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(Ak,{className:"w-4 h-4"}),"Create new project"]})]})]})}),a.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[a.jsxs("div",{className:"rounded-xl border bg-background/60 p-3",children:[a.jsx(Nu,{className:"w-4 h-4 text-primary mb-2"}),a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Supported code"}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Vite React and static web projects import directly."})]}),a.jsxs("div",{className:"rounded-xl border bg-background/60 p-3",children:[a.jsx(el,{className:"w-4 h-4 text-primary mb-2"}),a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Safe import"}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Unsupported stacks are reported without overwriting files."})]}),a.jsxs("div",{className:"rounded-xl border bg-background/60 p-3",children:[a.jsx(Hn,{className:"w-4 h-4 text-primary mb-2"}),a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Database aware"}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Supabase, Postgres, Prisma, Mongo, and SQL hints are added to the blueprint."})]})]}),re&&a.jsxs("div",{className:`rounded-xl border p-4 ${re.support.supported?"bg-emerald-500/5 border-emerald-500/20":"bg-destructive/5 border-destructive/20"}`,children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${re.support.supported?"bg-emerald-500/10 text-emerald-600":"bg-destructive/10 text-destructive"}`,children:re.support.supported?a.jsx(Wn,{className:"w-4 h-4"}):a.jsx(is,{className:"w-4 h-4"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:re.support.supported?"Ready in the editor":"Not supported yet"}),a.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[re.support.stack,": ",re.supp
7948ort.reason]}),a.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2",children:["Scanned ",re.scanned_files||re.files.length," files",(Zt=re.skipped)!=null&&Zt.length?` · skipped ${re.skipped.length}`:""]})]})]}),((Ke=re.dbHints)==null?void 0:Ke.length)>0&&a.jsxs("div",{className:"mt-4 rounded-lg border bg-background/70 p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(Hn,{className:"w-4 h-4 text-primary"}),a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Database detected"})]}),a.jsx("div",{className:"space-y-1",children:re.dbHints.slice(0,3).map(ie=>a.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.jsx("span",{className:"font-medium text-foreground",children:ie.type})," in ",a.jsx("code",{className:"rounded bg-muted px-1",children:ie.evidence})]},`${ie.type}-${ie.evidence}`))}),a.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[a.jsx(Q,{variant:"outline",size:"sm",onClick:()=>o("data"),children:"Connect existing DB"}),a.jsx(Q,{variant:"outline",size:"sm",onClick:()=>o("cloud"),children:"Create Supabase"})]})]})]})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Repository"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"A repository will be created or linked if it already exists."})]}),a.jsxs("div",{className:"p-4 rounded-xl border bg-card space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(oo,{className:"w-4 h-4 text-primary"}),a.jsxs("span",{className:"text-sm font-mono font-medium text-foreground",children:[f==null?void 0:f.login,"/",Te]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[C?a.jsx(Bs,{className:"w-3 h-3"}):a.jsx(Br,{className:"w-3 h-3"}),C?"Private repository":"Public repository"]}),a.jsx(Xl,{checked:C,onCheckedChange:A,className:"scale-[0.85]"})]})]}),a.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["All code for ",a.jsx("span",{className:"font-medium text-foreground",children:(s==null?void 0:s.name)||"this project"})," will be pushed."]})]}),a.jsxs(Q,{onClick:it,disabled:P,size:"lg",className:"gap-2 w-full",children:[P?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(oo,{className:"w-4 h-4"}),P?"Setting up...":"Create Repository & Push Code"]})]}),b&&k&&!e&&a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"flex items-center gap-3 p-4 rounded-xl bg-secondary/50 border",children:f&&a.jsxs(a.Fragment,{children:[a.jsx("img",{src:f.avatar_url,alt:"",className:"w-10 h-10 rounded-full"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:f.name||f.login}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:["@",f.login]})]})]})}),a.jsxs("div",{className:"p-4 rounded-xl border bg-card space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(to,{className:"w-4 h-4 text-foreground"}),a.jsx("span",{className:"text-sm font-mono font-semibold text-foreground",children:S})]}),a.jsxs("a",{href:j||"#",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-primary hover:underline",children:[a.jsx(Is,{className:"w-3 h-3"}),"View on GitHub"]}),_&&a.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Last pushed at ",_]}),a.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Target branch: ",a.jsx("code",{className:"rounded bg-muted px-1 font-mono text-[10px]",children:We})]}),D&&a.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text[11px] text-muted-foreground hover:text-foreground",children:[a.jsx(oo,{className:"w-3 h-3"}),"View latest commit"]})]}),a.jsxs("div",{className:"p-4 rounded-xl border bg-card flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Auto-push on build"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Automatically push code after every successful build"})]}),a.jsx(Xl,{checked:B,onCheckedChange:Nt})]}),a.jsxs("div",{className:"p-4 rounded-xl border bg-card flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Open PR back to main"}),a.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["When auto-pushing to a feature branch, open (or reuse) a pull request targeting ",a.jsx("code",{className:"text-[10px] bg-muted px-1 rounded",children:"main"}),"."]})]}),a.jsx(Xl,{checked:K,onCheckedChange:U})]}),a.jsxs("div",{className:"p-3 rounded-lg border border-dashed bg-muted/30 flex items-start gap-2",children:[a.jsx(is,{className:"w-4 h-4 text-muted-foreground shrink-0 mt-0.5"}),a.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:["Commits are authored by ",a.jsx("span",{className:"font-semibold text-foreground",children:"StudioJungle Bot"})," ([email protected]) so you can easily identify auto-generated pushes."]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Q,{onClick:q,disabled:P,className:"flex-1 gap-1.5",children:[P?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(zr,{className:"w-3.5 h-3.5"}),"Push Now"]}),a.jsx(Q,{variant:"outline",onClick:Ft,className:"gap-1.5 text-destructive hover:text-destructive",children:"Disconnect"})]}),a.jsx(Lge,{projectId:(s==null?void 0:s.id)||null,className:"mt-2"})]})]})})]})}const axe=[{prompt:"Build a landing page with hero section",expected:["page-gen"]},{prompt:"Add Stripe payment checkout",expected:["connector-stripe"]},{prompt:"Create database tables for users and orders",expected:["sc
7948hema-builder"]},{prompt:"Add login and signup with password reset",expected:["auth-gen"]},{prompt:"Send Slack notifications when order placed",expected:["connector-slack"]},{prompt:"Deploy to production",expected:["deploy-helper"]},{prompt:"Build a full app with auth, database, and email",expected:["auth-gen","schema-builder","connector-email"]}],ixe=[{nodes:["send_message","api_call"],expected:["connector-slack","rest-proxy"]},{nodes:["send_email","save_lead"],expected:["connector-email","schema-builder"]},{nodes:["knowledge_search"],expected:["connector-perplexity"]}];function oxe(){const[e,t]=m.useState([]),[r,n]=m.useState(!1),s=m.useCallback(async()=>{n(!0),t([]);const l=[],c=C=>{l.push(C),t([...l])};await new Promise(C=>setTimeout(C,200));const u=performance.now(),d=lo.length>=30&&lo.every(C=>C.id&&C.name&&C.category);c({name:"Tool Registry (34 tools, 6 categories)",passed:d,detail:`${lo.length} tools loaded`,duration:performance.now()-u}),await new Promise(C=>setTimeout(C,150));const p=performance.now(),h=A0("code"),f=A0("connector"),x=h.length>0&&f.length>0&&h.every(C=>C.category==="code");c({name:"Category Filtering",passed:x,detail:`code:${h.length} connectors:${f.length}`,duration:performance.now()-p}),await new Promise(C=>setTimeout(C,150));const g=performance.now(),y=YJ(),b=JJ("send_message"),v=y.length>0&&b.length>0;c({name:"Workflow ↔ Tool Mapping",passed:v,detail:`${y.length} workflow tools, send_message→${b.map(C=>C.id).join(",")}`,duration:performance.now()-g}),await new Promise(C=>setTimeout(C,150));for(const C of axe){const A=performance.now(),P=XJ(C.prompt),E=C.expected.every(_=>P.includes(_));c({name:`Prompt → "${C.prompt.slice(0,40)}..."`,passed:E,detail:`Expected: ${C.expected.join(", ")} | Got: ${P.join(", ")||"(none)"}`,duration:performance.now()-A}),await new Promise(_=>setTimeout(_,100))}const k=performance.now(),N=_0("```sql\nCREATE TABLE users (id uuid);\n```\nUsing Deno.serve for edge function",[]),j=N.includes("schema-builder")&&N.includes("edge-fn-gen");c({name:"Response → Tool Detection",passed:j,detail:`Detected: ${N.join(", ")}`,duration:performance.now()-k}),await new Promise(C=>setTimeout(C,150));for(const C of ixe){const A=performance.now(),P=ZJ(C.nodes),E=C.expected.every(_=>P.includes(_));c({name:`Workflow Run [${C.nodes.join(", ")}]`,passed:E,detail:`Expected: ${C.expected.join(", ")} | Got: ${P.join(", ")}`,duration:performance.now()-A}),await new Promise(_=>setTimeout(_,100))}const w=performance.now(),S=P0("connector-stripe"),T=(S==null?void 0:S.name)==="Stripe Connector"&&(S==null?void 0:S.category)==="connector";c({name:"Tool Lookup by ID",passed:T,detail:`connector-stripe → ${(S==null?void 0:S.name)||"NOT FOUND"}`,duration:performance.now()-w}),n(!1)},[]),i=e.filter(l=>l.passed).length,o=e.filter(l=>!l.passed).length;return a.jsxs("div",{className:"rounded-lg border bg-card overflow-hidden",children:[a.jsxs("div",{className:"px-3 py-2.5 bg-secondary/30 border-b flex items-center gap-2",children:[a.jsx(hr,{className:"w-4 h-4 text-primary"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Integration & Tools Demo"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Run all integration tests in-browser"})]}),a.jsx(Q,{size:"sm",variant:e.length>0?"outline":"default",onClick:e.length>0?()=>t([]):s,disabled:r,className:"h-7 text-xs gap-1.5",children:r?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"}),"Running..."]}):e.length>0?a.jsxs(a.Fragment,{children:[a.jsx(Ri,{className:"w-3 h-3"}),"Reset"]}):a.jsxs(a.Fragment,{children:[a.jsx(Oi,{className:"w-3 h-3"}),"Run All Tests"]})})]}),e.length>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"px-3 py-2 border-b bg-secondary/10 flex items-center gap-3",children:[a.jsxs("span",{className:"text-[10px] font-semibold text-emerald-600 flex items-center gap-1",children:[a.jsx(mn,{className:"w-3 h-3"})," ",i," passed"]}),o>0&&a.jsxs("span",{className:"text-[10px] font-semibold text-red-600 flex items-center gap-1",children:[a.jsx(aa,{className:"w-3 h-3"})," ",o," failed"]}),a.jsxs("span",{className:"text-[10px] text-muted-foreground ml-auto",children:[e.reduce((l,c)=>l+c.duration,0).toFixed(0),"ms total"]})]}),a.jsx($r,{className:"max-h-[300px]",children:a.jsx("div",{className:"p-2 space-y-1",children:e.map((l,c)=>
7948a.jsxs("div",{className:L("flex items-start gap-2 px-2 py-1.5 rounded-md text-[11px]",l.passed?"bg-emerald-500/5":"bg-red-500/5"),children:[l.passed?a.jsx(mn,{className:"w-3.5 h-3.5 text-emerald-500 shrink-0 mt-0.5"}):a.jsx(aa,{className:"w-3.5 h-3.5 text-red-500 shrink-0 mt-0.5"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"font-medium text-foreground truncate",children:l.name}),a.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:l.detail})]}),a.jsxs("span",{className:"text-[9px] text-muted-foreground shrink-0",children:[l.duration.toFixed(1),"ms"]})]},c))})})]})]})}var lxe=Symbol.for("react.lazy"),$g=B_[" use ".trim().toString()];function cxe(e){return typeof e=="object"&&e!==null&&"then"in e}function lM(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===lxe&&"_payload"in e&&cxe(e._payload)}function uxe(e){const t=dxe(e),r=m.forwardRef((n,s)=>{let{children:i,...o}=n;lM(i)&&typeof $g=="function"&&(i=$g(i._payload));const l=m.Children.toArray(i),c=l.find(hxe);if(c){const u=c.props.children,d=l.map(p=>p===c?m.Children.count(u)>1?m.Children.only(null):m.isValidElement(u)?u.props.children:null:p);return a.jsx(t,{...o,ref:s,children:m.isValidElement(u)?m.cloneElement(u,void 0,d):null})}return a.jsx(t,{...o,ref:s,children:i})});return r.displayName=`${e}.Slot`,r}function dxe(e){const t=m.forwardRef((r,n)=>{let{children:s,...i}=r;if(lM(s)&&typeof $g=="function"&&(s=$g(s._payload)),m.isValidElement(s)){const o=mxe(s),l=fxe(i,s.props);return s.type!==m.Fragment&&(l.ref=n?$L(n,o):o),m.cloneElement(s,l)}return m.Children.count(s)>1?m.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var pxe=Symbol("radix.slottable");function hxe(e){return m.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===pxe}function fxe(e,t){const r={...t};for(const n in t){const s=e[n],i=t[n];/^on[A-Z]/.test(n)?s&&i?r[n]=(...l)=>{const c=i(...l);return s(...l),c}:s&&(r[n]=s):n==="style"?r[n]={...s,...i}:n==="className"&&(r[n]=[s,i].filter(Boolean).join(" "))}return{...e,...r}}function mxe(e){var n,s;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var gxe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],xxe=gxe.reduce((e,t)=>{const r=uxe(`Primitive.${t}`),n=m.forwardRef((s,i)=>{const{asChild:o,...l}=s,c=o?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a.jsx(c,{...l,ref:i})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),yxe=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),bxe="VisuallyHidden",rw=m.forwardRef((e,t)=>a.jsx(xxe.span,{...e,ref:t,style:{...yxe,...e.style}}));rw.displayName=bxe;const vxe=".studiojungle.dev";function wxe(){const{user:e}=Us(),[t,r]=m.useState(0),[n,s]=m.useState(0),[i,o]=m.useState(!0),l=m.useCallback(async()=>{if(!e){r(0),s(0),o(!1);return}o(!0);try{const{data:c,error:u}=await G.from("project_settings").select("project_id, vercel_project_id, vercel_deploy_url, vercel_custom_domain");if(u)throw u;const d=c||[],p=new Set;let h=0;for(const f of d)(f.vercel_project_id||f.vercel_deploy_url||f.vercel_custom_domain)&&p.add(f.project_id),f.vercel_custom_domain&&!f.vercel_custom_domain.toLowerCase().endsWith(vxe)&&(h+=1);r(p.size),s(h)}catch(c){console.error("[useDeployCounts] failed:",c)}finally{o(!1)}},[e]);return m.useEffect(()=>{l()},[l]),{publishedProjects:t,customDomains:n,loading:i,refresh:l}}function cM(e,t=12){const r=e.split(/\r?\n/).map(s=>s.trimEnd()).filter(Boolean),n=r.filter(s=>!s.trimStart().startsWith(">")&&/\b(error|failed|cannot|could not|not found|ts\d{4}|vite|rollup|eslint)\b/i.test(s));return(n.length>0?n:r).slice(-t)}function jxe(e,t,r=[]){const n=t.trim()||r.join(`
7949`).trim(),s=cM(n||"No build output was captured.",16);return[`Build failed (exit ${e})`,...s].join(`
7950`)}async function Nxe(e,t,r,n){const s="https://xfmlsevleobdlnjqxmdi.supabase.co",i="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo",{data:{session:o}}=await G.auth.getSession();if(!(o!=null&&o.access_token))throw new Error("Not authenticated — please sign in to run a sandbox build.");const l=await fetch(`${s}/functions/v1/sandbox-build`,{method:"POST",signal:n==null?void 0:n.signal,headers:{Authorization:`Bearer ${o.access_token}`,apikey:i,"Content-Type":"application/json"},body:JSON.stringify({files:e,project_id:(n==null?void 0:n.projectId)||null})});if(!l.ok){const f=await l.text().catch(()=>"");throw new Error(`sandbox-build request failed (${l.status}): ${f.slice(0,300)}`)}if(!l.body)throw new Error("sandbox-build returned no response body");const c=l.body.getReader(),u=new TextDecoder;let d="",p=null,h=null;try{for(;;){const{value:x,done:g}=await c.read();if(g)break;d+=u.decode(x,{stream:!0});const y=d.split(`
7951
7952`);d=y.pop()??"";for(const b of y)for(const v of b.split(`
7953`)){if(!v.startsWith("data: "))continue;
7953const k=v.slice(6).trim();if(!(!k||k==="[DONE]"))try{const N=JSON.parse(k);N.type==="log"&&N.line!==void 0?t(N.line):N.type==="preview_url"&&typeof N.url=="string"?(h=N.url,r==null||r(N.url)):N.type==="result"&&(p={success:N.success??!1,exit:N.exit??1,output:N.output??"",previewUrl:h})}catch{t(k)}}}const f=u.decode();if(f&&(d+=f),d.trim())for(const x of d.split(`
7954`)){const g=x.trim();if(!g.startsWith("data: "))continue;const y=g.slice(6).trim();if(!(!y||y==="[DONE]"))try{const b=JSON.parse(y);b.type==="log"&&b.line!==void 0?t(b.line):b.type==="preview_url"&&typeof b.url=="string"?(h=b.url,r==null||r(b.url)):b.type==="result"&&(p={success:b.success??!1,exit:b.exit??1,output:b.output??"",previewUrl:h})}catch{t(y)}}}finally{c.cancel().catch(()=>{})}return p??{success:!1,exit:1,output:"No result received from sandbox-build function.",previewUrl:h}}const Zi="studiojungle.dev",op=`{
7955          ink: {
7956            50: '#f7f8f5',
7957            100: '#e8ede4',
7958            200: '#d1dacb',
7959            300: '#aebda5',
7960            400: '#849976',
7961            500: '#667b56',
7962            600: '#4f6142',
7963            700: '#3f4d35',
7964            800: '#333f2d',
7965            900: '#1f2a1e',
7966            950: '#0b120d',
7967          },
7968          jungle: {
7969            50: '#eef8f1',
7970            100: '#d8efdf',
7971            200: '#b5dfc2',
7972            300: '#84c79b',
7973            400: '#4ba96e',
7974            500: '#289351',
7975            600: '#1d743f',
7976            700: '#195d35',
7977            800: '#164a2d',
7978            900: '#123d25',
7979            950: '#082114',
7980          },
7981          moss: {
7982            50: '#f5f7ed',
7983            100: '#e8ecd5',
7984            200: '#d3dcaf',
7985            300: '#b6c57f',
7986            400: '#98ab56',
7987            500: '#7a8d3d',
7988            600: '#5f7130',
7989            700: '#4a5828',
7990            800: '#3d4824',
7991            900: '#343e22',
7992            950: '#1a2110',
7993          },
7994          cream: '#f5efe1',
7995          paper: '#fbf7ef',
7996        }`,Vj=`/** @type {import('tailwindcss').Config} */
7997export default {
7998  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
7999  theme: {
8000    extend: {
8001      colors: ${op},
8002    },
8003  },
8004  plugins: [],
8005};
8006`;function uM(e){return e?(e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"app").replace(/-+$/,"")||"app":`app-${Date.now().toString(36)}`}function kxe(e){const t=uM(e),r=[t];return t.length>3&&(r.push(`${t}-app`.slice(0,24)),r.push(`my-${t}`.slice(0,24))),r.push(`${t}-${Math.random().toString(36).slice(2,6)}`.slice(0,24)),[...new Set(r)].slice(0,4)}function lp(e){return e.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"").replace(/^www\./,"")}function Sxe(e){const t=lp(e),r=t.split(".").filter(Boolean);if(r.length<=2)return{kind:"apex",host:"@",root:t};const n=r.slice(-2).join("."),s=new Set(["co.uk","co.in","co.jp","co.kr","co.za","co.nz","com.au","com.br","com.mx","com.tr","com.sg","org.uk","net.au","gov.uk"]);if(r.length===3&&s.has(n))return{kind:"apex",host:"@",root:t};const i=r.slice(-2).join(".");return{kind:"subdomain",host:r.slice(0,-2).join("."),root:i}}function Cxe(e){return/\bink\s*:/.test(e)&&/\bpaper\s*:/.test(e)?e:/theme\s*:\s*\{\s*extend\s*:\s*\{\s*\}\s*\}/s.test(e)?e.replace(/theme\s*:\s*\{\s*extend\s*:\s*\{\s*\}\s*\}/s,`theme: {
8007    extend: {
8008      colors: ${op},
8009    },
8010  }`):/extend\s*:\s*\{/s.test(e)?e.replace(/extend\s*:\s*\{/,`extend: {
8011      colors: ${op},`):/theme\s*:\s*\{/s.test(e)?e.replace(/theme\s*:\s*\{/,`theme: {
8012    extend: {
8013      colors: ${op},
8014    },`):/plugins\s*:\s*\[/s.test(e)?e.replace(/plugins\s*:\s*\[/,`theme: {
8015    extend: {
8016      colors: ${op},
8017    },
8018  },
8019  plugins: [`):Vj}function Pxe(e){let t=!1;const r=e.map(n=>{const s=n.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/^tailwind\.config\.(?:js|cjs|mjs|ts|mts)$/.test(s))return n;t=!0;const i=Cxe(n.content);return i===n.content?n:{...n,content:i}});return t?r:[...r,{path:"tailwind.config.js",content:Vj}]}function Axe(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/^vite\.config\.(?:ts|js|mjs|mts)$/.test(r))return t;const n=t.content.replace(/^\s*import\s+path\s+from\s+['"]path['"];?\s*$/gm,"").replace(/^\s*import\s+\*\s+as\s+path\s+from\s+['"]path['"];?\s*$/gm,"").replace(/path\.resolve\(\s*__dirname\s*,\s*['"]\.?\/?src['"]\s*\)/g,"'/src'").replace(/\n{3,}/g,`
8020
8021`);return n===t.content?t:{...t,content:n}})}function _xe(e){let t="";for(let r=0;r<e.length;r+=1){const n=e[r];t+=n==="'"&&e[r-1]!=="\\"?"\\'":n}return t}function Txe(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/\.(?:ts|tsx|js|jsx)$/.test(r))return t;const n=t.content.split(`
8022`).map(s=>s.replace(/^(\s*[A-Za-z_$][\w$-]*\s*:\s*)'(.+)'(\s*[,}]\s*)$/,(i,o,l,c)=>l.includes("'")?`${o}'${_xe(l)}'${c}`:i)).join(`
8023`);return n===t.content?t:{...t,content:n}})}function Exe(e){return e.map(t=>{const r=t.path.replace(/^\/+/,"").replace(/\\/g,"/");if(!/^tsconfig(?:\.[^.\/]+)?\.json$/i.test(r))return t;try{const n=JSON.parse(t.content);return n.compilerOptions={...n.compilerOptions||{}},n.compilerOptions.noUnusedLocals=!1,n.compilerOptions.noUnusedParameters=!1,{...t,content:`${JSON.stringify(n,null,2)}
8024`}}catch{const n=t.content.replace(/"noUnusedLocals"\s*:\s*true/g,'"noUnusedLocals": false').replace(/"noUnusedParameters"\s*:\s*true/g,'"noUnusedParameters": false');return n===t.content?t:{...t,content:n}}})}function dM({open:e,onOpenChange:t}){const{files:r,project:n,schema:s,buildMode:i,target:o,setActiveWorkspaceTab:l,appendBuildError:c,triggerBuildRef:u}=gn(),{user:d}=Us(),{capturePreviewThumbnail:p}=H1(),h=kw(),f=wxe(),x=nd(),g=m.useRef(r);g.current=r;const[y,b]=m.useState(null),[v,k]=m.useState("choose-mode"),[N,j]=m.useState(!1),[w,S]=m.useState("sandbox"),[T,C]=m.useState(""),[A,P]=m.useState(!1),[E,_]=m.useState("Preparing publish..."),[I,D]=m.useState(null),[M,B]=m.useState(null),[$,K]=m.useState(null),[R,Y]=m.useState(null),[Z,O]=m.useState(!1),[ne,oe]=m.useState(null),[he,ae]=m.useState(!1);m.useState(""),m.useState(!1);const[ve,re]=m.useState(null),[se,le]=m.useState(null),[te,We]=m.useState(null),[Me,Te]=m.useState(!1),[Ee,st]=m.useState(""),[xt,on]=m.useState("iad1"),[Yt,mt]=m.useState("idle"),[ln,at]=m.useState(null),[gt,$t]=m.useState(null),[ue,je]=m.useState(null),ct=m.useMemo(()=>kxe(n==null?void 0:n.name),[n==null?void 0:n.name]);m.useEffect(()=>{if(!e||!(n!=null&&n.id))return;(async()=>{const{count:rt}=await G.from("db_connections").select("id",{count:"exact",head:!0}).eq("project_id",n.id);ae((rt||0)>0);const{data:fe}=await G.from("project_settings").select("branding").eq("project_id",n.id).single();fe&&fe.branding?b(fe.branding):b({showBadge:!0,faviconUrl:null})})()},[e,n==null?void 0:n.id]);const it=s&&s.tables&&s.tables.length>0||he;m.useEffect(()=>{if(!e||!(n!=null&&n.id))return;O(!1),(async()=>{const{data:rt}=await G.from("project_settings").select("vercel_project_id, vercel_custom_domain, vercel_deploy_url").eq("project_id",n.id).single();if(rt){const fe=rt.vercel_project_id||null,lt=rt.vercel_deploy_url||null,yt=rt.vercel_custom_domain||null,zt=yt?lp(yt):null;yt&&zt&&yt!==zt&&G.from("project_settings").update({vercel_custom_domain:zt}).eq("project_id",n.id).then(({error:qt})=>{qt&&console.warn("[deploy-dialog] heal vercel_custom_domain failed:",qt.message)});const Fe=!!zt&&zt.endsWith(`.${Zi}`);B(fe),K(lt),Y(Fe?zt:null),le(Fe?null:zt),C(Fe&&zt?zt.replace(`.${Zi}`,""):""),st(!Fe&&zt?zt:""),S(!Fe&&zt?"production":"sandbox")}O(!0)})()},[e,n==null?void 0:n.id]),m.useEffect(()=>{if(!Z||!e||A||v==="deploying"||N)return;if(!!M&&(!!R||!!se)){if(S(se?"production":"sandbox"),!I&&($||R||se)){const rt=$||(R?`https://${R}`:"")||(se?`https://${se}`:"");rt&&D({id:"persisted",url:rt,projectId:M})}k("done");return}if(k("choose-mode"),se){S("production");return}if(R){S("sandbox");return}!T&&ct.length>0&&C(ct[0])},[Z,e,se,R,T,ct,M,$,I,A,v]);const q=async(Ae,rt={})=>{const{data:fe,error:lt}=await G.functions.invoke("vercel-deploy",{body:{action:Ae,...rt}});if(lt)throw new Error(lt.message);if(fe!=null&&fe.error)throw new Error(fe.error);return fe},Nt=async Ae=>{let lt=0;for(;lt<12e4;){const yt=await q("status",{deploymentId:Ae});if((yt==null?void 0:yt.readyState)==="READY"||(yt==null?void 0:yt.readyState)==="ERROR"||(yt==null?void 0:yt.readyState)==="CANCELED")return yt;await new Promise(zt=>setTimeout(zt,2e3)),lt+=2e3}return q("status",{deploymentId:Ae})},U=Ae=>{const rt=(y==null?void 0:y.faviconUrl)||"/favicon.png";return!Ae.includes('rel="icon"')&&Ae.includes("</head>")&&(Ae=Ae.replace("</head>",`  <link rel="icon" href="${rt}" type="image/png">
8025</head>`)),(y==null?void 0:y.showBadge)!==!1&&Ae.includes("</body>")&&(Ae=Ae.replace("</body>",`<a href="https://studiojungle.ai" target="_blank" rel="noopener noreferrer" style="position:fixed;bottom:12px;right:12px;z-index:9999;background:rgba(0,0,0,0.75);color:#fff;padding:6px 12px;border-radius:20px;font-size:11px;font-family:system-ui,sans-serif;display:flex;align-items:center;gap:6px;backdrop-filter:blur(4px);box-shadow:0 2px 8px rgba(0,0,0,0.2);text-decoration:none;cursor:pointer;transition:opacity 0.2s;" onmouseover="this.style.opacity='0.8'" onmouseout="this.style.opacity='1'"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>Built with Studiojungle</a>
8026</body>`)),Ae},Ne=(Ae,rt="")=>{var qt,fr;const fe=[];for(const Jt of Ae){const _t=rt?`${rt}/${Jt.name}`:Jt.name;if(Jt.type==="folder"&&Jt.children)fe.push(...Ne(Jt.children,_t));else if(Jt.type==="file"&&Jt.content){const z=_t.endsWith(".html")?U(Jt.content):Jt.content;fe.push({path:_t,content:z})}}const lt=fe.some(Jt=>/\.(tsx|jsx)$/.test(Jt.path)),yt=fe.some(Jt=>Jt.path==="package.json"),zt=fe.some(Jt=>/vite\.config\.(ts|js|mjs)$/.test(Jt.path));if(lt&&!yt){const Jt=((qt=n==null?void 0:n.name)==null?void 0:qt.toLowerCase().replace(/[^a-z0-9]+/g,"-"))||"studio-app",_t=fe.map(ee=>ee.content).join(`
8027`),z={react:"^18.3.1","react-dom":"^18.3.1"};if(/from\s+['"]react-router/.test(_t)&&(z["react-router-dom"]="^6.30.0"),/from\s+['"]lucide-react/.test(_t)&&(z["lucide-react"]="^0.462.0"),/from\s+['"]@supabase\/supabase-js/.test(_t)&&(z["@supabase/supabase-js"]="^2.97.0"),/from\s+['"]recharts/.test(_t)&&(z.recharts="^2.15.0"),/from\s+['"]date-fns/.test(_t)&&(z["date-fns"]="^3.6.0"),/from\s+['"]sonner/.test(_t)&&(z.sonner="^1.7.0"),/from\s+['"]@radix-ui/.test(_t)){const ee=_t.match(/from\s+['"](@radix-ui\/[^'"]+)['"]/g)||[];for(const de of ee){const ge=(fr=de.match(/@radix-ui\/[^'"]+/))==null?void 0:fr[0];ge&&(z[ge]="latest")}}
8027/from\s+['"]class-variance-authority/.test(_t)&&(z["class-variance-authority"]="^0.7.1"),/from\s+['"]clsx/.test(_t)&&(z.clsx="^2.1.1"),/from\s+['"]tailwind-merge/.test(_t)&&(z["tailwind-merge"]="^2.6.0"),/from\s+['"]@tanstack\/react-query/.test(_t)&&(z["@tanstack/react-query"]="^5.83.0"),/from\s+['"]zod/.test(_t)&&(z.zod="^3.25.0"),/from\s+['"]react-hook-form/.test(_t)&&(z["react-hook-form"]="^7.61.0"),fe.push({path:"package.json",content:JSON.stringify({name:Jt,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"tsc -b && vite build",preview:"vite preview"},dependencies:z,devDependencies:{"@vitejs/plugin-react":"^4.5.0",typescript:"^5.8.0",vite:"^5.4.19","@types/react":"^18.3.0","@types/react-dom":"^18.3.0",tailwindcss:"^3.4.17",postcss:"^8.5.0",autoprefixer:"^10.4.21"}},null,2)})}if(lt&&!zt&&fe.push({path:"vite.config.ts",content:`import { defineConfig } from 'vite';
8028import react from '@vitejs/plugin-react';
8029
8030export default defineConfig({
8031  plugins: [react()],
8032  resolve: {
8033    alias: {
8034      '@': '/src',
8035    },
8036  },
8037});
8038`}),lt&&!fe.some(Jt=>Jt.path==="tsconfig.json")&&fe.push({path:"tsconfig.json",content:JSON.stringify({compilerOptions:{target:"ES2020",useDefineForClassFields:!0,lib:["ES2020","DOM","DOM.Iterable"],module:"ESNext",skipLibCheck:!0,moduleResolution:"bundler",allowImportingTsExtensions:!0,isolatedModules:!0,moduleDetection:"force",noEmit:!0,jsx:"react-jsx",strict:!0,noUnusedLocals:!1,noUnusedParameters:!1,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}),lt&&!fe.some(Jt=>Jt.path==="postcss.config.js")&&fe.push({path:"postcss.config.js",content:`export default {
8039  plugins: {
8040    tailwindcss: {},
8041    autoprefixer: {},
8042  },
8043};
8044`}),lt&&!fe.some(Jt=>Jt.path==="tailwind.config.js"||Jt.path==="tailwind.config.ts")&&fe.push({path:"tailwind.config.js",content:Vj}),lt){if(fe.some(_t=>_t.path==="src/vite-env.d.ts")||fe.push({path:"src/vite-env.d.ts",content:`/// <reference types="vite/client" />
8045`}),!fe.some(_t=>_t.path==="src/main.tsx"||_t.path==="src/main.jsx")){const _t=fe.find(Ie=>/App\.(tsx|jsx)$/.test(Ie.path)),z=_t?_t.path.replace(/^src\//,"./").replace(/\.(tsx|jsx)$/,""):"./App",ee=fe.some(Ie=>/from\s+['"]react-router/.test(Ie.content||"")),de=ee?`import { BrowserRouter } from 'react-router-dom';
8046`:"",ge=ee?"<BrowserRouter><App /></BrowserRouter>":"<App />",Se=fe.some(Ie=>Ie.path==="src/index.css");fe.push({path:"src/main.tsx",content:`import React from 'react';
8047import ReactDOM from 'react-dom/client';
8048${de}import App from '${z}';
8049${Se?`import './index.css';
8050`:""}
8051ReactDOM.createRoot(document.getElementById('root')!).render(
8052  <React.StrictMode>
8053    ${ge}
8054  </React.StrictMode>,
8055);
8056`})}const Jt=fe.find(_t=>_t.path==="index.html");Jt?Jt.content.includes('id="root"')||(Jt.content=`<!DOCTYPE html>
8057<html lang="en">
8058<head>
8059<meta charset="utf-8" />
8060<meta name="viewport" content="width=device-width, initial-scale=1" />
8061<title>${(n==null?void 0:n.name)||"App"}</title>
8062</head>
8063<body>
8064<div id="root"></div>
8065<script type="module" src="/src/main.tsx"><\/script>
8066</body>
8067</html>`):fe.push({path:"index.html",content:`<!DOCTYPE html>
8068<html lang="en">
8069<head>
8070<meta charset="utf-8" />
8071<meta name="viewport" content="width=device-width, initial-scale=1" />
8072<title>${(n==null?void 0:n.name)||"App"}</title>
8073</head>
8074<body>
8075<div id="root"></div>
8076<script type="module" src="/src/main.tsx"><\/script>
8077</body>
8078</html>`})}if(!lt&&!fe.some(_t=>_t.path==="index.html")){const _t=fe.find(z=>z.path.endsWith(".html"));if(_t)fe.push({path:"index.html",content:_t.content});else{const z=Ft();fe.push({path:"index.html",content:U(z)})}}if(!fe.some(Jt=>Jt.path==="vercel.json")){const Jt=fe.filter(z=>z.path.endsWith(".html")&&z.path!=="index.html"),_t=[];if(it){const z="https://xfmlsevleobdlnjqxmdi.supabase.co",ee=(n==null?void 0:n.id)||"";_t.push({source:"/api/:path*",destination:`${z}/functions/v1/autodb-rest/${ee}/:path*`}),_t.push({source:"/api-docs",destination:`${z}/functions/v1/api-docs/${ee}`})}for(const z of Jt){const ee=z.content.match(/<!--\s*route:\s*(\/[^\s]*)\s*-->/);ee&&ee[1]!=="/"&&_t.push({source:ee[1],destination:`/${z.path}`})}_t.push({source:"/(.*)",destination:"/index.html"}),fe.push({path:"vercel.json",content:JSON.stringify({rewrites:_t},null,2)})}return Txe(Exe(Pxe(Axe(fe))))},Ft=()=>{const Ae=(n==null?void 0:n.name)||"My App";return`<!DOCTYPE html>
8079<html lang="en">
8080<head>
8081<meta charset="utf-8">
8082<meta name="viewport" content="width=device-width, initial-scale=1">
8083<title>${Ae}</title>
8084<style>
8085*{box-sizing:border-box;margin:0;padding:0}
8086body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#f8fafc;color:#334155}
8087.container{text-align:center;padding:2rem}
8088h1{font-size:2rem;font-weight:700;margin-bottom:0.5rem}
8089p{color:#64748b;font-size:1rem}
8090</style>
8091</head>
8092<body>
8093<div class="container">
8094<h1>${Ae}</h1>
8095<p>Your app is live! Add more content to see it here.</p>
8096</div>
8097</body>
8098</html>`},Zt=m.useCallback(async(Ae,rt,fe)=>{if(!(n!=null&&n.id))return;const lt={project_id:n.id,vercel_project_id:Ae,vercel_deploy_url:rt};fe!==void 0&&(lt.vercel_custom_domain=fe),await G.from("project_settings").upsert(lt,{onConflict:"project_id"})},[n==null?void 0:n.id]),Ke=m.useCallback(async()=>{mt("pushing"),$t(null),je(null);try{const Ae=Dh(d==null?void 0:d.id).token;if(!Ae){$t("Connect GitHub first to auto-push code after publishing."),mt("skipped");return}let rt=null,fe=null,lt="main",yt=!1;if(n!=null&&n.id){const{data:fr,error:Jt}=await G.from("projects").select("github_owner, github_repo, github_branch, github_auto_push").eq("id",n.id).maybeSingle();!Jt&&fr&&(rt=fr.github_owner||null,fe=fr.github_repo||null,lt=fr.github_branch||"main",yt=!!fr.github_auto_push)}if(n!=null&&n.id&&(rt||(rt=localStorage.getItem(`github-owner::${n.id}`)),fe||(fe=localStorage.getItem(`github-repo::${n.id}`)),lt||(lt=localStorage.getItem(`github-branch::${n.id}`)||"main"),yt||(yt=localStorage.getItem(`github-auto-push::${n.id}`)==="true")),!rt||!fe){$t("No GitHub repository is linked for this project yet."),mt("skipped");return}if(!yt){je({owner:rt,repo:fe,branch:lt,files:0}),$t(`GitHub is linked to ${rt}/${fe}, but auto-push is off.`),mt("skipped");return}const zt=Ne(r);if(zt.length===0){$t("No files were available to push."),mt("skipped");return}const{data:Fe,error:qt}=await G.functions.invoke("github-push",{body:{action:"push",token:Ae,owner:rt,repo:fe,files:zt,commitMessage:`Deploy: ${new Date().toLocaleStr
8098ing()}`,branch:lt}});if(qt||Fe!=null&&Fe.error){console.error("GitHub auto-push failed:",(qt==null?void 0:qt.message)||(Fe==null?void 0:Fe.error)),$t((qt==null?void 0:qt.message)||(Fe==null?void 0:Fe.error)||"Auto-push failed."),mt("error");return}at((Fe==null?void 0:Fe.html_url)||null),je({owner:rt,repo:fe,branch:lt,files:zt.length,commitSha:(Fe==null?void 0:Fe.commit_sha)||(Fe==null?void 0:Fe.sha)||null}),$t(`Pushed ${zt.length} files to ${rt}/${fe}.`),mt("done")}catch(Ae){console.error("GitHub auto-push error:",Ae),$t(Ae instanceof Error?Ae.message:"Auto-push failed."),mt("error")}},[d==null?void 0:d.id,r,n==null?void 0:n.id]),ie=m.useCallback(async()=>{var rt;const Ae=!!M;P(!0),_(Ae?"Preparing re-publish...":"Preparing publish..."),D(null),mt("idle"),at(null),$t(null),je(null),k("deploying");try{const fe=g.current,lt=Ne(fe);if(lt.length===0){Mt({title:"No files to publish",description:"Generate some code first."}),P(!1),k("choose-mode");return}const yt=uM(n==null?void 0:n.name);let zt;if(n!=null&&n.id){const{data:{user:z}}=await G.auth.getUser();if(z){const{data:ee}=await G.from("project_deployments").insert({project_id:n.id,user_id:z.id,target:"vercel",status:"pending",metadata:{mode:w,file_count:lt.length}}).select("id").single();zt=ee==null?void 0:ee.id}}let Fe,qt;try{_("Running build check...");const z=[],ee=await Nxe(lt,de=>{z.push(de),z.length>160&&z.shift()},void 0,{projectId:(n==null?void 0:n.id)||null});if(!ee.success)throw cM(ee.output||z.join(`
8099`),12).forEach(ge=>c(`BUILD: ${ge}`)),new Error(jxe(ee.exit,ee.output,z));if(_(`Uploading build to StudioJungle Cloud (${xt})…`),Fe=await q("deploy",{projectName:yt,files:lt,region:xt,...M?{projectId:M}:{}}),D(Fe),B(Fe.projectId),K(Fe.url),_("Waiting for deployment to become ready..."),qt=await Nt(Fe.id),(qt==null?void 0:qt.readyState)!=="READY"){let de=(qt==null?void 0:qt.errorMessage)||(qt==null?void 0:qt.errorCode)||`Deployment ended with ${(qt==null?void 0:qt.readyState)||"unknown status"}`;if(/exit(ed)? with|build failed/i.test(de))try{const ge=await q("events",{deploymentId:Fe.id,limit:200}),De=(Array.isArray(ge==null?void 0:ge.events)?ge.events:Array.isArray(ge)?ge:[]).map(Ce=>{var xn,et,wt;return((xn=Ce==null?void 0:Ce.payload)==null?void 0:xn.text)||(Ce==null?void 0:Ce.text)||((wt=(et=Ce==null?void 0:Ce.payload)==null?void 0:et.info)==null?void 0:wt.text)||""}).filter(Ce=>typeof Ce=="string"&&Ce.trim().length>0).filter(Ce=>/error|failed|cannot|unresolved|missing|✘|✖/i.test(Ce)).slice(-8).join(`
8100`);De&&(de=`${de}
8101
8102Build log:
8103${De}`)}catch(ge){console.warn("Could not fetch build events:",ge)}throw new Error(de)}}catch(z){throw zt&&await G.from("project_deployments").update({status:"failed",error_message:z instanceof Error?z.message:String(z)}).eq("id",zt),z}zt&&await G.from("project_deployments").update({status:"success",deploy_url:(qt==null?void 0:qt.url)||Fe.url,metadata:{mode:w,vercel_project_id:Fe.projectId}}).eq("id",zt);let fr=null;if(w==="sandbox"){const z=T?`${T.toLowerCase().replace(/[^a-z0-9-]/g,"")}.${Zi}`:null;if(z){_("Assigning preview URL...");try{await q("add-domain",{projectId:Fe.projectId,domain:z})}catch(ee){console.error("Sandbox wildcard domain error:",ee)}fr=z,Y(z),le(null),_("Saving publish settings..."),await Zt(Fe.projectId,Fe.url,z)}else _("Saving publish settings..."),await Zt(Fe.projectId,Fe.url)}else{const z=lp(Ee)||se;if(z){_("Connecting custom domain...");try{await q("add-domain",{projectId:Fe.projectId,domain:z})}catch(ee){console.error("Production domain error:",ee)}fr=z,le(z),Y(null),_("Saving publish settings..."),await Zt(Fe.projectId,Fe.url,z)}else _("Saving publish settings..."),await Zt(Fe.projectId,Fe.url)}if(n!=null&&n.id){_("Syncing auth URL...");try{const{data:z,error:ee}=await G.functions.invoke("sync-supabase-auth-url",{body:{projectId:n.id}});ee?console.warn("[deploy-dialog] auth URL sync failed:",ee.message):z!=null&&z.error?console.warn("[deploy-dialog] auth URL sync returned error:",z.error):z!=null&&z.site_url&&console.log("[deploy-dialog] auth URL synced to:",z.site_url)}catch(z){console.warn("[deploy-dialog] auth URL sync threw:",z)}}_("Published successfully."),j(!1),k("done"),f.refresh();const Jt=!!M,_t=w==="sandbox"?"Preview":"Production";Mt({title:Jt?`🚀 ${_t} Updated!`:`🚀 ${_t} Published!`,description:fr?`https://${fr}`:(qt==null?void 0:qt.url)||Fe.url});try{const ee=g.current.flatMap(function de(ge){return ge.type==="folder"&&ge.children?ge.children.flatMap(de):[ge]}).find(de=>de.name==="index.html"&&de.content);ee!=null&&ee.content&&p(ee.content)}catch{console.warn("Post-deploy thumbnail capture failed (non-critical)")}Ke()}catch(fe){_("Publish failed.");const lt=fe&&fe.message||"Publish failed";if(/build failed/i.test(lt)&&(u!=null&&u.current)){Mt({title:"Build failed — Repair Agent is patching it now",description:lt.split(`
8104`).slice(0,4).join(`
8105`),variant:"destructive"});try{t(!1),(rt=u.current)==null||rt.call(u,`🔧 The publish build just failed. Fix these errors so the next publish succeeds. Do NOT redesign — minimal patches only.
8106
8107${lt}`)}catch{}}else Mt({title:"Publish failed",description:lt,variant:"destructive"});k("choose-mode")}finally{P(!1)}},[n==null?void 0:n.name,M,T,Ee,se,Zt,w,Ke,Nt,p,c,u,t]),we=()=>{if(w==="sandbox"&&!T.trim()||w==="production"&&!Ee.trim()&&!se)return;const Ae=h.plan!=="none",rt=Ae?"/studio/billing":"/pricing";if(!M){const lt=h.quotas.maxPublishedProjects;if(Number.isFinite(lt)&&f.publishedProjects>=lt){Mt({title:Ae?"Published-project limit reached":"Pick a plan to publish",description:Ae?`Your ${h.label} plan includes ${lt} published project${lt===1?"":"s"}. You currently have ${f.publishedProjects}. Switch tier to publish more.`:"Publishing requires a Starter, Pro, or Studio plan. Pick one to ship this project.",variant:"destructive"}),V(),x(rt);return}}if(w==="production"&&Ee.trim()&&!se){const lt=h.quotas.maxCustomDomains;if(Number.isFinite(lt)&&f.customDomains>=lt){Mt({title:Ae?"Custom-domain limit reached":"Pick a plan for custom domains",description:Ae?`Your ${h.label} plan supports ${lt} custom domain${lt===1?"":"s"}. You have ${f.customDomains}. Switch tier to add more.`:"Custom domains require a Starter, Pro, or Studio plan. Pick one to continue.",variant:"destructive"}),V(),x(rt);return}}ie()},Je=async()=>
8107{const Ae=se,rt=M||(I==null?void 0:I.projectId);if(!(!Ae||!rt)){Te(!0);try{const fe=await q("verify-domain",{projectId:rt,domain:Ae});We({verified:!!fe.verified,misconfigured:!!fe.misconfigured,dnsConfigured:!!fe.dnsConfigured,checkedAt:Date.now()}),fe.dnsConfigured?Mt({title:"✅ DNS verified",description:`${Ae} is now connected.`}):fe.misconfigured?Mt({title:"DNS misconfigured",description:"Check the records below — propagation can take up to 72h."}):Mt({title:"DNS still propagating",description:"Hold tight — most domains resolve within 30 min."})}catch(fe){Mt({title:"Verification failed",description:fe.message,variant:"destructive"})}finally{Te(!1)}}},ot=Ae=>{navigator.clipboard.writeText(Ae),Mt({title:"Copied!",description:Ae})},V=()=>{A||(t(!1),setTimeout(()=>{D(null),oe(null),re(null),j(!1),mt("idle"),at(null),$t(null),je(null)},300))},ye=!!M,me=R||(T?`${T}.${Zi}`:null),_e=me?`https://${me}`:(I==null?void 0:I.url)||$,dt=se?`https://${lp(se)}`:null,kt=w==="sandbox"?_e:dt||(I==null?void 0:I.url)||$,wn=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(T.toLowerCase()),kn=A?"deploying":v;return a.jsx(yo,{open:e,onOpenChange:V,children:a.jsxs(Fi,{className:"sm:max-w-lg p-0 overflow-hidden border-0 shadow-2xl",children:[kn==="choose-mode"&&a.jsxs("div",{className:"p-6",children:[a.jsxs(Bi,{className:"pb-4",children:[a.jsxs(La,{className:"flex items-center gap-2.5 text-lg",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center",children:a.jsx(Es,{className:"w-4 h-4 text-primary"})}),ye?"Re-publish":"Publish Your App"]}),a.jsx(ol,{children:"Choose how you want to deploy your app."})]}),a.jsxs("div",{className:"space-y-4 pt-1",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{onClick:()=>S("sandbox"),className:L("group relative p-4 rounded-xl border text-left transition-all",w==="sandbox"?"border-primary/50 bg-primary/[0.04] shadow-sm ring-2 ring-primary/15":"border-border hover:border-primary/30 bg-card"),children:[!R&&!se&&a.jsx("span",{className:"absolute top-2.5 right-2.5 text-[9px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-primary/15 text-primary",children:"Free"}),a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx("div",{className:L("w-7 h-7 rounded-lg flex items-center justify-center",w==="sandbox"?"bg-primary/15 text-primary":"bg-secondary text-muted-foreground"),children:a.jsx(ys,{className:"w-3.5 h-3.5"})}),a.jsx("span",{className:"text-sm font-semibold",children:"Sandbox"})]}),a.jsxs("p",{className:"text-[11.5px] text-muted-foreground leading-snug",children:["Free preview URL on ",a.jsx("span",{className:"font-mono text-foreground/80",children:Zi}),". Share it with anyone."]}),me&&a.jsx("div",{className:"mt-2 pt-2 border-t border-border/60",children:a.jsx("p",{className:"text-[10px] font-mono text-muted-foreground truncate",children:me})})]}),a.jsxs("button",{onClick:()=>{if(!h.features.productionDeploy){t(!1),x("/studio/billing");return}S("production")},className:L("group relative p-4 rounded-xl border text-left transition-all",w==="production"?"border-amber-500/50 bg-amber-500/[0.04] shadow-sm ring-2 ring-amber-500/15":"border-border hover:border-amber-500/30 bg-card"),children:[!h.features.productionDeploy&&a.jsxs("span",{className:"absolute top-2.5 right-2.5 inline-flex items-center gap-1 text-[9px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-700",children:[a.jsx(Bs,{className:"w-2.5 h-2.5"})," Pro"]}),a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx("div",{className:L("w-7 h-7 rounded-lg flex items-center justify-center",w==="production"?"bg-amber-500/15 text-amber-600":"bg-secondary text-muted-foreground"),children:a.jsx(hr,{className:"w-3.5 h-3.5"})}),a.jsx("span",{className:"text-sm font-semibold",children:"Production"})]}),a.jsx("p",{className:"text-[11.5px] text-muted-foreground leading-snug",children:h.features.productionDeploy?"Your own custom domain. For live, customer-facing apps.":"Custom domains for live apps. Pro plan required."}),se&&a.jsx("div",{className:"mt-2 pt-2 border-t border-border/60",children:a.jsx("p",{className:"text-[10px] font-mono text-muted-foreground truncate",children:se})})]})]}),!f.loading&&Number.isFinite(h.quotas.maxPublishedProjects)&&a.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center justify-between gap-3 rounded-lg border bg-card/40 px-3 py-2",children:[a.jsxs("span",{children:["Published projects: ",a.jsx("span",{className:"font-mono text-foreground",children:f.publishedProjects})," / ",a.jsx("span",{className:"font-mono text-foreground",children:h.quotas.maxPublishedProjects})," ","(",h.label,")"]}),f.publishedProjects>=h.quotas.maxPublishedProjects&&a.jsx("button",{onClick:()=>{V(),x(h.plan==="none"?"/pricing":"/studio/billing")},className:"text-primary font-medium hover:underline",children:h.plan==="none"?"Pick a plan →":"Switch tier →"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-semibold text-muted-foreground mb-2 block uppercase tracking-wider",children:"Deploy Region"}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:[{id:"iad1",label:"🇺🇸 US East",city:"Washington D.C."},{id:"sfo1",label:"🇺🇸 US West",city:"San Francisco"},{id:"cdg1",label:"🇪🇺 Europe",city:"Paris"},{id:"hnd1",label:"🇯🇵 Asia",city:"Tokyo"},{id:"syd1",label:"🇦🇺 Oceania",city:"Sydney"}].map(Ae=>a.jsx("button",{onClick:()=>on(Ae.id),className:L("px-3 py-1.5 rounded-lg text-xs font-medium transition-all border",xt===Ae.id?"bg-primary text-primary-foreground border-primary shadow-sm":"bg-card text-muted-foreground border-border hover:border-primary/30 hover:text-foreground"),children:Ae.label},Ae.id))})]}),w==="sandbox"&&!R&&a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-semibold text-muted-foreground mb-2 block uppercase tracking-wider",children:"Subdomain"}),a.jsxs("div",{className:"flex items-center gap-0",children:[a.jsx(Cn,{value:T,onChange:Ae=>{C(Ae.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),oe(null)},onKeyDown:Ae=>Ae.key==="Enter"&&wn&&we(),placeholder:"my-awesome-app",className:"rounded-r-none border-r-0 font-mono text-sm h-10"}),a.jsxs("div",{className:"h-10 px-3 flex items-center bg-muted border border-l-0 rounded-r-md text-xs text-muted-foreground font-mono whitespace-nowrap",children:[".",Zi]})]}),T&&!wn&&a.jsx("p",{className:"text-[11px] text-destructive mt-1.5",children:"Only lowercase letters, numbers, and hyphens. Must start/end with a letter or number."}),T&&wn&&a.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Your sandbox → ",a.jsxs("span",{className:"font-mono text-foreground font-medium",children:["https://",T,".",Zi]})]}),a.jsxs("div",{className:"mt-3",children:[a.jsxs("label",{className:"text-[11px] font-medium text-muted-foreground mb-2 flex items-center gap-1",children:[a.jsx(Dn,{className:"w-3 h-3"})," Suggestions"]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:ct.map(Ae=>a.jsx("button",{onClick:()=>{C(Ae),oe(null)},className:L("px-3 py-1.5 rounded-full text-xs font-medium transition-all border max-w-full truncate",T===Ae?"bg-primary text-primary-foreground border-primary shadow-sm":"bg-card text-muted-foreground border-border hover:border-primary/30 hover:text-foreground"),children:Ae},Ae))})]})]}),w==="production"&&a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-semibold text-muted-foreground mb-2 block uppercase tracking-wider",children:"Your Domain"}),se?a.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-primary/5 border border-primary/20",children:[a.jsx(Wn,{className:"w-3.5 h-3.5 text-primary shrink-0"}),a.jsx("span",{className:"font-mono text-sm text-foreground font-medium",children:se})]}):a.jsxs("div",{children:[a.jsx(Cn,{value:Ee,onChange:Ae=>{st(Ae.target.value.toLowerCase()),oe(null)},onKeyDown:Ae=>Ae.key==="Enter"&&Ee.trim()&&we(),placeholder:"app.yourdomain.com",className:"font-mono text-sm h-10"}),Ee.trim()&&a.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Your app → ",a.jsxs("span",{className:"font-mono text-foreground font-medium",children:["https://",Ee.trim()]})]})]})]}),ne&&a.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg bg-destructive/5 border border-destructive/20 text-xs text-destructive",children:[a.jsx(is,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),a.jsx("span",{children:ne})]}),(()=>{const Ae=[{id:"iad1",label:"🇺🇸 US East",city:"Washington D.C."},{id:"sfo1",label:"🇺🇸 US West",city:"San Francisco"},{id:"cdg1",label:"🇪🇺 Europe",city:"Paris"},{id:"hnd1",label:"🇯🇵 Asia",city:"Tokyo"},{id:"syd1",label:"🇦🇺 Oceania",city:"Sydney"}].find(fe=>fe.id===xt),rt=w==="sandbox"?R||(T?`${T}.${Zi}`:null):se||Ee.trim()||null;return rt?a.jsxs("div",{className:"rounded-lg border bg-card/50 px-3 py-2.5 text-xs flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground
8107/70 mb-0.5",children:"About to publish"}),a.jsx("div",{className:"font-mono text-foreground truncate",children:rt})]}),Ae&&a.jsxs("div",{className:"shrink-0 text-right",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Region"}),a.jsx("div",{className:"font-medium text-foreground",children:Ae.label})]})]}):null})(),a.jsxs(Q,{onClick:we,disabled:w==="sandbox"&&!R&&(!T.trim()||!wn)||w==="production"&&!se&&!Ee.trim()||A,className:"w-full gap-2 h-11 text-sm font-semibold truncate",children:[A?a.jsx(ze,{className:"w-4 h-4 animate-spin shrink-0"}):w==="sandbox"?a.jsx(ys,{className:"w-4 h-4 shrink-0"}):a.jsx(Es,{className:"w-4 h-4 shrink-0"}),a.jsx("span",{className:"truncate",children:w==="sandbox"?ye&&R?`Update ${R}`:T?`Deploy to ${T}.${Zi}`:"Deploy to Sandbox":se?`Re-publish to ${se}`:Ee.trim()?`Publish to ${Ee.trim()}`:"Publish to Production"})]})]})]}),kn==="deploying"&&a.jsxs("div",{className:"p-6",children:[a.jsx(rw,{children:a.jsx(La,{children:"Deploying"})}),a.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-5",children:[a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-20 h-20 rounded-2xl bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center",children:a.jsx(ze,{className:"w-9 h-9 text-primary animate-spin"})}),a.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-primary/20 animate-pulse"})]}),a.jsxs("div",{className:"text-center space-y-1",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:w==="sandbox"?ye?"Updating preview...":"Deploying preview...":ye?"Deploying updates...":"Publishing to your domain..."}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:w==="sandbox"?me&&a.jsx("span",{className:"font-mono",children:me}):(se||Ee.trim())&&a.jsx("span",{className:"font-mono",children:se||Ee.trim()})})]}),a.jsxs("div",{className:"w-full rounded-xl border bg-muted/30 p-3 text-left",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-foreground",children:[a.jsx(ze,{className:"h-3.5 w-3.5 animate-spin text-primary"}),a.jsx("span",{children:E})]}),a.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:"Keep this window open. First publish can take 30-120 seconds while the build, upload, and domain steps finish."})]})]})]}),kn==="done"&&a.jsxs("div",{children:[a.jsx(rw,{children:a.jsx(La,{children:"Published"})}),a.jsx("div",{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5",children:a.jsxs("div",{className:"flex items-start gap-4",children:[a.jsx("div",{className:"w-12 h-12 rounded-2xl bg-primary/15 flex items-center justify-center shrink-0 ring-4 ring-primary/5",children:a.jsx(Wn,{className:"w-6 h-6 text-primary"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"text-base font-bold text-foreground",children:w==="sandbox"?ye?"Preview updated!":"Preview deployed!":ye?"Successfully updated!":"Published!"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:w==="sandbox"?"Your preview is live and ready to share.":"Your app is live and ready to share."})]})]})}),a.jsxs("div",{className:"px-6 pb-6 space-y-4",children:[a.jsx("div",{className:"flex items-center gap-2",children:a.jsx("span",{className:L("text-[10px] font-semibold uppercase tracking-wider px-2.5 py-1 rounded-full",w==="sandbox"?"bg-amber-500/10 text-amber-600":"bg-primary/10 text-primary"),children:w==="sandbox"?"👁️ Preview":"🚀 Production"})}),a.jsx("div",{className:"p-3.5 rounded-xl bg-card border-2 border-primary/20 shadow-sm",children:a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:w==="sandbox"?"Preview URL":"Live URL"}),a.jsx("a",{href:kt||"#",target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline font-mono font-medium truncate block",children:kt})]}),a.jsxs("div",{className:"flex gap-1 shrink-0",children:[a.jsx(Q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>ot(kt||""),children:a.jsx(gs,{className:"w-3.5 h-3.5"})}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-8 w-8",asChild:!0,children:a.jsx("a",{href:kt||"#",target:"_blank",rel:"noopener noreferrer",children:a.jsx(Is,{className:"w-3.5 h-3.5"})})})]})]})}
8107),a.jsxs("div",{className:L("rounded-xl border overflow-hidden",Yt==="done"?"border-primary/25 bg-primary/[0.04]":Yt==="error"?"border-destructive/20 bg-destructive/[0.03]":"bg-card/50"),children:[a.jsxs("div",{className:"px-3.5 py-2.5 border-b bg-background/50 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:L("h-7 w-7 rounded-lg flex items-center justify-center",Yt==="done"?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"),children:Yt==="done"?a.jsx(to,{className:"w-3.5 h-3.5"}):a.jsx(oo,{className:"w-3.5 h-3.5"})}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs font-semibold text-foreground",children:"GitHub Sync"}),(ue==null?void 0:ue.owner)&&(ue==null?void 0:ue.repo)&&a.jsxs("p",{className:"text-[10px] text-muted-foreground font-mono",children:[ue.owner,"/",ue.repo]})]})]}),Yt==="done"&&a.jsx("span",{className:"text-[10px] font-semibold text-primary bg-primary/10 px-2 py-0.5 rounded-full",children:"Code pushed"}),Yt==="pushing"&&a.jsxs("span",{className:"text-[10px] font-medium text-amber-600 bg-amber-500/10 px-2 py-0.5 rounded-full flex items-center gap-1",children:[a.jsx(ze,{className:"w-2.5 h-2.5 animate-spin"})," Pushing code"]}),Yt==="skipped"&&a.jsx("span",{className:"text-[10px] font-medium text-muted-foreground bg-muted px-2 py-0.5 rounded-full",children:ue?"Auto-push off":"Needs setup"}),Yt==="error"&&a.jsx("span",{className:"text-[10px] font-medium text-destructive bg-destructive/10 px-2 py-0.5 rounded-full",children:"Push failed"})]}),a.jsx("div",{className:"p-3.5 space-y-3",children:Yt==="done"?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[11px] text-foreground font-medium",children:"Your code is synced with GitHub and this preview is live."}),ue&&a.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[10px]",children:[a.jsxs("div",{className:"rounded-lg border bg-background/70 p-2",children:[a.jsx("p",{className:"text-muted-foreground",children:"Branch"}),a.jsx("p",{className:"mt-0.5 font-mono font-semibold truncate",children:ue.branch})]}),a.jsxs("div",{className:"rounded-lg border bg-background/70 p-2",children:[a.jsx("p",{className:"text-muted-foreground",children:"Files"}),a.jsx("p",{className:"mt-0.5 font-semibold",children:ue.files})]}),a.jsxs("div",{className:"rounded-lg border bg-background/70 p-2",children:[a.jsx("p",{className:"text-muted-foreground",children:"Commit"}),a.jsx("p",{className:"mt-0.5 font-mono font-semibold truncate",children:ue.commitSha?ue.commitSha.slice(0,7):"latest"})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[ln&&a.jsx(Q,{variant:"outline",size:"sm",className:"h-8 text-xs",asChild:!0,children:a.jsxs("a",{href:ln,target:"_blank",rel:"noopener noreferrer",children:[a.jsx(Is,{className:"w-3 h-3 mr-1.5"}),"View commit"]})}),a.jsxs(Q,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{V(),l("github")},children:[a.jsx(ni,{className:"w-3 h-3 mr-1.5"}),"GitHub settings"]})]})]}):Yt==="skipped"?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[11px] text-muted-foreground",children:gt||"Connect GitHub in the workspace to auto-push code on every publish."}),a.jsxs(Q,{type:"button",variant:"outline",size:"sm",onClick:()=>{V(),l("github")},className:"h-8 text-xs",children:[a.jsx(ni,{className:"w-3 h-3 mr-1.5"}),"Open GitHub settings"]})]}):Yt==="error"?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[11px] text-muted-foreground",children:gt||"Auto-push failed. You can manually push from the GitHub tab."}),a.jsxs(Q,{type:"button",variant:"outline",size:"sm",onClick:()=>{V(),l("github")},className:"h-8 text-xs",children:[a.jsx(oo,{className:"w-3 h-3 mr-1.5"}),"Review sync"]})]}):Yt==="pushing"?a.jsxs("p",{className:"text-[11px] text-muted-foreground flex items-center gap-2",children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"}),"Committing project files to your repository..."]}):a.jsx("p",{className:"text-[11px] text-muted-foreground",children:"GitHub sync runs after publish when a repository is linked and auto-push is enabled."})})]}),w==="sandbox"&&a.jsxs("div",{className:"rounded-xl border bg-card/50 p-3.5 flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Br,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Need your own domain?"})]}),a.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground leading-relaxed",children:"Keep this preview URL for sharing, or switch to Production and connect a custom domain."})]}),a.jsxs(Q,{variant:"default",size:"sm",className:"h-9 shrink-0 text-xs gap-1.5",onClick:()=>
8107{if(!h.features.productionDeploy){Mt({title:"Pro plan required",description:"Custom domains are available on the Pro plan. Redirecting to billing…"}),V(),x("/studio/billing");return}Mt({title:"Switching to Production setup",description:"Enter your custom domain on the next screen."}),S("production"),st(""),oe(null),j(!0),k("choose-mode")},children:[a.jsx(Br,{className:"w-3.5 h-3.5"}),"Connect custom domain"]})]}),w==="production"&&se&&(()=>{const Ae=lp(se),rt=Sxe(Ae),fe=rt.kind==="apex",lt=fe?"A":"CNAME",yt=rt.host,zt=fe?"76.76.21.21":"cname.vercel-dns.com",Fe=te,qt=Fe!=null&&Fe.dnsConfigured?{text:"Connected",cls:"text-emerald-700 bg-emerald-500/10"}:Fe!=null&&Fe.misconfigured?{text:"Misconfigured",cls:"text-rose-700 bg-rose-500/10"}:(Fe==null?void 0:Fe.verified)===!1||!Fe?{text:"Pending DNS",cls:"text-amber-700 bg-amber-500/10"}:{text:"Verifying…",cls:"text-muted-foreground bg-muted"};return a.jsxs("div",{className:"rounded-xl border bg-card/50 overflow-hidden",children:[a.jsxs("div",{className:"px-3.5 py-2.5 border-b bg-muted/30 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Br,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Custom Domain"}),a.jsx("span",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70",children:fe?"apex":"subdomain"})]}),a.jsx("span",{className:L("text-[10px] font-medium px-2 py-0.5 rounded-full",qt.cls),children:qt.text})]}),a.jsxs("div",{className:"p-3.5 space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[Fe!=null&&Fe.dnsConfigured?a.jsx(Wn,{className:"w-3.5 h-3.5 text-emerald-600 shrink-0"}):a.jsx(is,{className:"w-3.5 h-3.5 text-amber-600 shrink-0"}),a.jsx("span",{className:"font-mono text-foreground font-medium",children:Ae})]}),!(Fe!=null&&Fe.dnsConfigured)&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[a.jsx(is,{className:"w-3 h-3"}),a.jsx("span",{className:"text-[11px] font-semibold",children:fe?"Add this A record at your DNS provider":"Add this CNAME record at your DNS provider"})]}),a.jsx("div",{className:"p-2.5 rounded-lg bg-muted/50 border",children:a.jsxs("div",{className:"grid grid-cols-[64px_1fr] gap-x-2 gap-y-1 text-[11px] font-mono",children:[a.jsx("span",{className:"text-muted-foreground font-sans",children:"Type"}),a.jsx("span",{children:lt}),a.jsx("span",{className:"text-muted-foreground font-sans",children:"Name"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{children:yt}),a.jsx("button",{onClick:()=>ot(yt),className:"text-muted-foreground/50 hover:text-primary",children:a.jsx(gs,{className:"w-2.5 h-2.5"})})]}),a.jsx("span",{className:"text-muted-foreground font-sans",children:"Value"}),a.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[a.jsx("span",{className:"truncate",children:zt}),a.jsx("button",{onClick:()=>ot(zt),className:"text-muted-foreground/50 hover:text-primary shrink-0",children:a.jsx(gs,{className:"w-2.5 h-2.5"})})]})]})}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:fe?"Apex domains use an A record pointing at our cloud edge IP. Some registrars (Cloudflare, Squarespace, etc.) use ALIAS or ANAME instead — that works too.":`Subdomains use a CNAME record. Set the Name to "${yt}" and target cname.vercel-dns.com.`}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"SSL is auto-provisioned after DNS propagation (typically <30 min, up to 72h)."})]}),(Fe==null?void 0:Fe.dnsConfigured)&&a.jsx("p",{className:"text-[11px] text-emerald-700",children:"DNS is live and SSL is provisioned. Re-publish to push the latest build to this domain."}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Q,{variant:"outline",size:"sm",className:"gap-1.5 text-xs h-8",onClick:Je,disabled:Me,children:[Me?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(zr,{className:"w-3 h-3"}),Me?"Checking…":"Refresh DNS status"]}),(Fe==null?void 0:Fe.checkedAt)&&a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last checked ",new Date(Fe.checkedAt).toLocaleTimeString()]})]})]})]})})(),n&&n.id&&it&&(()=>{const Ae=(kt==null?void 0:kt.replace("https://",""))||"",rt=Ae?`https://${Ae}/api/{table}`:null,fe=Ae?`https://${Ae}/api-docs`:null;return a.jsxs("div",{className:"rounded-xl border bg-card/50 overflow-hidden",children:[a.jsxs("div",{className:"px-3.5 py-2.5 border-b bg-muted/30 flex items-center gap-2",children:[a.jsx(ni,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-xs font-semibold text-foreground",children:"API Endpoints"})]}),a.jsxs("div",{className:"p-3.5 space-y-2.5",children:[rt&&a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground font-medium mb-0.5",children:"REST API"}),a.jsx("code",{className:"text-[11px] font-mono text-foreground truncate block",children:rt})]}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:()=>ot(rt),children:a.jsx(gs,{className:"w-3 h-3"})})]}),fe&&a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground font-medium mb-0.5",children:"Swagger Docs"}),a.jsx("a",{href:fe,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] font-mono text-primary hover:underline truncate block",children:fe})]}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:()=>ot(fe),children:a.jsx(gs,{className:"w-3 h-3"})})]})]})]})})(),ne&&a.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg bg-amber-500/5 border border-amber-500/20 text-xs text-amber-600",children:[a.jsx(is,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),a.jsx("span",{children:ne})]}),a.jsxs("div",{className:"flex gap-2 pt-1",children:[a.jsxs(Q,{className:"flex-1 h-11 gap-2 text-sm font-medium",disabled:A,onClick:()=>{oe(null),mt("idle"),at(null),$t(null),je(null),ie()},children:[A?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{className:"w-4 h-4"}),A?"Publishing…":"Re-publish"]}),a.jsx(Q,{variant:"outline",className:"h-11 px-5 text-sm",onClick:V,children:"Done"})]})]})]})]})})}function Ixe(){const{toolUsageHistory:e,setActiveWorkspaceTab:t,triggerBuildRef:r}=gn(),[n,s]=m.useState("code"),[i,o]=m.useState("catalog"),[l,c]=m.useState(!1),u=Rxe(e),d=p=>{const h=p.action;if(!h){W.info(`${p.name} — no action configured`);return}switch(h.toast&&W.success(h.toast),h.type){case"navigate":h.tab&&t(h.tab);break;case"prompt":h.prompt&&r.current&&r.current(h.prompt);break;case"dialog":h.dialogId==="vercel-deploy"?c(!0):W.info(`${p.name} — dialog is not wired yet`);break}};return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"h-11 border-b flex items-center px-3 gap-2 shrink-0 overflow-x-auto scrollbar-hide",children:[a.jsxs("button",{onClick:()=>o("catalog"),className:L("flex items-center gap-1.5 text-xs font-medium transition-colors whitespace-nowrap",i==="catalog"?"text-primary":"text-muted-foreground hover:text-foreground"),children:[a.jsx(al,{className:"w-3.5 h-3.5"}),"Catalog"]}),a.jsxs("button",{onClick:()=>o("history"),className:L("flex items-center gap-1.5 text-xs font-medium transition-colors whitespace-nowrap",i==="history"?"text-primary":"text-muted-foreground hover:text-foreground"),children:[a.jsx(Lr,{className:"w-3.5 h-3.5"}),"History",e.length>0&&a.jsx("span",{className:"min-w-[16px] h-[16px] px-1 rounded-full bg-primary/15 text-primary text-[9px] font-semibold flex items-center justify-center",children:e.length})]}),a.jsxs("button",{onClick:()=>o("demo"),className:L("flex items-center gap-1.5 text-xs font-medium transition-colors whitespace-nowrap",i==="demo"?"text-primary":"text-muted-foreground hover:text-foreground"),children:[a.jsx(hr,{className:"w-3.5 h-3.5"}),"Demo"]})]}),a.jsxs($r,{className:"flex-1",children:[i==="catalog"&&a.jsxs("div",{className:"p-3 space-y-2",children:[a.jsx("div",{className:"px-3 py-2 rounded-lg bg-secondary/40 border border-border/50",children:a.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:[a.jsx("span",{className:"font-medium text-foreground",children:"Qu
8107ick Starts"})," are ready-to-send prompt templates. Click one to drop the prompt into the chat composer — the AI then runs it through the same chat pipeline.",a.jsx("span",{className:"block mt-1",children:"Connectors (Stripe, Slack, etc.) are different — they wire real integrations."})]})}),KJ.map(p=>{const h=A0(p.id),f=n===p.id;return a.jsxs("div",{className:"rounded-lg border bg-card",children:[a.jsxs("button",{onClick:()=>s(f?null:p.id),className:"w-full flex items-center gap-2 px-3 py-2.5 text-left hover:bg-secondary/50 rounded-lg transition-colors",children:[a.jsx("span",{className:"text-sm",children:p.icon}),a.jsx("span",{className:"text-xs font-semibold text-foreground flex-1",children:p.label}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:h.length}),f?a.jsx(Yr,{className:"w-3.5 h-3.5 text-muted-foreground"}):a.jsx(ia,{className:"w-3.5 h-3.5 text-muted-foreground"})]}),f&&a.jsx("div",{className:"px-2 pb-2 space-y-1",children:h.map(x=>a.jsx(Oxe,{tool:x,usageCount:e.filter(g=>g.toolId===x.id).length,onActivate:()=>d(x)},x.id))})]},p.id)})]}),i==="history"&&a.jsx("div",{className:"p-3 space-y-3",children:u.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[a.jsx(Lr,{className:"w-8 h-8 text-muted-foreground/30 mb-3"}),a.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"No tools used yet"}),a.jsx("p",{className:"text-[10px] text-muted-foreground/70 mt-1",children:"Tools will appear here as the AI uses them"})]}):[...u].reverse().map((p,h)=>a.jsxs("div",{className:"rounded-lg border bg-card overflow-hidden",children:[a.jsxs("div",{className:"px-3 py-2 bg-secondary/30 border-b",children:[a.jsx("p",{className:"text-[10px] font-medium text-foreground",children:"Prompt → Tool Mapping"}),a.jsxs("p",{className:"text-[9px] text-muted-foreground font-mono",children:[new Date(p.timestamp).toLocaleTimeString()," · ",p.entries.length," tool",p.entries.length!==1?"s":""," used"]})]}),a.jsx("div",{className:"p-2 space-y-1",children:p.entries.map((f,x)=>{const g=lo.find(y=>y.id===f.toolId);return g?a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-secondary/50",children:[a.jsx("span",{className:"text-sm",children:g.icon}),a.jsx("span",{className:"text-xs font-medium text-foreground flex-1",children:g.name}),a.jsx("span",{className:L("text-[9px] px-1.5 py-0.5 rounded-full border font-medium",g.color),children:g.category})]},x):null})})]},h))}),i==="demo"&&a.jsx("div",{className:"p-3",children:a.jsx(oxe,{})})]}),a.jsx(dM,{open:l,onOpenChange:c})]})}function Oxe({tool:e,usageCount:t,onActivate:r}){return a.jsxs("button",{onClick:r,className:"w-full flex items-start gap-2.5 px-2.5 py-2 rounded-md hover:bg-secondary/50 transition-colors text-left group",children:[a.jsx("span",{className:"text-sm mt-0.5",children:e.icon}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-xs font-medium text-foreground",children:e.name}),t>0&&a.jsxs("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-semibold",children:["×",t]})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground leading-snug mt-0.5",children:e.description})]}),a.jsx(Oi,{className:"w-3 h-3 text-muted-foreground/0 group-hover:text-primary transition-colors shrink-0 mt-1"})]})}function Rxe(e){if(e.length===0)return[];const t=[];let r=[e[0]],n=e[0].timestamp;for(let s=1;s<e.length;s++)e[s].timestamp-n<2e3?r.push(e[s]):(t.push({timestamp:r[0].timestamp,entries:r}),r=[e[s]]),n=e[s].timestamp;return t.push({timestamp:r[0].timestamp,entries:r}),t}function _b({status:e}){return e==="completed"?a.jsx(mn,{className:"w-4 h-4 text-emerald-500"}):e==="failed"?a.jsx(aa,{className:"w-4 h-4 text-destructive"}):e==="empty"?a.jsx(Ar,{className:"w-4 h-4 text-amber-500"}):a.jsx(Lr,{className:"w-4 h-4 text-muted-foreground animate-pulse"})}function pM(e){return e==="completed"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":e==="failed"?"bg-destructive/10 text-destructive border-destructive/20":e==="empty"?"bg-amber-500/10 text-amber-600 border-amber-500/20":"bg-muted text-muted-foreground border-border"}function sw(e){return e?e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`:"—"}
8107function aw(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Dxe({log:e,onClose:t}){var r;return a.jsxs("div",{className:"fixed inset-0 z-50 flex",onClick:t,children:[a.jsx("div",{className:"flex-1 bg-black/30"}),a.jsxs("div",{className:"w-[520px] bg-card border-l shadow-2xl h-full flex flex-col",onClick:n=>n.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b sticky top-0 bg-card z-10",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"text-sm font-bold text-foreground",children:"Build Log"}),a.jsx("p",{className:"text-[10px] font-mono text-muted-foreground truncate",children:e.id})]}),a.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:a.jsx(qn,{className:"w-4 h-4"})})]}),a.jsx($r,{className:"flex-1",children:a.jsxs("div",{className:"p-6 space-y-5",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Status"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(_b,{status:e.status}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] capitalize",pM(e.status)),children:e.status})]})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Duration"}),a.jsx("p",{className:"text-xs font-medium",children:sw(e.duration_ms)})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Mode"}),a.jsx("p",{className:"text-xs font-medium capitalize",children:((r=e.mode)==null?void 0:r.replace("-"," "))||"app builder"})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Files Generated"}),a.jsx("p",{className:"text-xs font-medium",children:e.files_generated})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Pipeline"}),a.jsx("p",{className:"text-xs font-medium",children:e.use_orchestration?"Enhanced":"Standard"})]})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs font-semibold text-foreground mb-2 flex items-center gap-1.5",children:[a.jsx(r6,{className:"w-3.5 h-3.5"})," User Prompt"]}),a.jsx("div",{className:"bg-background border rounded-lg p-3",children:a.jsx("p",{className:"text-xs text-foreground whitespace-pre-wrap",children:e.prompt})})]}),e.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-destructive mb-2",children:"❌ Error"}),a.jsx("pre",{className:"bg-destructive/5 border border-destructive/20 rounded-lg p-3 text-[10px] font-mono text-destructive overflow-auto whitespace-pre-wrap",children:e.error_message})]}),e.file_names&&e.file_names.length>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs font-semibold text-foreground mb-2 flex items-center gap-1.5",children:[a.jsx(dT,{className:"w-3.5 h-3.5"})," Generated Files (",e.file_names.length,")"]}),a.jsx("div",{className:"bg-background border rounded-lg p-3 space-y-1",children:e.file_names.map((n,s)=>a.jsx("p",{className:"text-[10px] font-mono text-muted-foreground",children:n},s))})]}),e.orchestration_phases&&Array.isArray(e.orchestration_phases)&&e.orchestration_phases.length>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs font-semibold text-foreground mb-2 flex items-center gap-1.5",children:[a.jsx(tl,{className:"w-3.5 h-3.5"})," Pipeline Phases"]}),a.jsx("div",{className:"space-y-0",children:e.orchestration_phases.map((n,s)=>a.jsxs("div",{className:"flex items-center gap-3 py-2 border-b last:border-0",children:[a.jsx(_b,{status:n.status==="done"?"completed":n.status}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("p",{className:"text-xs font-medium text-foreground",children:n.name||n.id})}),n.durationMs&&a.jsx("span",{className:"text-[10px] text-muted-foreground",children:sw(n.durationMs)})]},s))})]}),e.plan_steps&&Array.isArray(e.plan_steps)&&e.plan_steps.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-foreground mb-2",children:"Execution Steps"}),a.jsx("div",{className:"space-y-1",children:e.plan_steps.map((n,s)=>a.jsxs("div",{className:"flex items-center gap-2 py-1",children:[a.jsx(_b,{status:n.status==="done"?"completed":n.status}),a.jsx("p",{className:"text-[10px] text-foreground",children:n.title})]},s))})]}),e.ai_response_preview&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-foreground mb-2",children:"AI Response Preview"}),a.jsx("pre",{className:"bg-background border rounded-lg p-3 text-[10px] font-mono text-muted-foreground overflow-auto whitespace-pre-wrap max-h-60",children:e.ai_response_preview})]}),a.jsxs("div",{className:"text-[10px] text-muted-foreground space-y-0.5 pt-2 border-t",children:[a.jsxs("p",{children:["Started: ",aw(e.started_at)]}),e.completed_at&&a.jsxs("p",{children:["Completed: ",aw(e.completed_at)]})]})]})})]})]})}function Mxe({projectId:e,onBack:t}){const{logs:r,loading:n,loadLogs:s}=Yw(e),[i,o]=m.useState(""),[l,c]=m.useState("all"),[u,d]=m.useState(null);m.useEffect(()=>{s()},[s]);const p=r.filter(f=>{if(l!=="all"&&f.status!==l)return!1;if(i.trim()){const x=i.toLowerCase();return f.prompt.toLowerCase().includes(x)||f.id.includes(x)}return!0}),h=[{id:"all",label:"All"},{id:"completed",label:"Completed"},{id:"failed",label:"Failed"},{id:"empty",label:"Empty"}];return a.jsxs("div",{className:"flex-1 flex flex-col items-center px-4 pt-8 pb-8 overflow-y-auto relative z-10",children:[a.jsxs("div",{className:"w-full max-w-4xl",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsx(Q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:t,children:a.jsx(ei,{className:"w-4 h-4"})}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Build Logs"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Review every build — prompt, files, status, and errors"})]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(Cn,{value:i,onChange:f=>o(f.target.value),placeholder:"Search by prompt or ID...",className:"pl-9"})]}),a.jsx("div",{className:"flex items-center gap-1",children:h.map(f=>a.jsx("button",{onClick:()=>c(f.id),className:L("px-3 py-1.5 rounded-full text-xs font-medium transition-all",l===f.
8107id?"bg-primary/10 text-primary border border-primary/20":"bg-card border text-muted-foreground hover:text-foreground"),children:f.label},f.id))})]}),a.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[a.jsxs("div",{className:"bg-secondary/30 px-4 py-2 grid grid-cols-[1fr_80px_80px_80px_40px] gap-2 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:[a.jsx("span",{children:"Prompt"}),a.jsx("span",{children:"Status"}),a.jsx("span",{children:"Files"}),a.jsx("span",{children:"Duration"}),a.jsx("span",{})]}),n&&a.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading..."}),!n&&p.length===0&&a.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No build logs found"}),p.map(f=>a.jsxs("div",{onClick:()=>d(f),className:"px-4 py-3 grid grid-cols-[1fr_80px_80px_80px_40px] gap-2 items-center border-t hover:bg-secondary/20 cursor-pointer transition-colors",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("p",{className:"text-xs font-medium text-foreground truncate",children:[f.prompt.slice(0,80),f.prompt.length>80?"...":""]}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:aw(f.started_at)})]}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] px-1.5 py-0 capitalize w-fit",pM(f.status)),children:f.status}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:f.files_generated}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:sw(f.duration_ms)}),a.jsx(ia,{className:"w-3.5 h-3.5 text-muted-foreground"})]},f.id))]})]}),u&&a.jsx(Dxe,{log:u,onClose:()=>d(null)})]})}const Lxe=10*60*1e3,$xe={queued:{label:"Queued",icon:Lr,color:"text-muted-foreground"},running:{label:"Running",icon:ze,color:"text-primary animate-spin"},paused:{label:"Paused",icon:vT,color:"text-amber-600"},succeeded:{label:"Success",icon:mn,color:"text-emerald-600"},failed:{label:"Failed",icon:Ar,color:"text-destructive"},canceled:{label:"Canceled",icon:Ar,color:"text-muted-foreground"},stale:{label:"Abandoned",icon:Ar,color:"text-muted-foreground/70"}};function Tb(e){if(e.status==="running"||e.status==="queued"||e.status==="paused"){const t=new Date(e.started_at).getTime();if(!Number.isNaN(t)&&Date.now()-t>Lxe)return"stale"}return e.status}function Fxe(e){return e!=null&&e.trim()?(e.trim().split(`
8108`).find(Boolean)||e.trim()).replace(/^implement this now\.?\s*/i,"").replace(/^fix the current build.*?:?\s*/i,"Fix build errors").slice(0,120):"(no prompt recorded)"}function Gl(e){return new Date(e).toISOString().slice(0,10)}function Bxe(e){const t=new Date(e),r=new Date,n=new Date;return n.setDate(r.getDate()-1),Gl(e)===Gl(r.toISOString())?"Today":Gl(e)===Gl(n.toISOString())?"Yesterday":t.toLocaleDateString(void 0,{month:"long",day:"numeric"})}function Uxe(e){return new Date(e).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function zxe(e,t){if(t==="all")return!0;const r=new Date(e).getTime(),n=Date.now();return t==="today"?Gl(e)===Gl(new Date().toISOString()):t==="7d"?n-r<=7*24*60*60*1e3:t==="30d"?n-r<=30*24*60*60*1e3:!0}function qxe(){const{project:e}=gn(),{user:t}=Us(),[r,n]=m.useState([]),[s,i]=m.useState(!0),[o,l]=m.useState(!1),[c,u]=m.useState(null),[d,p]=m.useState({}),[h,f]=m.useState(""),[x,g]=m.useState("all"),[y,b]=m.useState("30d"),[v,k]=m.useState(0);m.useEffect(()=>{if(!(e!=null&&e.id)||!(t!=null&&t.id)){n([]),i(!1);return}let T=!1;return i(!0),(async()=>{try{const{data:C,error:A}=await G.from("build_jobs").select("id,status,started_at,finished_at,events_count,files_count,prompt,error_message,model,build_strategy,mode").eq("user_id",t.id).eq("project_id",e.id).order("started_at",{ascending:!1}).limit(50);if(T)return;A?(String(A.message||"").match(/relation .* does not exist/i)&&l(!0),n([])):n(C||[])}finally{T||i(!1)}})(),()=>{T=!0}},[e==null?void 0:e.id,t==null?void 0:t.id,v]),m.useEffect(()=>{if(!(e!=null&&e.id)||!(t!=null&&t.id)||o)return;const T=G.channel(`bh_${e.id}`).on("postgres_changes",{event:"*",schema:"public",table:"build_jobs",filter:`user_id=eq.${t.id}`},C=>{const A=C.new||C.old;!A||A.project_id!==e.id||(C.eventType==="INSERT"&&C.new?n(P=>[C.new,...P].slice(0,50)):C.eventType==="UPDATE"&&C.new?n(P=>P.map(E=>E.id===C.new.id?C.new:E)):C.eventType==="DELETE"&&C.old&&n(P=>P.filter(E=>E.id!==C.old.id)))}).subscribe();return()=>{G.removeChannel(T)}},[e==null?void 0:e.id,t==null?void 0:t.id,o]);const N=async T=>
8108{if(c===T){u(null);return}if(u(T),!d[T])try{const{data:C,error:A}=await G.from("build_events").select("id,job_id,seq,kind,payload,created_at").eq("job_id",T).order("seq",{ascending:!0}).limit(500);!A&&C&&p(P=>({...P,[T]:C}))}catch{}},j=m.useMemo(()=>{const T=r.length;let C=0,A=0,P=0,E=0;for(const _ of r){const I=Tb(_);I==="succeeded"?C++:I==="failed"?A++:I==="running"||I==="paused"||I==="queued"?P++:I==="stale"&&E++}return{total:T,succeeded:C,failed:A,running:P,stale:E}},[r]),w=m.useMemo(()=>{const T=h.trim().toLowerCase();return r.filter(C=>{const A=Tb(C);return x!=="all"&&A!==x||!zxe(C.started_at,y)?!1:T?[C.prompt,C.error_message,C.model,C.build_strategy,C.mode,C.id].filter(Boolean).join(" ").toLowerCase().includes(T):!0})},[r,h,y,x]),S=m.useMemo(()=>{const T=new Map;for(const C of w){const A=Gl(C.started_at),P=T.get(A)||[];P.push(C),T.set(A,P)}return Array.from(T.entries()).map(([C,A])=>({key:C,label:Bxe(A[0].started_at),rows:A}))},[w]);return o?a.jsx("div",{className:"h-full flex items-center justify-center p-8",children:a.jsxs("div",{className:"max-w-md text-center space-y-3",children:[a.jsx(ai,{className:"w-10 h-10 mx-auto text-muted-foreground/40"}),a.jsx("h3",{className:"text-base font-semibold",children:"Build history isn't enabled"}),a.jsxs("p",{className:"text-sm text-muted-foreground",children:["Apply the ",a.jsx("code",{className:"text-[11.5px] px-1.5 py-0.5 rounded bg-muted",children:"build_jobs"})," migration and set ",a.jsx("code",{className:"text-[11.5px] px-1.5 py-0.5 rounded bg-muted",children:"USE_RESILIENT_BUILDS=1"})," in Supabase secrets to start logging build runs here."]})]})}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"px-4 py-3 border-b bg-card space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ai,{className:"w-4 h-4 text-muted-foreground"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-sm font-semibold",children:"History"}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:s?"Loading…":`${j.total} run${j.total===1?"":"s"} · ${j.succeeded} succeeded · ${j.failed} failed${j.running>0?` · ${j.running} live`:""}${j.stale>0?` · ${j.stale} abandoned`:""}`})]}),a.jsx("button",{onClick:()=>k(T=>T+1),className:"h-8 w-8 rounded-md border bg-background inline-flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-secondary",title:"Refresh history",children:a.jsx(zr,{className:L("h-3.5 w-3.5",s&&"animate-spin")})})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[a.jsx(ja,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),a.jsx("input",{value:h,onChange:T=>f(T.target.value),placeholder:"Search prompts or errors...",className:"h-8 w-full rounded-md border bg-background pl-8 pr-3 text-xs outline-none focus:ring-1 focus:ring-primary"})]}),a.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-background p-0.5",children:[a.jsx(B$,{className:"ml-2 h-3.5 w-3.5 text-muted-foreground"}),["today","7d","30d","all"].map(T=>a.jsx("button",{onClick:()=>b(T),className:L("h-7 rounded px-2 text-[11px] font-medium",y===T?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground hover:bg-secondary"),children:T==="today"?"Today":T==="7d"?"7d":T==="30d"?"30d":"All"},T))]}),a.jsxs("select",{value:x,onChange:T=>g(T.target.value),className:"h-8 rounded-md border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-primary",children:[a.jsx("option",{value:"all",children:"All statuses"}),a.jsx("option",{value:"succeeded",children:"Succeeded"}),a.jsx("option",{value:"failed",children:"Failed"}),a.jsx("option",{value:"running",children:"Running"}),a.jsx("option",{value:"queued",children:"Queued"}),a.jsx("option",{value:"stale",children:"Abandoned"}),a.jsx("option",{value:"canceled",children:"Canceled"})]})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:s?a.jsxs("div",{className:"p-6 text-center text-xs text-muted-foreground",children:[a.jsx(ze,{className:"w-4 h-4 mx-auto animate-spin mb
8108-2"})," Loading history…"]}):r.length===0?a.jsxs("div",{className:"p-8 text-center",children:[a.jsx(ai,{className:"w-10 h-10 mx-auto text-muted-foreground/40 mb-3"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"No builds yet for this project."}),a.jsx("p",{className:"text-xs text-muted-foreground/70 mt-1",children:"Send a prompt in the chat panel to start one."})]}):w.length===0?a.jsxs("div",{className:"p-8 text-center",children:[a.jsx(ja,{className:"w-10 h-10 mx-auto text-muted-foreground/40 mb-3"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"No history matches these filters."}),a.jsx("button",{onClick:()=>{f(""),b("all"),g("all")},className:"mt-3 rounded-md border px-3 py-1.5 text-xs font-medium hover:bg-secondary",children:"Clear filters"})]}):a.jsx("div",{className:"px-4 py-5 space-y-7",children:S.map(T=>a.jsxs("section",{children:[a.jsx("h4",{className:"mb-2 text-lg font-semibold tracking-tight",children:T.label}),a.jsx("div",{className:"rounded-xl border bg-card divide-y overflow-hidden",children:T.rows.map(C=>{const A=Tb(C),P=$xe[A],E=P.icon,_=c===C.id,I=C.finished_at?Math.round((new Date(C.finished_at).getTime()-new Date(C.started_at).getTime())/1e3):null;return a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>N(C.id),className:"w-full grid grid-cols-[auto_auto_1fr_auto] items-start gap-3 px-4 py-3 hover:bg-muted/40 transition text-left",children:[_?a.jsx(Yr,{className:"w-3.5 h-3.5 mt-1 text-muted-foreground"}):a.jsx(ia,{className:"w-3.5 h-3.5 mt-1 text-muted-foreground"}),a.jsx(E,{className:L("w-4 h-4 mt-0.5 shrink-0",P.color)}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"flex items-center gap-2",children:a.jsx("span",{className:"text-sm font-medium truncate",children:Fxe(C.prompt)})}),a.jsxs("div",{className:"text-[11px] text-muted-foreground flex flex-wrap items-center gap-2 mt-0.5",children:[a.jsx("span",{children:P.label}),a.jsx("span",{children:"·"}),a.jsx("span",{children:$s(new Date(C.started_at),{addSuffix:!0})}),I!==null&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:[I,"s"]})]}),C.files_count>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:[C.files_count," files"]})]}),C.events_count>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:[C.events_count," events"]})]})]}),C.error_message&&a.jsxs("div",{className:"text-[11px] text-destructive mt-1 truncate",children:["⚠ ",C.error_message.slice(0,200)]})]}),a.jsxs("div",{className:"text-right",children:[a.jsx("div",{className:"text-sm font-medium text-muted-foreground tabular-nums",children:Uxe(C.started_at)}),a.jsx("code",{className:"mt-1 block text-[10px] text-muted-foreground/50 font-mono",children:C.id.slice(0,8)})]})]}),_&&a.jsx("div",{className:"px-4 pb-3 pl-12 bg-muted/20 border-l-2 border-muted ml-6",children:d[C.id]?d[C.id].length===0?a.jsx("div",{className:"text-[11px] text-muted-foreground py-2",children:"No events recorded for this run."}):a.jsxs("ul",{className:"text-[11px] space-y-0.5 font-mono py-2",children:[d[C.id].slice(0,100).map(D=>a.jsxs("li",{className:"truncate",children:[a.jsxs("span",{className:"text-muted-foreground/60",children:["#",D.seq]}),a.jsx("span",{className:"ml-2 px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider",children:D.kind}),a.jsx("span",{className:"ml-2 text-muted-foreground",children:Hxe(D.kind,D.payload)})]},D.id)),d[C.id].length>100&&a.jsxs("li",{className:"text-muted-foreground/60 italic pt-1",children:["…",d[C.id].length-100," more events truncated"]})]}):a.jsxs("div",{className:"text-[11px] text-muted-foreground py-2",children:[a.jsx(ze,{className:"w-3 h-3 animate-spin inline mr-1.5"})," Loading events…"]})})]},C.id)})})]},T.key))})})]})}function Hxe(e,t){if(e==="tool_use"){const n=String(t.name||"?"),s=t.input||{},i=s.path||s.name||s.route||"";return i?`${n}(${i})`:n}return Object.keys(t||{}).slice(0,4).join(", ")||"(empty)"}const Eb={url:"https://xfmlsevleobdlnjqxmdi.supabase.co",anonKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"};function hM(e){const[t,r]=m.useState(null),[n,s]=m.useState(null),[i,o]=m.useState(!0),l=m.useCallback(async()=>{var x;if(!e){r(null),s(null),o(!1);return}const[p,h]=await Promise.all([G.from("projects").select("custom_supabase_url, custom_supabase_anon_key, custom_supabase_service_key").eq("id",e).single(),G.from("project_cloud_config").select("env_vars").eq("project_id",e).maybeSingle()]);p.data?r({url:p.data.custom_supabase_url||null,anonKey:p.data.custom_supabase_anon_key||null,serviceKey:p.data.custom_supabase_service_key||null}):r(null);const f=(x=h.data)==null?void 0:x.env_vars;f!=null&&f.SUPABASE_URL&&(f!=null&&f.SUPABASE_ANON_KEY)?s({url:f.SUPABASE_URL,anonKey:f.SUPABASE_ANON_KEY}):s(null),o(!1)},[e]);m.useEffect(()=>{l()},[l]);const c=m.useMemo(()=>{const p=!!(t!=null&&t.url&&(t!=null&&t.anonKey)),h=!!(n!=null&&n.url&&(n!=null&&n.anonKey));if(p){const x=t.url,g=Ib(x);return{source:"byos",url:x,anonKey:t.anonKey,hasByos:!0,byosConfig:{url:t.url,anonKey:t.anonKey,hasServiceKey:!!t.serviceKey},label:`Custom (${g})`,host:g}}if(h){const x=n.url,g=Ib(x);return{source:"cloud",url:x,anonKey:n.anonKey,hasByos:!1,byosConfig:null,label:`StudioJungle Cloud (${g})`,host:g}}const f=Ib(Eb.url);return{source:"platform",url:Eb.url,anonKey:Eb.anonKey,hasByos:!1,byosConfig:null,label:"Studiojungle Cloud",host:f}},[t,n]),u=m.useCallback(p=>`${c.url}/functions/v1/${p}`,[c.url]),d=m.useCallback(async()=>{var f;return{"Content-Type":"application/json",Authorization:`Bearer ${((f=(await G.auth.getSession()).data.session)==null?void 0:f.access_token)||""}`,apikey:c.anonKey}},[c.anonKey]);return{resolved:c,loading:i,refresh:l,getFunctionUrl:u,getHeaders:d}}function Ib(e){try{const t=new URL(e),r=t.hostname.split(".");return r.length>=3&&r[1]==="supabase"?r[0].slice(0,12):t.hostname.slice(0,24)}catch{return e.slice(0,24)}}const Wf={totalRequests:0,totalCreditsUsed:0,totalTokens:0,monthlyRequests:0,monthlyCreditsUsed:0,dailyRequests:0,dailyCreditsUsed:0,recentLogs:[],byModel:{},byMode:{}};function Wxe(e){const[t,r]=m.useState(Wf),[n,s]=m.useState(!0),i=m.useCallback(async()=>
8108{if(!e){r(Wf),s(!1);return}s(!0);try{const{data:o,error:l}=await G.from("ai_usage_logs").select("*").eq("project_id",e).order("created_at",{ascending:!1}).limit(500);if(l||!o){r(Wf),s(!1);return}const c=new Date,u=new Date(c.getFullYear(),c.getMonth(),1),d=new Date(c.getTime()-24*60*60*1e3),p={},h={};let f=0,x=0,g=0,y=0,b=0,v=0;for(const k of o){const N=Number(k.credits_used)||0,j=Number(k.total_tokens)||0,w=new Date(k.created_at);v+=N,b+=j,w>=u&&(f++,x+=N),w>=d&&(g++,y+=N),p[k.model]||(p[k.model]={count:0,credits:0,tokens:0}),p[k.model].count++,p[k.model].credits+=N,p[k.model].tokens+=j,h[k.mode]||(h[k.mode]={count:0,credits:0}),h[k.mode].count++,h[k.mode].credits+=N}r({totalRequests:o.length,totalCreditsUsed:v,totalTokens:b,monthlyRequests:f,monthlyCreditsUsed:x,dailyRequests:g,dailyCreditsUsed:y,recentLogs:o.slice(0,50),byModel:p,byMode:h})}catch(o){console.error("Failed to fetch AI credits:",o),r(Wf)}finally{s(!1)}},[e]);return m.useEffect(()=>{i()},[i]),{summary:t,loading:n,refresh:i}}const Ob=[{value:"us-east-1",label:"US East (Virginia)",flag:"🇺🇸"},{value:"us-west-2",label:"US West (Oregon)",flag:"🇺🇸"},{value:"eu-west-1",label:"EU West (Ireland)",flag:"🇮🇪"},{value:"eu-central-1",label:"EU Central (Frankfurt)",flag:"🇩🇪"},{value:"ap-southeast-1",label:"Asia Pacific (Singapore)",flag:"🇸🇬"},{value:"ap-northeast-1",label:"Asia Pacific (Tokyo)",flag:"🇯🇵"}],c_=[{key:"database",label:"Database",icon:Hn,description:"PostgreSQL database with auto-provisioning"},{key:"auth",label:"Authentication",icon:Bs,description:"User signup, login, and session management"},{key:"edgeFunctions",label:"Edge Functions",icon:hr,description:"Serverless backend functions (Deno)"},{key:"storage",label:"File Storage",icon:Op,description:"Upload and serve files and images"},{key:"realtime",label:"Realtime",icon:m6,description:"Live subscriptions and presence"}];function Vxe({projectId:e,compact:t}){const{config:r,loading:n,updateConfig:s,updateFeature:i,setEnvVar:o,removeEnvVar:l}=mO(e),{functions:c,secrets:u,loading:d,refresh:p}=W1(e),{resolved:h}=hM(e),f=(h==null?void 0:h.source)==="byos"?"byos":(r==null?void 0:r.backend_mode)||"studiojungle";m.useEffect(()=>{r&&(h==null?void 0:h.source)==="byos"&&r.backend_mode!=="byos"&&s({backend_mode:"byos"})},[h==null?void 0:h.source,r,s]);const[x,g]=m.useState(""),[y,b]=m.useState(""),[v,k]=m.useState([]),[N,j]=m.useState(!1),[w,S]=m.useState(null);if(m.useEffect(()=>{if(!e)return;(async()=>{j(!0);const A=c.find(P=>P.function_name==="database-schema");if(A!=null&&A.source_code){const E=(A.source_code.match(/CREATE TABLE\s+(?:IF NOT EXISTS\s+)?(\w+)/gi)||[]).map(_=>_.replace(/CREATE TABLE\s+(IF NOT EXISTS\s+)?/i,""));k(E)}j(!1)})()},[e,c]),n||!r)return a.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:a.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full"})});const T=async()=>{x.trim()&&(await o(x.trim(),y.trim()),g(""),b(""),W.success(`Added ${x}`))};return t?a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>s({backend_mode:"studiojungle"}),className:L("flex-1 flex items-center gap-2 p-3 rounded-xl border transition-all text-left",f==="studiojungle"?"border-primary bg-primary/5 shadow-sm":"border-border hover:bg-secondary/50"),children:[a.jsx(os,{className:L("w-5 h-5",f==="studiojungle"?"text-primary":"text-muted-foreground")}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold",children:"Studiojungle Cloud"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Managed (default)"})]})]}),a.jsxs("button",{onClick:()=>s({backend_mode:"byos"}),className:L("flex-1 flex items-center gap-2 p-3 rounded-xl border transition-all text-left",f==="byos"?"border-primary bg-primary/5 shadow-sm":"border-border hover:bg-secondary/50"),children:[a.jsx(Is,{className:L("w-5 h-5",f==="byos"?"text-primary":"text-muted-foreground")}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold",children:"Bring Your Own"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Custom backend"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium mb-1.5 block",children:"Region"}
8108),a.jsxs(Ns,{value:r.region,onValueChange:C=>s({region:C}),children:[a.jsx(hs,{className:"h-9 text-xs",children:a.jsx(ks,{})}),a.jsx(fs,{children:Ob.map(C=>a.jsxs(Dt,{value:C.value,className:"text-xs",children:[C.flag," ",C.label]},C.value))})]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:c_.map(C=>a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-card",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(C.icon,{className:"w-3.5 h-3.5 text-muted-foreground"}),a.jsx("span",{className:"text-xs font-medium",children:C.label})]}),a.jsx(Xl,{checked:r.features[C.key],onCheckedChange:A=>i(C.key,A),className:"scale-75"})]},C.key))})]}):a.jsxs("div",{className:"space-y-6",children:[a.jsxs("section",{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(ya,{className:"w-4 h-4 text-primary"})," Hosting Provider"]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("button",{onClick:()=>s({cloud_provider:"managed",backend_mode:"studiojungle"}),className:L("flex-1 p-4 rounded-xl border transition-all text-left",r.cloud_provider==="managed"?"border-primary bg-primary/5 shadow-sm":"border-border hover:bg-secondary/50"),children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center",children:a.jsx(os,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold",children:"Managed Cloud"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Studio Jungle hosts everything"})]}),a.jsx("span",{className:"text-[10px] font-semibold text-primary px-1.5 py-0.5 rounded bg-primary/10 ml-auto",children:"+$10/mo"}),r.cloud_provider==="managed"&&a.jsx(mn,{className:"w-4 h-4 text-primary"})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Database, Auth, Storage, Edge Functions — all managed by Studio Jungle. No Supabase account needed. Per-project fee added to your subscription."})]}),a.jsxs("button",{onClick:()=>s({cloud_provider:"byos",backend_mode:"byos"}),className:L("flex-1 p-4 rounded-xl border transition-all text-left",r.cloud_provider==="byos"?"border-primary bg-primary/5 shadow-sm":"border-border hover:bg-secondary/50"),children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-amber-500/10 flex items-center justify-center",children:a.jsx(Is,{className:"w-4 h-4 text-amber-600"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold",children:"Bring Your Own"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Your own Supabase account"})]}),a.jsx("span",{className:"text-[10px] font-semibold text-emerald-600 px-1.5 py-0.5 rounded bg-emerald-500/10 ml-auto",children:"Free"}),r.cloud_provider==="byos"&&a.jsx(mn,{className:"w-4 h-4 text-primary"})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Connect your Supabase via OAuth — Studio Jungle creates projects in your org. Free tier limit: 2 projects per Supabase org."})]})]}),r.cloud_provider==="managed"&&a.jsxs("p",{className:"mt-3 text-[11px] text-muted-foreground bg-primary/5 border border-primary/20 rounded-lg px-3 py-2",children:[a.jsx("span",{className:"font-medium text-primary",children:"Managed Cloud:"})," Studio Jungle hosts your project's database, auth, storage, and edge functions. Each managed project adds $10/mo to your Studio Jungle subscription. You don't need a Supabase account."]})]}),a.jsx(Ni,{}),a.jsx("section",{children:(()=>{var P;const C=!!((P=r.env_vars)!=null&&P.SUPABASE_PROJECT_REF),A=Ob.find(E=>E.value===r.region);return a.jsxs(a.Fragment,{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Br,{className:"w-4 h-4 text-primary"})," Region"]}),C?a.jsx("div",{className:"px-4 py-3 rounded-xl border bg-card",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold",children:A?`${A.flag} ${A.label}`:r.region||"Not set"}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Provisioned region cannot be changed. To migrate, create a new project."})]}),a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:"Locked"})]})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs(Ns,{value:r.regi
8108on,onValueChange:E=>s({region:E}),children:[a.jsx(hs,{className:"h-9 text-xs",children:a.jsx(ks,{})}),a.jsx(fs,{children:Ob.map(E=>a.jsxs(Dt,{value:E.value,className:"text-xs",children:[E.flag," ",E.label]},E.value))})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground italic px-1",children:"Pick the region closest to your users. This locks at first provision and can't be changed later."})]})]})})()}),a.jsx(Ni,{}),a.jsxs("section",{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(sa,{className:"w-4 h-4 text-primary"})," Cloud Features",a.jsx(Ge,{variant:"outline",className:"text-[9px] ml-auto",children:"Always on"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground mb-2",children:"Supabase enables Database, Auth, Storage, Edge Functions, and Realtime by default for every project. They can't be disabled per-project — only org-level on a paid plan."}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:c_.map(C=>a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-card",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-6 h-6 rounded-md bg-emerald-500/10 flex items-center justify-center",children:a.jsx(C.icon,{className:"w-3 h-3 text-emerald-600"})}),a.jsx("span",{className:"text-[11px] font-medium",children:C.label})]}),a.jsx(mn,{className:"w-3.5 h-3.5 text-emerald-500"})]},C.key))})]}),a.jsx(Ni,{}),a.jsxs("section",{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Bs,{className:"w-4 h-4 text-primary"})," Environment Variables"]}),a.jsxs("div",{className:"space-y-2",children:[Object.entries(r.env_vars).map(([C,A])=>a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-card",children:[a.jsx("span",{className:"text-xs font-mono font-medium flex-1 truncate",children:C}),a.jsx("span",{className:"text-xs text-muted-foreground font-mono truncate max-w-[120px]",children:"•".repeat(Math.min(A.length,12))}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>l(C),children:a.jsx(oa,{className:"w-3 h-3"})})]},C)),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Cn,{value:x,onChange:C=>g(C.target.value),placeholder:"KEY_NAME",className:"text-xs h-8 font-mono flex-1"}),a.jsx(Cn,{value:y,onChange:C=>b(C.target.value),placeholder:"value",type:"password",className:"text-xs h-8 font-mono flex-1"}),a.jsxs(Q,{size:"sm",variant:"outline",className:"h-8 gap-1 text-xs",onClick:T,disabled:!x.trim(),children:[a.jsx(Kr,{className:"w-3 h-3"})," Add"]})]})]})]}),a.jsx(Ni,{}),a.jsxs("section",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h4",{className:"text-sm font-semibold flex items-center gap-2",children:[a.jsx(G$,{className:"w-4 h-4 text-primary"})," Edge Functions",c.length>0&&a.jsx(Ge,{variant:"secondary",className:"text-[9px] px-1.5",children:c.filter(C=>C.function_name!=="database-schema").length})]}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:p,title:"Refresh",children:a.jsx(zr,{className:L("w-3.5 h-3.5",d&&"animate-spin")})})]}),d?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ze,{className:"w-4 h-4 animate-spin text-muted-foreground"})}):c.filter(C=>C.function_name!=="database-schema").length===0?a.jsxs("div",{className:"border rounded-xl p-4 bg-secondary/20 text-center",children:[a.jsx(hr,{className:"w-5 h-5 text-muted-foreground/40 mx-auto mb-1.5"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"No edge functions yet"}),a.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"Functions will appear here when generated during builds"})]}):a.jsx("div",{className:"space-y-1.5",children:c.filter(C=>C.function_name!=="database-schema").map(C=>a.jsxs("div",{className:"border rounded-xl bg-card overflow-hidden",children:[a.jsxs("button",{onClick:()=>S(w===C.id?null:C.id),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-secondary/30 transition-colors",children:[a.jsx("div",{className:"w-7 h-7 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx(hr,{className:"w-3.5 h-3.5 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-xs font-semibold truncate",children:C.display_name}),a.jsx(Ge,{variant:C.status==="deployed"?"default":"secondary",className:"text-[8px] px-1.5 shrink-0",children:C.status})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:C.path})]}),a.jsx("div",{className:"flex gap-1 shrink-0",children:C.methods.map(A=>a.jsx(Ge,{variant:"outline",className:"text-[8px] px-1",children:A},A))})]}),w===C.id&&a.jsx("div",{className:"px-4 pb-3 border-t bg-secondary/10",children:a.jsxs("div",{className:"grid grid-cols-2 gap-2 py-2 text-[10px]",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Function:"})," ",a.jsx("span",{className:"font-mono font-medium",children:C.function_name})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"JWT:"})," ",a.jsx("span",{className:C.verify_jwt?"text-green-500":"text-amber-500",children:C.verify_jwt?"Required":"Public"})]}),C.description&&a.jsxs("div",{className:"col-span-2",children:[a.jsx("span",{className:"text-muted-foreground",children:"Description:"})," ",a.jsx("span",{children:C.description})]}),C.feature_category&&a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Category:"})," ",a.jsx(Ge,{variant:"outline",className:"text-[8px] px-1",children:C.feature_category})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"Created:"})," ",a.jsx("span",{children:new Date(C.created_at).toLocaleDateString()})]})]})})]},C.id))})]}),a.jsx(Ni,{}),a.jsxs("section",{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Di,{className:"w-4 h-4 text-primary"})," Database Tables",v.length>0&&a.jsx(Ge,{variant:"secondary",className:"text-[9px] px-1.5",children:v.length})]}),v.length===0?a.jsxs("div",{className:"border rounded-xl p-4 bg-secondary/20 text-center",children:[a.jsx(Hn,{className:"w-5 h-5 text-muted-foreground
8108/40 mx-auto mb-1.5"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"No tables detected"}),a.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"Tables will appear here after schema generation"})]}):a.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:v.map(C=>a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-card",children:[a.jsx(Di,{className:"w-3 h-3 text-muted-foreground shrink-0"}),a.jsx("span",{className:"text-xs font-mono truncate",children:C})]},C))})]}),a.jsx(Ni,{}),a.jsxs("section",{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Ql,{className:"w-4 h-4 text-primary"})," Detected Secrets",u.length>0&&a.jsx(Ge,{variant:"secondary",className:"text-[9px] px-1.5",children:u.length})]}),u.length===0?a.jsxs("div",{className:"border rounded-xl p-4 bg-secondary/20 text-center",children:[a.jsx(Ql,{className:"w-5 h-5 text-muted-foreground/40 mx-auto mb-1.5"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"No secrets detected"}),a.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"Required secrets are auto-detected from edge functions"})]}):a.jsx("div",{className:"space-y-1.5",children:u.map(C=>a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 rounded-lg border bg-card",children:[a.jsx(Ql,{className:"w-3 h-3 text-muted-foreground shrink-0"}),a.jsx("span",{className:"text-xs font-mono font-medium flex-1 truncate",children:C.secret_name}),a.jsx(Ge,{variant:C.is_configured?"default":"destructive",className:"text-[8px] px-1.5",children:C.is_configured?"Set":"Missing"})]},C.id))})]}),(r.vercel_project_id||r.vercel_domain)&&a.jsxs(a.Fragment,{children:[a.jsx(Ni,{}),a.jsxs("section",{children:[a.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Es,{className:"w-4 h-4 text-primary"})," Cloud Deployment"]}),a.jsxs("div",{className:"border rounded-xl p-4 bg-card space-y-2",children:[r.vercel_domain&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-xs text-muted-foreground",children:"Domain"}),a.jsx("span",{className:"text-xs font-mono font-medium",children:r.vercel_domain})]}),r.vercel_last_deploy_status&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-xs text-muted-foreground",children:"Last Deploy"}),a.jsx(Ge,{variant:r.vercel_last_deploy_status==="READY"?"default":"secondary",className:"text-[9px]",children:r.vercel_last_deploy_status})]}),r.vercel_last_deploy_at&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-xs text-muted-foreground",children:"Deployed"}),a.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(r.vercel_last_deploy_at).toLocaleString()})]})]})]})]})]})}const Gxe=[{id:"crud",name:"CRUD API",icon:"📦",category:"crud",description:"REST endpoints for create, read, update, delete",code:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
8109import { createClient } from "https://esm.sh/@supabase/[email protected]";
8110
8111const corsHeaders = {
8112  "Access-Control-Allow-Origin": "*",
8113  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
8114};
8115
8116serve(async (req) => {
8117  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
8118
8119  const supabase = createClient(
8120    Deno.env.get("SUPABASE_URL")!,
8121    Deno.env.get("SUPABASE_ANON_KEY")!,
8122    { global: { headers: { Authorization: req.headers.get("Authorization") || "" } } }
8123  );
8124
8125  const url = new URL(req.url);
8126  const table = url.searchParams.get("table") || "items";
8127
8128  try {
8129    if (req.method === "GET") {
8130      const { data, error } = await supabase.from(table).select("*");
8131      if (error) throw error;
8132      return new Response(JSON.stringify(data), { headers: { ...corsHeaders, "Content-Type": "application/json" } });
8133    }
8134    if (req.method === "POST") {
8135      const body = await req.json();
8136      const { data, error } = await supabase.from(table).insert(body).select().single();
8137      if (error) throw error;
8138      return new Response(JSON.stringify(data), { status: 201, headers: { ...corsHeaders, "Content-Type": "application/json" } });
8139    }
8140    return new Response("Method not allowed", { status: 405, headers: corsHeaders });
8141  } catch (e) {
8142    return new Response(JSON.stringify({ error: e.message }), { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } });
8143  }
8144});`},{id:"auth",name:"Auth Webhook",icon:"🔐",category:"auth",description:"Handle auth events like sign-up, sign-in",code:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
8145
8146const corsHeaders = {
8147  "Access-Control-Allow-Origin": "*",
8148  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
8149};
8150
8151serve(async (req) => {
8152  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
8153  const payload = await req.json();
8154  console.log("Auth event:", payload.type, payload.record?.email);
8155  return new Response(JSON.stringify({ received: true }), {
8156    headers: { ...corsHeaders, "Content-Type": "application/json" },
8157  });
8158});`},{id:"ai",name:"AI Endpoint",icon:"🤖",category:"ai",description:"Proxy AI model calls with streaming",code:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
8159
8160const corsHeaders = {
8161  "Access-Control-Allow-Origin": "*",
8162  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
8163};
8164
8165serve(async (req) => {
8166  if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });
8167  const { prompt } = await req.json();
8168  const apiKey = Deno.env.get("OPENAI_API_KEY");
8169  if (!apiKey) return new Response("Missing API key", { status: 500, headers: corsHeaders });
8170  const response = await fetch("https://api.openai.com/v1/chat/completions", {
8171    method: "POST",
8172    headers: { "Content-Type": "application/json", Authorization: \`Bearer \${apiKey}\` },
8173    body: JSON.stringify({ model: "gpt-4o-mini", messages: [{ role: "user", content: prompt }] }),
8174  });
8175  const data = await response.json();
8176  return new Response(JSON.stringify({ result: data.choices?.[0]?.message?.content }), {
8177    headers: { ...corsHeaders, "Content-Type": "application/json" },
8178  });
8179});`},{id:"cron",name:"Scheduled Task",icon:"⏰",category:"general",description:"Background job for periodic tasks",code:`import { serve } from "https://deno.land/[email protected]/http/server.ts";
8180import { createClient } from "https://esm.sh/@supabase/[email protected]";
8181
8182serve(async (req) => {
8183  const supabase = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);
8184  const { data, error } = await supabase.from("sessions").delete().lt("expires_at", new Date().toISOString());
8185  return new Response(JSON.stringify({ success: !error, cleaned: data?.length || 0 }), {
8186    headers: { "Content-Type": "application/json" },
8187  });
8188});`}],u_={auth:{label:"Auth",color:"bg-purple-500/15 text-purple-600"},crud:{label:"CRUD",color:"bg-blue-500/15 text-blue-600"},ai:{label:"AI",color:"bg-amber-500/15 text-amber-600"},webhook:{label:"Webhook",color:"bg-rose-500/15 text-rose-600"},storage:{label:"Storage",color:"bg-cyan-500/15 text-cyan-600"},general:{label:"General",color:"bg-secondary text-muted-foreground"}};function Kxe(e){var s;const t=[];function r(i,o){for(const l of i){if(l.type==="folder"&&l.name==="functions"){const c=o.join("/");if(c===""||c==="supabase")return l}if(l.type==="folder"&&l.children){const c=r(l.children,[...o,l.name]);if(c)return c}}return null}const n=r(e,[]);if(n!=null&&n.children){for(const i of n.children)if(i.type==="folder"){const o=((s=i.children)==null?void 0:s.some(l=>l.name==="index.ts"||l.name==="index.js"))??!1;t.push({name:i.name,hasIndex:o})}}return t}function Yxe({functions:e,fileTreeFunctions:t,secrets:r,buildLogs:n,dbTables:s,projectId:i,projectName:o,backend:l,infra:c,onRefreshInfra:u}){const{provision:d,provisioning:p}=a1(),{connect:h,connecting:f}=rO(),[x,g]=m.useState(!1),[y,b]=m.useState(!1),v=m.useRef(null),k=m.useCallback(()=>new Promise(_=>{v.current=_,g(!0)}),[]),N=m.useCallback(_=>{var I;(I=v.current)==null||I.call(v,_),v.current=null,g(!1)},[]),j=m.useCallback(()=>{var _;(_=v.current)==null||_.call(v,null),v.current=null,g(!1)},[]),w=e.length+t.filter(_=>!e.some(I=>I.function_name===_.name)).length,S=c.functions.length||w,T=e.filter(_=>_.status==="deployed").length+t.filter(_=>!e.some(I=>I.function_name===_.name)).length;n.filter(_=>_.status==="completed").length;const C=n.filter(_=>_.status==="failed"||_.status==="error").length,A=c.tables.length||s.length,P=c.users.length,E=[{label:"Edge Functions",value:S,sub:`${T} deployed`,icon:sa,color:"text-primary"},{label:"Database Tables",value:A,sub:"tables active",icon:Hn,color:"text-emerald-500"},{label:"Auth Users",value:P,sub:"registered",icon:Zl,color:"text-blue-500"},{label:"Secrets",value:r.length,sub:"configured",icon:Bs,color:"text-amber-500"},{label:"Storage Buckets",value:c.storage.length,sub:c.storage.length===1?"bucket":"buckets",icon:Op,color:"text-purple-500"},{label:"Failed Builds",value:C,sub:C===0?"all good ✓":"need attention",icon:Ar,color:C>0?"text-destructive":"text-emerald-500"}];return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-6",children:[a.jsxs("div",{className:L("flex items-center gap-3 rounded-xl px-4 py-3 border",l.source==="byos"?"bg-amber-500/5 border-amber-500/20":"bg-primary/5 border-primary/20"),children:[l.source==="byos"?a.jsx(Is,{className:"w-5 h-5 text-amber-600"}):a.jsx(os,{className:"w-5 h-5 text-primary"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold",children:l.source==="byos"?"Custom Backend":"StudioJungle Cloud"}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:l.source==="byos"?l.host:"Platform-managed infrastru
8188cture"})]}),a.jsxs(Ge,{variant:"outline",className:"gap-1.5",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500"})," Connected"]}),c.status==="provisioned"&&i&&a.jsxs(Q,{size:"sm",variant:"ghost",className:"gap-1.5 text-[11px]",disabled:y,title:"Reset the Supabase Site URL to your deployed app URL (or this project's *.supabase.co URL if not deployed yet). Fixes signup/recovery email links pointing at localhost.",onClick:async()=>{if(!(!i||y)){b(!0);try{const{data:_,error:I}=await G.functions.invoke("sync-supabase-auth-url",{body:{projectId:i}});I?W.error("Auth URL sync failed",{description:I.message}):_!=null&&_.error?W.error("Auth URL sync failed",{description:String(_.detail||_.error)}):_!=null&&_.site_url?W.success("Auth URL synced",{description:_.site_url}):W.message("Auth URL sync ran",{description:"No changes needed."})}catch(_){W.error("Auth URL sync failed",{description:_ instanceof Error?_.message:String(_)})}finally{b(!1)}}},children:[y?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(zr,{className:"w-3 h-3"}),"Sync Auth URL"]})]}),c.status!=="provisioned"&&i&&a.jsxs("div",{className:L("flex items-center gap-3 rounded-xl px-4 py-3 border",c.status==="error"?"bg-destructive/5 border-destructive/20":"bg-amber-500/5 border-amber-500/20"),children:[c.status==="loading"?a.jsx(ze,{className:"w-5 h-5 text-amber-500 animate-spin shrink-0"}):c.status==="error"?a.jsx(aa,{className:"w-5 h-5 text-destructive shrink-0"}):a.jsx(Ar,{className:"w-5 h-5 text-amber-500 shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold",children:c.status==="loading"?"Checking infrastructure...":c.status==="error"?"Infrastructure Error":"Backend Not Provisioned"}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:c.status==="loading"?"Fetching project backend status":c.status==="error"?c.error||"Could not connect to backend":"This project needs a dedicated backend instance"})]}),(c.status==="not_provisioned"||c.status==="error")&&a.jsxs(Q,{size:"sm",variant:c.status==="error"?"destructive":"default",disabled:p||f,onClick:async()=>{if(!i)return;const _=await k();if(!_){W.message("Region required",{description:"Pick a region to provision the database."});return}const I=async()=>d(i,o||"Project",_);let D=await I();if(D.needs_connect){W.info("Redirecting to Supabase to authorize…");const M=await h();if(M.redirecting)return;if(!M.success){W.error(M.error||"Could not connect Supabase");return}W.success("Supabase connected — provisioning…"),D=await I()}if(D.success){if(D.supabase_url){const M=D.supabase_url.replace(/^https?:\/\//,"").replace(/\.supabase\.co.*/,".supabase.co");W.success(`Database ready · ${M} · ${D.region||""}`,{duration:8e3})}else W.success("Backend provisioned successfully!");u()}else W.error(D.error||"Provisioning failed")},className:"gap-1.5",children:[p||f?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(Es,{className:"w-3.5 h-3.5"}),f?"Connecting…":p?"Provisioning...":c.status==="error"?"Retry":"Provision Now"]})]}),a.jsx(i1,{open:x,onClose:j,onConfirm:N}),a.jsx("div",{className:"grid grid-cols-3 gap-3",children:E.map(_=>a.jsxs("div",{className:"border rounded-xl p-4 bg-card hover:bg-secondary/30 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(_.icon,{className:L("w-4 h-4",_.color)}),a.jsx("span",{className:"text-[11px] text-muted-foreground font-medium",children:_.label})]}),a.jsx("p",{className:"text-2xl font-bold",children:_.value}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:_.sub})]},_.label))}),n.length>0&&a.jsxs("div",{children:[a.jsxs("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[a.jsx(lc,{className:"w-4 h-4 text-primary"})," Recent Activity"]}),a.jsx("div",{className:"space-y-1.5",children:n.slice(0,5).map(_=>{var I;return a.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5 rounded-lg border bg-card",children:[_.status==="completed"?a.jsx(mn,{className:"w-4 h-4 text-emerald-500 shrink-0"}):_.status==="failed"||_.status==="error"?a.jsx(aa,{className:"w-4 h-4 text-destructive shrink-0"}):a.jsx(ze,{className:"w-4 h-4 text-amber-500 animate-spin shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("p",{className:"text-xs font-medium truncate",children:[((I=_.prompt)==null?void 0:I.slice(0,60))||"Build","..."]}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[_.files_generated||0," files changed"]})]}),a.jsxs("div",{className:"text-right shrink-0",children:[_.duration_ms&&a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[(_.duration_ms/1e3).toFixed(1),"s"]}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:_.created_at?$s(new Date(_.created_at),{addSuffix:!0}):""})]})]},_.id)})})]})]})}function Jxe({functions:e,fileTreeFunctions:t,selectedFn:r,setSelectedFn:n,removeFunction:s,loading:i,backend:o,projectId:l,secrets:c,refresh:u,addFunction:d}){const[p,h]=m.useState("list"),f=async v=>{if(!l)return;const k=`${v.id}-${Date.now().toString(36).slice(-4)}`;await d({function_name:k,display_name:v.name,description:v.description,methods:v.id==="crud"?["GET","POST","PUT","DELETE"]:["POST"],path:`/functions/v1/${k}`,verify_jwt:!0,source_code:v.code,auto_generated:!1,feature_category:v.category}),W.success(`Created "${v.name}" edge function`),h("list")},x=new Set(e.map(v=>v.function_name)),g=t.filter(v=>!x.has(v.name)),y=e.length+g.length,b=e.filter(v=>v.status==="deployed").length+g.length;return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsx("div",{className:"border-b px-4 flex gap-0.5",children:[{id:"list",label:"Functions",count:y},{id:"explorer",label:"API Explorer"},{id:"sdk",label:"SDK"},{id:"templates",label:"Templates"}].map(v=>a.jsxs("button",{onClick:()=>h(v.id),className:L("px-3 py-2 text-xs font-medium transition-colors border-b-2 -mb-px",p===v.id?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"),children:[v.label,v.count!=null&&v.count>0&&a.jsx("span",{className:"ml-1 text-[10px] bg-primary/15 text-primary px-1.5 py-0.5 rounded-full",children:v.count})]},v.id))}),a.jsxs("div",{className:"flex-1 overflow-hidden",children:[p==="list"&&a.jsxs("div",{className:"h-full flex",children:[a.jsxs("div",{className:"w-[340px] border-r overflow-auto p-4 space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-secondary/50 border flex-1",children:[a.jsx(lc,{className:"w-4 h-4 text-primary"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-lg font-bold leading-none",children:y}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Total"})]})]}),a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-secondary/50 border flex-1",children:[a.jsx(Br,{className:"w-4 h-4 text-emerald-500"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-lg font-bold leading-none",children:b}),a.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Deployed"})]})]})]}),i?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ze,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):y===0?a.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[a.jsx(sa,{className:"w-8 h-8 opacity-30 mx-auto mb-2"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No edge functions yet"}),a.jsx("p",{className:"text-xs mt-1",children:"Build a feature that needs backend logic"})]}):a.jsxs("div",{className:"space-y-1.5",children:[e.map(v=>{const k=u_[v.feature_category||"general"]||u_.general;return a.jsxs("button",{onClick:()=>n(v),className:L("w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all group border",(r==null?void 0:r.id)===v.id?"bg-primary/5 border-primary/20 shadow-sm":"bg-card hover:bg-secondary/50 border-border/50"),children:[a.jsx("div",{className:L("w-2.5 h-2.5 rounded-full shrink-0",v.status==="deployed"?"bg-emerald-500":v.status==="error"?"bg-destructive":"bg-muted-foreground")}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-sm font-semibold truncate block",children:v.display_name}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[a.jsx("span",{className:L("text-[9px] font-semibold px-1.5 py-0.5 rounded-md",k.color),children:k.label}),a.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono truncate",children:["/functions/v1/",v.function_name]})]})]}),a.jsx("div",{className:"flex gap-1 shrink-0",children:v.methods.slice(0,2).map(N=>a.jsx("span",{className:L("text-[9px] font-bold px-1.5 py-0.5 rounded-md",N==="GET"&&"bg-emerald-500/15 text-emerald-600",N==="POST"&&"bg-blue-500/15 text-blue-600",N==="DELETE"&&"bg-red-500/15 text-red-600"),children:N},N))}),a.jsx("div",{role:"button",tabIndex:0,onClick:N=>{N.stopPropagation(),s(v.id),(r==null?void 0:r.id)===v.id&&n(null)},onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.stopPropagation(),s(v.id),(r==null?void 0:r.id)===v.id&&n(null))},className:"opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-all cursor-pointer",children:a.jsx(oa,{className:"w-3 h-3"})})]},v.id)}),g.map(v=>a.jsxs("div",{className:"w-full flex items-center gap-3 px-4 py-3 rounded-xl border bg-card border-dashed border-border/70",children:[a.jsx("div",{className:"w-2.5 h-2.5 rounded-full shrink-0 bg-emerald-500"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-sm font-semibold truncate block",children:v.name.replace(/-/g," ").replace(/\b\w/g,k=>k.toUpperCase())}),a.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:["/functions/v1/",v.name]})]}),a.jsx(Ge,{variant:"secondary",className:"text-[9px]",children:"File-based"})]},v.name))]})]}),a.jsx("div",{className:"flex-1 overflow-auto",children:r?a.jsxs("div",{className:"p-5 space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:L("w-3 h-3 rounded-full",r.status==="deployed"?"bg-emerald-500":"bg-destructive")}
8188),a.jsx("h2",{className:"text-lg font-bold",children:r.display_name}),a.jsx(Ge,{variant:"outline",className:"text-[10px]",children:r.status})]}),r.description&&a.jsx("p",{className:"text-xs text-muted-foreground",children:r.description}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"border rounded-lg p-3",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium",children:"Endpoint"}),a.jsx("p",{className:"text-xs font-mono mt-1",children:r.path})]}),a.jsxs("div",{className:"border rounded-lg p-3",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium",children:"Auth"}),a.jsx("p",{className:"text-xs mt-1",children:r.verify_jwt?"JWT Required":"Public"})]}),a.jsxs("div",{className:"border rounded-lg p-3",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium",children:"Methods"}),a.jsx("div",{className:"flex gap-1 mt-1",children:r.methods.map(v=>a.jsx("span",{className:L("text-[10px] font-bold px-1.5 py-0.5 rounded",v==="GET"&&"bg-emerald-500/15 text-emerald-600",v==="POST"&&"bg-blue-500/15 text-blue-600"),children:v},v))})]}),a.jsxs("div",{className:"border rounded-lg p-3",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium",children:"Actions"}),a.jsxs("div",{className:"flex gap-1.5 mt-1",children:[a.jsxs(Q,{variant:"outline",size:"sm",className:"text-[10px] h-6 gap-1",onClick:()=>h("explorer"),children:[a.jsx(NT,{className:"w-3 h-3"})," Test"]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"text-[10px] h-6 gap-1",onClick:()=>h("sdk"),children:[a.jsx(sd,{className:"w-3 h-3"})," SDK"]})]})]})]}),r.source_code&&a.jsxs("div",{className:"border rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium",children:"Source Code"}),a.jsxs(Q,{variant:"ghost",size:"sm",className:"text-[10px] h-6 gap-1",onClick:()=>{navigator.clipboard.writeText(r.source_code||""),W.success("Copied!")},children:[a.jsx(gs,{className:"w-3 h-3"})," Copy"]})]}),a.jsx("pre",{className:"text-[11px] font-mono bg-secondary rounded-lg p-3 overflow-auto max-h-64 whitespace-pre-wrap border",children:r.source_code})]})]}):a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground",children:[a.jsx(sa,{className:"w-10 h-10 opacity-40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Select a Function"}),a.jsx("p",{className:"text-xs mt-1",children:"View details, test, or generate SDK code"})]})})]}),p==="explorer"&&a.jsx(Xxe,{selectedFn:r,projectId:l,backend:o}),p==="sdk"&&a.jsx(Zxe,{selectedFn:r}),p==="templates"&&a.jsxs("div",{className:"h-full overflow-auto p-4",children:[a.jsx("h3",{className:"text-sm font-semibold mb-1",children:"Edge Function Templates"}),a.jsx("p",{className:"text-xs text-muted-foreground mb-4",children:"Create from a template or let the AI auto-generate"}),a.jsx("div",{className:"grid grid-cols-2 gap-3",children:Gxe.map(v=>a.jsxs("button",{onClick:()=>f(v),className:"flex flex-col items-start gap-2 p-4 rounded-xl border bg-card hover:bg-secondary/50 transition-colors text-left group",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl",children:v.icon}),a.jsx("span",{className:"text-sm font-semibold",children:v.name})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:v.description}),a.jsxs(Ge,{variant:"outline",className:"text-[10px] mt-1 group-hover:bg-primary/10 group-hover:text-primary transition-colors",children:[a.jsx(Kr,{className:"w-3 h-3 mr-1"})," Create"]})]},v.id))})]})]})]})}function Xxe({selectedFn:e,projectId:t,backend:r}){const[n,s]=m.useState("POST"),[i,o]=m.useState(`{
8189  "key": "value"
8190}`),[l,c]=m.useState(null),[u,d]=m.useState(!1),p=e?`${r.url}${e.path}`:"",h=async()=>{var x;if(!e)return;d(!0);const f=performance.now();try{const y=((x=(await G.auth.getSession()).data.session)==null?void 0:x.access_token)||"",b={method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`,apikey:r.anonKey}};n!=="GET"&&(b.body=i);const v=await fetch(p,b),k=await v.text();let N=k;try{N=JSON.stringify(JSON.parse(k),null,2)}catch{}c({status:v.status,body:N,latency:Math.round(performance.now()-f)})}catch(g){c({status:0,body:`Error: ${g.message}`,latency:Math.round(performance.now()-f)})}finally{d(!1)}};return e?a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"flex items-center gap-2 p-3 border-b",children:[a.jsxs(Ns,{value:n,onValueChange:s,children:[a.jsx(hs,{className:"w-24 h-9 text-xs font-bold",children:a.jsx(ks,{})}),a.jsx(fs,{children:["GET","POST","PUT","DELETE","PATCH"].map(f=>a.jsx(Dt,{value:f,className:"text-xs font-bold",children:f},f))})]}),a.jsx(Cn,{value:p,readOnly:!0,className:"flex-1 h-9 text-xs font-mono bg-secondary"}),a.jsxs(Q,{size:"sm",onClick:h,disabled:u,className:"gap-1.5",children:[u?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(Li,{className:"w-3.5 h-3.5"})," Send"]})]}),a.jsxs("div",{className:"flex-1 flex flex-col overflow-auto",children:[a.jsxs("div",{className:"p-3",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider font-medium",children:"Request Body"}),a.jsx("textarea",{value:i,onChange:f=>o(f.target.value),className:"w-full min-h-[100px] font-mono text-xs bg-secondary rounded-lg p-3 mt-1 resize-none focus:outline-none focus:ring-1 focus:ring-primary/30 border"})]}),l&&a.jsxs("div",{className:"border-t p-3",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[a.jsx(Ge,{variant:l.status>=200&&l.status<300?"default":"destructive",className:"text-[10px]",children:l.status}),a.jsxs("span",{className:"text-xs text-muted-foreground",children:[l.latency,"ms"]})]}),a.jsx("pre",{className:"text-xs font-mono max-h-48 overflow-auto whitespace-pre-wrap bg-secondary rounded-lg p-3 border",children:l.body})]})]})]}):a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(NT,{className:"w-10 h-10 opacity-40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"API Explorer"}),a.jsx("p",{className:"text-xs mt-1",children:"Select an edge function first"})]})}function Zxe({selectedFn:e}){const[t,r]=m.useState("supabase");if(!e)return a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(sd,{className:"w-10 h-10 opacity-40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"SDK Code Generator"}),a.jsx("p",{className:"text-xs mt-1",children:"Select an edge function first"})]});const n=e.function_name,s={supabase:`import { supabase } from "@/integrations/supabase/client";
8191
8192const { data, error } = await supabase.functions.invoke("${n}", {
8193  body: { /* your payload */ },
8194});`,fetch:`const PROJECT_ID = import.meta.env.VITE_SUPABASE_PROJECT_ID;
8195const response = await fetch(
8196  \`https://\${PROJECT_ID}.supabase.co/functions/v1/${n}\`,
8197  { method: "POST", headers: { "Content-Type": "application/json", "Authorization": \`Bearer \${userToken}\` }, body: JSON.stringify({}) }
8198);`,axios:`import axios from "axios";
8199const { data } = await axios.post(\`https://\${PROJECT_ID}.supabase.co/functions/v1/${n}\`, {}, { headers: { "Authorization": \`Bearer \${userToken}\` } });`};return a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[a.jsx("div",{className:"flex gap-1",children:["supabase","fetch","axios"].map(i=>a.jsx("button",{onClick:()=>r(i),className:L("px-3 py-1.5 rounded-md text-xs font-medium transition-colors",t===i?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-secondary"),children:i==="supabase"?"Supabase SDK":i.charAt(0).toUpperCase()+i.slice(1)},i))}),a.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>{navigator.clipboard.writeText(s[t]),W.success("Copied!")},className:"gap-1.5 text-xs",children:[a.jsx(gs,{className:"w-3.5 h-3.5"})," Copy"]})]}),a.jsx("pre",{className:"flex-1 p-4 text-xs font-mono overflow-auto whitespace-pre-wrap bg-secondary/30",children:s[t]})]})}function fM(e){if(!e)return{label:"Unknown",tone:"neutral"};switch(e){case"ACTIVE_HEALTHY":return{label:"Healthy",tone:"good"};
8199case"COMING_UP":return{label:"Provisioning…",tone:"warn"};case"GOING_DOWN":return{label:"Pausing…",tone:"warn"};case"INACTIVE":return{label:"Paused",tone:"neutral"};case"INIT_FAILED":return{label:"Init failed",tone:"bad"};case"REMOVED":return{label:"Removed",tone:"bad"};case"RESTORING":return{label:"Restoring…",tone:"warn"};case"UPGRADING":return{label:"Upgrading…",tone:"warn"};case"PAUSING":return{label:"Pausing…",tone:"warn"};case"RESTART_REQUESTED":return{label:"Restart pending",tone:"warn"};case"UNKNOWN":return{label:"Unknown",tone:"neutral"};default:return{label:e.replace(/_/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase()),tone:"neutral"}}}const mM={good:"bg-emerald-500",warn:"bg-amber-500 animate-pulse",bad:"bg-rose-500",neutral:"bg-muted-foreground"},gM={good:"text-emerald-600",warn:"text-amber-600",bad:"text-rose-600",neutral:"text-muted-foreground"};function Qxe({dbTables:e,projectId:t,infra:r,onRefresh:n}){const s=r.tables.length>0?r.tables:e,i=il(),{migrateSchema:o}=aO(),[l,c]=m.useState(!1),[u,d]=m.useState(null),p=m.useMemo(()=>{if(!(i!=null&&i.files))return null;const g=y=>{for(const b of y){if(b.type==="file"&&b.name==="schema.sql"&&b.content)return b.content;if(b.type==="folder"&&b.children){const v=g(b.children);if(v)return v}}return null};return g(i.files)},[i==null?void 0:i.files]),[h,f]=m.useState(null),x=async()=>{if(!(!t||!p)){c(!0),f(null),console.log(`[run-schema] Sending ${p.length} bytes of SQL to project-db-migrate`);try{const g=await o(t,{sql:p});if(g.success)W.success("Migration applied",{description:"schema.sql executed against your project database."}),f(null),setTimeout(()=>n==null?void 0:n(),1e3);else{const y=g.error||"Unknown error";console.error("[run-schema] Migration failed:",y),f(y),W.error("Migration failed",{description:y.length>200?y.slice(0,200)+"…":y,duration:1e4})}}catch(g){const y=g.message;console.error("[run-schema] Migration threw:",y),f(y),W.error("Migration failed",{description:y,duration:1e4})}finally{c(!1)}}};return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Hn,{className:"w-4 h-4 text-primary"}),a.jsx("h3",{className:"text-sm font-semibold",children:"Database Tables"}),a.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[s.length," tables"]}),r.project_status&&(()=>{const g=fM(r.project_status);return a.jsxs(Ge,{variant:"outline",className:L("text-[9px] gap-1",gM[g.tone]),children:[a.jsx("span",{className:L("w-1.5 h-1.5 rounded-full",mM[g.tone])}),g.label]})})()]}),r.project_url&&a.jsx("span",{className:"text-[10px] text-muted-foreground font-mono",children:r.project_ref})]}),r.status==="not_provisioned"&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a.jsx(Hn,{className:"w-10 h-10 opacity-30 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No Supabase project provisioned"}),a.jsx("p",{className:"text-xs mt-1",children:"Create a new project to auto-provision a dedicated database"})]}),s.length===0&&r.status!=="not_provisioned"?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-muted-foreground space-y-3",children:[a.jsx(Hn,{className:"w-10 h-10 opacity-30"}),a.jsxs("div",{className:"text-center",children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No tables found"}),p?a.jsxs("p",{className:"text-xs mt-1",children:["A ",a.jsx("span",{className:"font-mono text-foreground",children:"schema.sql"})," exists in your files but hasn't been applied yet."]}):a.jsx("p",{className:"text-xs mt-1",children:'Ask the AI to generate a schema (e.g. "add database tables for X")'})]}),p&&t&&a.jsxs(a.Fragment,{children:[a.jsxs(Q,{onClick:x,disabled:l,size:"sm",className:"gap-2",children:[l?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(Hn,{className:"w-3.5 h-3.5"}),l?"Running migration…":"Run schema.sql now"]}),h&&a.jsxs("div",{className:"max-w-md mt-2 px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/5 text-left",children:[a.jsx("p",{className:"text-[10px] uppercase tracking-wider text-rose-600 font-medium mb-0.5",children:"Last error"}),a.jsx("p",{className:"text-[11px] text-rose-700 font-mono whitespace-pre-wrap break-all",children:h})]})]})]}):a.jsxs("div",{className:"space-y-2",children:[a.jsx("div",{className:"px-3 py-2 rounded-lg bg-secondary/40 border border-border/50",children:a.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.jsx("span",{className:"font-medium text-foreground",children:"Source:"})," Live data from your connected Supabase project"," ",a.jsx("span",{className:"font-mono text-[10px]",children:r.project_ref}),". Read directly from ",a.jsx("span",{className:"font-mono",children:"information_schema"})," via the Supabase Management API."]})}),s.map((g,y)=>{const b=u===g.name,v=Array.isArray(g.column_details)?g.column_details:[];return a.jsxs("div",{className:L("border rounded-xl bg-card transition-all",b?"ring-1 ring-primary/30":"hover:bg-secondary/30"),children:[a.jsxs("button",{onClick:()=>d(b?null:g.name),className:"w-full flex items-center gap-3 p-4 text-left",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx(Di,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-semibold font-mono",children:g.name}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[g.columns," columns · ",g.rls?"RLS enabled":"RLS disabled"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[g.rls?a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1 text-emerald-600 border-emerald-500/30",children:[a.jsx(os,{className:"w-3 h-3"})," RLS"]}):a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1 text-amber-600 border-amber-500/30",children:[a.jsx(Ar,{className:"w-3 h-3"})," No RLS"]}),a.jsx(Ge,{variant:"secondary",className:"text-[9px]",children:g.rows!=null?`~${g.rows} rows`:"Active"}),b?a.jsx(Yr,{className:"w-4 h-4 text-muted-foreground"}):a.jsx(ia,{className:"w-4 h-4 text-muted-foreground"})]})]}),b&&v.length>0&&a.jsxs("div",{className:"border-t bg-background/40 px-4 py-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:["Columns (",v.length,")"]}),v.length>8&&a.jsx("span",{className:"text-[9px] text-muted-foreground italic",children:"scroll within"})]}),a.jsx("div",{className:"grid grid-cols-1 gap-1 max-h-80 overflow-y-auto pr-1",children:v.map((k,N)=>a.jsxs("div",{className:"grid grid-cols-12 items-center gap-2 text-[11px] px-2 py-1.5 rounded hover:bg-secondary/40",children:[a.jsxs("div",{className:"col-span-4 font-mono font-medium truncate flex items-center gap-1.5",children:[k.is_pk&&a.jsx(Ge,{variant:"outline",className:"text-[8px] px-1 py-0 h-3.5 border-primary/40 text-primary",children:"PK"}
8199),k.is_fk&&a.jsx(Ge,{variant:"outline",className:"text-[8px] px-1 py-0 h-3.5 border-blue-500/40 text-blue-600",children:"FK"}),a.jsx("span",{className:"truncate",children:k.name})]}),a.jsx("div",{className:"col-span-3 font-mono text-muted-foreground truncate",children:k.type}),a.jsx("div",{className:"col-span-2 text-[10px]",children:k.nullable?a.jsx("span",{className:"text-muted-foreground",children:"nullable"}):a.jsx("span",{className:"text-amber-700",children:"NOT NULL"})}),a.jsxs("div",{className:"col-span-3 font-mono text-[10px] text-muted-foreground truncate",title:k.default||"",children:[k.default?`default: ${k.default}`:"",k.is_unique&&a.jsx("span",{className:"ml-1 text-emerald-600",children:"· unique"})]})]},N))})]}),b&&v.length===0&&a.jsx("div",{className:"border-t px-4 py-3 text-[11px] text-muted-foreground italic",children:"No columns returned (API empty). Try refreshing the panel."})]},y)})]})]})}function eye({projectId:e,infra:t}){const r=t.users,[n,s]=m.useState(null);return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Zl,{className:"w-4 h-4 text-primary"}),a.jsx("h3",{className:"text-sm font-semibold",children:"Auth Users"}),a.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:r.length})]}),t.project_ref&&a.jsx("span",{className:"text-[10px] text-muted-foreground font-mono",children:t.project_ref})]}),t.status==="not_provisioned"?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-muted-foreground",children:[a.jsx(Zl,{className:"w-10 h-10 opacity-30 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No Supabase project provisioned"}),a.jsx("p",{className:"text-xs mt-1",children:"Users will appear once a dedicated backend is provisioned"})]}):r.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-muted-foreground",children:[a.jsx(Zl,{className:"w-10 h-10 opacity-30 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No users yet"}),a.jsx("p",{className:"text-xs mt-1",children:"Users will appear when they sign up to your app"})]}):a.jsx("div",{className:"space-y-1.5",children:r.map(i=>{var h;const o=n===i.id,l=i.user_metadata||{},c=l.full_name||l.name||l.display_name||"",u=l.avatar_url||l.picture||"",d=i.banned_until&&new Date(i.banned_until)>new Date,p=((h=(c||i.email||"?").trim()[0])==null?void 0:h.toUpperCase())||"?";return a.jsxs("div",{className:L("rounded-xl border bg-card transition-all",o&&"ring-1 ring-primary/30"),children:[a.jsxs("button",{onClick:()=>s(o?null:i.id),className:"w-full flex items-center gap-3 px-4 py-3 text-left",children:[u?a.jsx("img",{src:u,alt:"",className:"w-8 h-8 rounded-full object-cover shrink-0"}):a.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-xs font-bold text-primary shrink-0",children:p}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium truncate",children:c||i.email||"Anonymous"}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[c&&i.email&&a.jsx("span",{className:"text-[11px] text-muted-foreground",children:i.email}),i.email_confirmed_at?a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1 text-emerald-600",children:[a.jsx(mn,{className:"w-3 h-3"})," Verified"]}):a.jsx(Ge,{variant:"outline",className:"text-[9px] gap-1 text-amber-600",children:"Unverified"}),d&&a.jsx(Ge,{variant:"outline",className:"text-[9px] text-rose-600 border-rose-500/30",children:"Banned"}),i.is_anonymous&&a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:"Anonymous"}),i.is_sso_user&&a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:"SSO"}),i.mfa_factors&&i.mfa_factors.length>0&&a.jsxs(Ge,{variant:"outline",className:"text-[9px] text-blue-600",children:["MFA · ",i.mfa_factors.length]}),i.providers.map(f=>a.jsx(Ge,{variant:"secondary",className:"text-[9px]",children:f},f))]})]}),a.jsxs("div",{className:"text-right shrink-0",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground",children:i.last_sign_in_at?`Last sign-in ${$s(new Date(i.last_sign_in_at),{addSuffix:!0})}`:"Never signed in"}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Joined ",i.created_at?$s(new Date(i.created_at),{addSuffix:!0}):""]})]})]}),o&&a.jsxs("div",{className:"px-4 pb-4 pt-1 space-y-3 border-t mt
8199-1",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"User ID"}),a.jsx("p",{className:"font-mono text-[11px] break-all",children:i.id})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Role"}),a.jsx("p",{className:"text-[11px]",children:i.role||"authenticated"})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Email"}),a.jsx("p",{className:"text-[11px] break-all",children:i.email||"—"}),i.email_confirmed_at&&a.jsxs("p",{className:"text-[9px] text-muted-foreground mt-0.5",children:["Confirmed ",$s(new Date(i.email_confirmed_at),{addSuffix:!0})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Phone"}),a.jsx("p",{className:"text-[11px]",children:i.phone||"—"}),i.phone_confirmed_at&&a.jsxs("p",{className:"text-[9px] text-muted-foreground mt-0.5",children:["Confirmed ",$s(new Date(i.phone_confirmed_at),{addSuffix:!0})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Created"}),a.jsx("p",{className:"text-[11px]",children:i.created_at?new Date(i.created_at).toLocaleString():"—"})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Updated"}),a.jsx("p",{className:"text-[11px]",children:i.updated_at?new Date(i.updated_at).toLocaleString():"—"})]})]}),i.invited_at&&a.jsxs("div",{className:"text-xs",children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-0.5",children:"Invited"}),a.jsx("p",{className:"text-[11px]",children:new Date(i.invited_at).toLocaleString()})]}),d&&a.jsxs("div",{className:"text-xs bg-rose-500/5 border border-rose-500/20 rounded-lg p-2",children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-rose-600 mb-0.5",children:"Banned until"}),a.jsx("p",{className:"text-[11px] text-rose-700",children:new Date(i.banned_until).toLocaleString()})]}),i.identities&&i.identities.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-1",children:"Linked Identities"}),a.jsx("div",{className:"space-y-1",children:i.identities.map((f,x)=>a.jsxs("div",{className:"flex items-center justify-between text-[11px] px-2 py-1.5 rounded bg-secondary/40",children:[a.jsx(Ge,{variant:"secondary",className:"text-[9px]",children:f.provider}),f.last_sign_in_at&&a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Used ",$s(new Date(f.last_sign_in_at),{addSuffix:!0})]})]},x))})]}),i.mfa_factors&&i.mfa_factors.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-1",children:"MFA Factors"}),a.jsx("div",{className:"space-y-1",children:i.mfa_factors.map(f=>a.jsxs("div",{className:"flex items-center justify-between text-[11px] px-2 py-1.5 rounded bg-secondary/40",children:[a.jsx("span",{children:f.friendly_name||f.factor_type}),a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:f.status})]},f.id))})]}),i.user_metadata&&Object.keys(i.user_metadata).length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-[9px] uppercase tracking-wider text-muted-foreground/70 mb-1",children:"User Metadata"}),a.jsx("pre",{className:"text-[10px] font-mono bg-secondary/40 rounded p-2 overflow-x-auto whitespace-pre-wrap break-all",children:JSON.stringify(i.user_metadata,null,2)})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground/70 pt-1 border-t italic",children:"Password hashes, recovery tokens, and MFA secrets are never exposed — Supabase strips them at the API layer."})]})]},i.id)})})]})}function tye({buildLogs:e}){const t=r=>{r&&(window.dispatchEvent(new CustomEvent("sj:chat-prefill",{detail:{prompt:r}}
8199)),W.success("Prompt loaded into chat — review and send",{duration:3e3}))};return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-4",children:[a.jsx("div",{className:"flex items-center justify-between",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ai,{className:"w-4 h-4 text-primary"}),a.jsx("h3",{className:"text-sm font-semibold",children:"Build Logs"}),a.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[e.length," builds"]})]})}),e.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-muted-foreground",children:[a.jsx(ai,{className:"w-10 h-10 opacity-30 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No build logs"}),a.jsx("p",{className:"text-xs mt-1",children:"Logs will appear when you start building"})]}):a.jsx("div",{className:"space-y-2",children:e.map(r=>{var o;const n=r.started_at?new Date(r.started_at).getTime():r.created_at?new Date(r.created_at).getTime():Date.now(),i=r.status==="running"&&Date.now()-n>10*60*1e3?"abandoned":r.status;return a.jsxs("div",{className:"border rounded-xl p-4 bg-card",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[i==="completed"?a.jsx(mn,{className:"w-4 h-4 text-emerald-500"}):i==="failed"||i==="error"?a.jsx(aa,{className:"w-4 h-4 text-destructive"}):i==="abandoned"?a.jsx(Ar,{className:"w-4 h-4 text-muted-foreground/70"}):a.jsx(ze,{className:"w-4 h-4 text-amber-500 animate-spin"}),a.jsx("p",{className:"text-sm font-medium flex-1 truncate",children:((o=r.prompt)==null?void 0:o.slice(0,80))||"Build"}),a.jsx(Ge,{variant:i==="completed"?"default":i==="failed"?"destructive":"secondary",className:"text-[9px]",children:i}),r.prompt&&i!=="running"&&a.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>t(r.prompt),className:"h-6 px-2 text-[10px] gap-1",title:"Load this prompt back into the chat composer",children:[a.jsx(zr,{className:"w-3 h-3"})," Re-run"]})]}),a.jsxs("div",{className:"flex items-center gap-4 text-[10px] text-muted-foreground",children:[r.files_generated!=null&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tl,{className:"w-3 h-3"})," ",r.files_generated," files"]}),r.duration_ms!=null&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Lr,{className:"w-3 h-3"})," ",(r.duration_ms/1e3).toFixed(1),"s"]}),r.created_at&&a.jsx("span",{children:$s(new Date(r.created_at),{addSuffix:!0})})]})]},r.id)})})]})}function nye({buildLogs:e,projectId:t}){const{summary:r,loading:n,refresh:s}=Wxe(t),i=e.reduce((l,c)=>l+(c.duration_ms||0),0);e.reduce((l,c)=>l+(c.files_generated||0),0);const o=e.length>0?Math.round(e.filter(l=>l.status==="completed").length/e.length*100):0;return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ip,{className:"w-4 h-4 text-primary"}),a.jsx("h3",{className:"text-sm font-semibold",children:"AI Credits & Usage"})]}),a.jsxs(Q,{variant:"ghost",size:"sm",onClick:s,className:"gap-1.5 text-xs",children:[a.jsx(zr,{className:L("w-3.5 h-3.5",n&&"animate-spin")})," Refresh"]})]}),a.jsxs("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 to-primary/10 p-5",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/15 flex items-center justify-center",children:a.jsx(hr,{className:"w-5 h-5 text-primary"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-semibold",children:"Credit Usage"}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Tracks every AI request for billing"})]})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{className:"bg-background/60 rounded-lg p-3 text-center",children:[a.jsx("p",{className:"text-2xl font-bold",children:r.dailyCreditsUsed.toFixed(1)}),a.jsx("p",{className:"text-[10px] text-muted-foreground font-medium",children:"Today"})]}),a.jsxs("div",{className:"bg-background/60 rounded-lg p-3 text-center",children:[a.jsx("p",{className:"text-2xl font-bold",children:r.monthlyCreditsUsed.toFixed(1)}),a.jsx("p",{className:"text-[10px] text-muted-foreground font-medium",children:"This Month"})]}),a.jsxs("div",{className:"bg-background/60 rounded-lg p-3 text-center",children:[a.jsx("p",{className:"text-2xl font-bold",children:r.totalCreditsUsed.toFixed(1)}),a.jsx("p",{className:"text-[10px] text-muted-foreground font-medium",children:"All Time"})]})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-3",children:[{label:"Total Requests",value:r.totalRequests||e.length,icon:lc},{label:"Total Tokens",value:r.totalTokens>1e3?`${(r.totalTokens/1e3).toFixed(1)}k`:r.totalTokens,icon:Tk},{label:"Avg Duration",value:r.totalRequests>0?`${(i/Math.max(e.length,1)/1e3).toFixed(1)}s`:"0s",icon:Lr},{label:"Success Rate",value:`${o}%`,icon:Sw}
8199].map(l=>a.jsxs("div",{className:"border rounded-xl p-4 bg-card",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(l.icon,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:l.label})]}),a.jsx("p",{className:"text-xl font-bold",children:l.value})]},l.label))}),Object.keys(r.byModel).length>0&&a.jsxs("div",{children:[a.jsxs("h4",{className:"text-xs font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Tk,{className:"w-3.5 h-3.5 text-primary"})," Credits by Route"]}),a.jsx("div",{className:"space-y-2",children:Object.entries(r.byModel).sort(([,l],[,c])=>c.credits-l.credits).map(([l,c],u)=>{const d=r.totalRequests>0?c.count/r.totalRequests*100:0;return a.jsxs("div",{className:"border rounded-xl p-3 bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("span",{className:"text-xs font-semibold",children:["Route ",u+1]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1",children:[a.jsx(hr,{className:"w-2.5 h-2.5"})," ",c.credits.toFixed(1)," credits"]}),a.jsxs(Ge,{variant:"secondary",className:"text-[9px]",children:[c.count," calls"]})]})]}),a.jsx("div",{className:"w-full h-2 bg-secondary rounded-full overflow-hidden mb-2",children:a.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${d}%`}})}),a.jsxs("div",{className:"flex gap-4 text-[10px] text-muted-foreground",children:[a.jsxs("span",{children:[c.tokens>1e3?`${(c.tokens/1e3).toFixed(1)}k`:c.tokens," tokens"]}),a.jsxs("span",{children:[Math.round(d),"% of total"]})]})]},l)})})]}),Object.keys(r.byMode).length>0&&a.jsxs("div",{children:[a.jsxs("h4",{className:"text-xs font-semibold mb-3 flex items-center gap-2",children:[a.jsx(si,{className:"w-3.5 h-3.5 text-primary"})," Credits by Mode"]}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:Object.entries(r.byMode).sort(([,l],[,c])=>c.credits-l.credits).map(([l,c])=>a.jsxs("div",{className:"border rounded-lg px-4 py-3 bg-card flex-1 min-w-[120px]",children:[a.jsx("p",{className:"text-xs font-semibold capitalize",children:l.replace(/-/g," ")}),a.jsx("p",{className:"text-lg font-bold mt-1",children:c.credits.toFixed(1)}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[c.count," requests"]})]},l))})]}),r.recentLogs.length>0&&a.jsxs("div",{children:[a.jsxs("h4",{className:"text-xs font-semibold mb-3 flex items-center gap-2",children:[a.jsx(ai,{className:"w-3.5 h-3.5 text-primary"})," Recent AI Requests"]}),a.jsx("div",{className:"space-y-1.5 max-h-[300px] overflow-auto",children:r.recentLogs.slice(0,20).map(l=>a.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5 rounded-lg border bg-card",children:[a.jsx("div",{className:L("w-2 h-2 rounded-full shrink-0",l.status==="completed"?"bg-emerald-500":"bg-destructive")}
8199),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs font-medium truncate",children:l.mode||"AI request"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:l.endpoint})]}),a.jsxs("div",{className:"text-right shrink-0 space-y-0.5",children:[a.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[a.jsx(hr,{className:"w-2.5 h-2.5 text-primary"}),a.jsx("span",{className:"text-[10px] font-semibold",children:Number(l.credits_used).toFixed(1)})]}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[l.total_tokens>1e3?`${(l.total_tokens/1e3).toFixed(1)}k`:l.total_tokens," tok",l.duration_ms?` · ${(l.duration_ms/1e3).toFixed(1)}s`:""]}),a.jsx("p",{className:"text-[9px] text-muted-foreground",children:l.created_at?$s(new Date(l.created_at),{addSuffix:!0}):""})]})]},l.id))})]}),r.totalRequests===0&&e.length===0&&!n&&a.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[a.jsx(Ip,{className:"w-8 h-8 opacity-30 mx-auto mb-2"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No AI usage yet"}),a.jsx("p",{className:"text-xs mt-1",children:"Credits will be tracked as you build"})]}),r.totalRequests===0&&e.length>0&&!n&&a.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/5 p-4 text-[12px] text-foreground",children:[a.jsxs("p",{className:"font-medium",children:[e.length," legacy build",e.length===1?"":"s"," not tracked here yet"]}),a.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Per-request credit logging shipped recently. Builds before that show in ",a.jsx("strong",{children:"Build Logs"})," but not in this tab. New builds will appear here automatically."]})]})]})}function rye({secrets:e,onRefresh:t,onRemoveSecret:r}){const[n,s]=m.useState(new Set),[i,o]=m.useState(null);return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Bs,{className:"w-4 h-4 text-primary"}),a.jsx("h3",{className:"text-sm font-semibold",children:"Project Secrets"}),a.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:e.length})]}),a.jsxs(Q,{variant:"ghost",size:"sm",onClick:t,className:"gap-1.5 text-xs",children:[a.jsx(zr,{className:"w-3.5 h-3.5"})," Refresh"]})]}),e.length===0?a.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[a.jsx(Bs,{className:"w-8 h-8 mx-auto mb-2 opacity-40"}),a.jsx("p",{className:"text-sm",children:"No secrets required yet"}),a.jsx("p",{className:"text-xs mt-1",children:"Secrets will be auto-detected when edge functions are created"})]}):a.jsx("div",{className:"space-y-1.5",children:e.map(l=>a.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl bg-card border",children:[a.jsx(Bs,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),a.jsx("span",{className:"text-xs font-mono font-medium flex-1 truncate",children:l.secret_name}),a.jsx(Ge,{variant:l.is_configured?"default":"outline",className:"text-[9px]",children:l.is_configured?"Configured":"Pending"}),a.jsx("button",{onClick:()=>s(c=>{const u=new Set(c);return u.has(l.secret_name)?u.delete(l.secret_name):u.add(l.secret_name),u}),className:"text-muted-foreground hover:text-foreground transition-colors",children:n.has(l.secret_name)?a.jsx(ku,{className:"w-3.5 h-3.5"}):a.jsx(ys,{className:"w-3.5 h-3.5"})}),a.jsx("button",{disabled:i===l.id,onClick:async()=>{if(window.confirm(`Delete secret "${l.secret_name}" from this project vault?`)){o(l.id);try{await r(l.id),W.success(`Deleted ${l.secret_name}`)}catch(c){W.error(c instanceof Error?c.message:"Could not delete secret")}finally{o(null)}}},className:"text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50",title:"Delete secret",children:a.jsx(oa,{className:"w-3.5 h-3.5"})})]},l.id))})]})}function sye(e){if(!e)return"Direct";try{return new URL(e).host.replace(/^www\./,"")||"Direct"}catch{return e.replace(/^https?:\/\//,"").split("/")[0]||"Direct"}}
8199function aye(e){return e.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function iye(e){if(!Number.isFinite(e)||e<=0)return"0s";const t=Math.floor(e/60),r=Math.round(e%60);return t<=0?`${r}s`:`${t}m ${r.toString().padStart(2,"0")}s`}function oye({projectId:e}){const[t,r]=m.useState(7),[n,s]=m.useState([]),[i,o]=m.useState([]),[l,c]=m.useState(!1),u=m.useCallback(async()=>{if(!e)return;c(!0);const x=new Date(Date.now()-t*24*60*60*1e3).toISOString(),[g,y]=await Promise.all([G.from("cloud_analytics_events").select("id,path,referrer,visitor_key,session_key,created_at").eq("project_id",e).gte("created_at",x).order("created_at",{ascending:!0}).limit(5e3),G.from("cloud_deployments").select("slug,url,status").eq("project_id",e).neq("status","deleted").order("updated_at",{ascending:!1})]);g.error?(console.warn("[cloud-analytics] events fetch failed:",g.error.message),s([])):s(g.data||[]),o(y.data||[]),c(!1)},[e,t]);m.useEffect(()=>{u()},[u]);const d=m.useMemo(()=>{const x=new Set(n.map(P=>P.visitor_key)).size,g=new Map;for(const P of n){const E=g.get(P.session_key)||[];E.push(P),g.set(P.session_key,E)}let y=0,b=0,v=0;g.forEach(P=>{if(P.sort((_,I)=>new Date(_.created_at).getTime()-new Date(I.created_at).getTime()),P.length<=1){v+=1;return}const E=(new Date(P[P.length-1].created_at).getTime()-new Date(P[0].created_at).getTime())/1e3;y+=Math.max(0,E),b+=1});const k=new Set(n.filter(P=>Date.now()-new Date(P.created_at).getTime()<5*60*1e3).map(P=>P.visitor_key)).size,N=b?y/b:0,j=g.size?Math.round(v/g.size*100):0,w=new Map;for(let P=t-1;P>=0;P--){const E=new Date(Date.now()-P*24*60*60*1e3),_=E.toISOString().slice(0,10);w.set(_,{date:aye(E),visitors:new Set,pageviews:0})}for(const P of n){const E=new Date(P.created_at).toISOString().slice(0,10),_=w.get(E);_&&(_.visitors.add(P.visitor_key),_.pageviews+=1)}const S=new Map,T=new Map;for(const P of n){const E=sye(P.referrer);S.has(E)||S.set(E,new Set),S.get(E).add(P.visitor_key);const _=P.path||"/";T.has(_)||T.set(_,new Set),T.get(_).add(P.visitor_key)}const C=Array.from(S.entries()).map(([P,E])=>({label:P,visitors:E.size})).sort((P,E)=>E.visitors-P.visitors).slice(0,5),A=Array.from(T.entries()).map(([P,E])=>({label:P,visitors:E.size})).sort((P,E)=>E.visitors-P.visitors).slice(0,6);return{activeVisitors:k,visitors:x,pageviews:n.length,viewsPerVisit:n.length&&g.size?(n.length/g.size).toFixed(2):"0.00",avgDuration:N,bounceRate:j,chartData:Array.from(w.values()).map(P=>({date:P.date,visitors:P.visitors.size,pageviews:P.pageviews})),topSources:C,topPages:A}},[n,t]),p=Math.max(1,...d.topSources.map(x=>x.visitors)),h=Math.max(1,...d.topPages.map(x=>x.visitors)),f=i.some(x=>x.status==="active");return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-5",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[a.jsx(si,{className:"w-4 h-4 text-primary"}),"Published Analytics"]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Traffic captured from Studio Jungle Cloud published URLs."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ge,{variant:"outline",className:"gap-1.5 h-8 px-3",children:[a.jsx("span",{className:L("w-2 h-2 rounded-full",d.activeVisitors>0?"bg-emerald-500 animate-pulse":"bg-muted-foreground")}),d.activeVisitors," current visitors"]}),a.jsxs(Ns,{value:String(t),onValueChange:x=>r(Number(x)),children:[a.jsx(hs,{className:"h-8 w-[130px] text-xs",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"7",children:"Last 7 days"}),a.jsx(Dt,{value:"30",children:"Last 30 days"}),a.jsx(Dt,{value:"90",children:"Last 90 days"})]})]}),a.jsxs(Q,{variant:"outline",size:"sm",onClick:u,disabled:l,className:"h-8 gap-1.5 text-xs",children:[a.jsx(zr,{className:L("w-3.5 h-3.5",l&&"animate-spin")}),"Refresh"]})]})]}),!f&&a.jsxs("div",{className:"rounded-xl border bg-amber-500/5 border-amber-500/20 p-4",children:[a.jsx("p",{className:"text-sm font-semibold",children:"Publish this project to start analytics"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Analytics starts collecting after a Studio Jungle Cloud deployment is active."})]}),a.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-5",children:[{label:"Visitors",value:d.visitors.toLocaleStr
8199ing(),accent:!0},{label:"Pageviews",value:d.pageviews.toLocaleString()},{label:"Views / Visit",value:d.viewsPerVisit},{label:"Visit Duration",value:iye(d.avgDuration)},{label:"Bounce Rate",value:`${d.bounceRate}%`}].map(x=>a.jsxs("div",{className:L("rounded-xl border bg-card p-4 shadow-sm",x.accent&&"border-primary/40 ring-1 ring-primary/20"),children:[a.jsx("p",{className:L("text-xs font-semibold",x.accent?"text-primary":"text-muted-foreground"),children:x.label}),a.jsx("p",{className:"mt-4 text-2xl font-semibold tracking-tight",children:x.value})]},x.label))}),a.jsxs("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:[a.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[a.jsx("p",{className:"text-sm font-semibold",children:"Visitors over time"}),a.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[n.length," events"]})]}),a.jsx("div",{className:"h-[340px]",children:a.jsx(dm,{width:"100%",height:"100%",children:a.jsxs(_me,{data:d.chartData,margin:{top:12,right:18,left:0,bottom:4},children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"sjVisitors",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.26}),a.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),a.jsx(Ig,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),a.jsx(nl,{dataKey:"date",tickLine:!1,axisLine:!1,tick:{fontSize:12,fill:"hsl(var(--muted-foreground))"}}),a.jsx(rl,{tickLine:!1,axisLine:!1,tick:{fontSize:12,fill:"hsl(var(--muted-foreground))"},allowDecimals:!1}),a.jsx(ga,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))",background:"hsl(var(--card))"},labelStyle:{fontWeight:700,color:"hsl(var(--foreground))"}}),a.jsx(ml,{type:"monotone",dataKey:"visitors",stroke:"hsl(var(--primary))",strokeWidth:2.5,fill:"url(#sjVisitors)"}),a.jsx(gd,{type:"monotone",dataKey:"pageviews",stroke:"hsl(var(--muted-foreground))",strokeWidth:1.5,dot:!1})]})})})]}),a.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[a.jsx(d_,{title:"Top sources",rows:d.topSources,max:p,empty:"No referrers yet."}),a.jsx(d_,{title:"Top pages",rows:d.topPages,max:h,empty:"No page traffic yet."})]})]})}function d_({title:e,rows:t,max:r,empty:n}){return a.jsxs("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:[a.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[a.jsx("p",{className:"text-sm font-semibold",children:e}),a.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Visitors"})]}),t.length===0?a.jsx("p",{className:"text-sm text-muted-foreground",children:n}):a.jsx("div",{className:"space-y-3",children:t.map(s=>a.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3",children:[a.jsx("div",{className:"min-w-0",children:a.jsxs("div",{className:"relative h-9 overflow-hidden rounded-lg bg-secondary",children:[a.jsx("div",{className:"absolute inset-y-0 left-0 rounded-lg bg-primary/15",style:{width:`${Math.max(8,s.visitors/r*100)}%`}}),a.jsx("div",{className:"relative flex h-full items-center px-3 text-sm font-medium",children:a.jsx("span",{className:"truncate",children:s.label})})]})}),a.jsx("span",{className:"w-10 text-right text-sm font-semibold tabular-nums",children:s.visitors})]},s.label))})]})}function lye({functions:e,fileTreeFunctions:t,buildLogs:r,backend:n}){const s=new Set(e.map(x=>x.function_name)),i=[...e.map(x=>({name:x.function_name,displayName:x.display_name,status:x.status,source:"registered"})),...t.filter(x=>!s.has(x.name)).map(x=>({name:x.name,displayName:x.name.replace(/-/g," ").replace(/\b\w/g,g=>g.toUpperCase()),status:"deployed",source:"file-tree"}))],o=r[0],l=r.filter(x=>x.status==="completed").slice(0,10),[c,u]=m.useState({}),[d,p]=m.useState(!1),h=m.useCallback(async x=>{u(y=>({...y,[x]:{status:null,latency:0,checking:!0}}));const g=performance.now();try{const y=`${n.url}/functions/v1/${x}`,b=await fetch(y,{method:"OPTIONS",headers:{apikey:n.anonKey}}),v=Math.round(performance.now()-g);u(k=>({...k,[x]:{status:b.status,latency:v,checking:!1}}))}catch(y){const b=Math.round(performance.now()-g);u(v=>({...v,[x]:{status:null,latency:b,error:y.message,checking:!1}}))}},[n]),f=m.useCallback(async()=>{p(!0),await Promise.all(i.map(x=>h(x.name))),p(!1)},[i,h]);return a.jsxs("div",{className:"h-full overflow-auto p-5 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Es,{className:"w-4 h-4 text-primary"}),a.jsx("h3",{className:"text-sm font-semibold",children:"Deployments"})]}),i.length>0&&a.jsxs(Q,{variant:"outline",size:"sm",onClick:f,disabled:d,className:"gap-1.5 text-xs",children:[d?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(lc,{className:"w-3.5 h-3.5"}),"Health Check All"]})]}),a.jsx("div",{className:"rounded-xl border p-3 bg-secondary/30",children:a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx(Br,{className:"w-3.5 h-3.5 text-primary shrink-0"}),a.jsx("span",{className:"font-medium",children:"API Base:"}),a.jsxs("code",{className:"text-[11px] font-mono text-muted-foreground flex-1 truncate",children:[n.url,"/functions/v1/"]}),a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1",children:[a.jsx("span",{className:L("w-1.5 h-1.5 rounded-full",n.source==="cloud"?"bg-emerald-500":n.source==="byos"?"bg-amber-500":"bg-blue-500")}),n.source==="cloud"?"Project Instance":n.source==="byos"?"BYOS":"Platform"]})]})}
8199),a.jsx("div",{className:L("rounded-xl border p-4",(o==null?void 0:o.status)==="completed"?"bg-emerald-500/5 border-emerald-500/20":"bg-amber-500/5 border-amber-500/20"),children:a.jsxs("div",{className:"flex items-center gap-3",children:[(o==null?void 0:o.status)==="completed"?a.jsx(mn,{className:"w-5 h-5 text-emerald-500"}):o?a.jsx(Ar,{className:"w-5 h-5 text-amber-500"}):a.jsx(Br,{className:"w-5 h-5 text-muted-foreground"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold",children:o?o.status==="completed"?"Last deploy successful":"Last deploy had issues":"No deployments yet"}),(o==null?void 0:o.created_at)&&a.jsx("p",{className:"text-[10px] text-muted-foreground",children:$s(new Date(o.created_at),{addSuffix:!0})})]})]})}),a.jsxs("div",{children:[a.jsxs("h4",{className:"text-xs font-semibold mb-3 flex items-center gap-2",children:[a.jsx(sa,{className:"w-3.5 h-3.5 text-primary"})," Edge Functions (",i.length,")"]}),i.length===0?a.jsx("p",{className:"text-xs text-muted-foreground",children:"No edge functions to deploy"}):a.jsx("div",{className:"space-y-1.5",children:i.map(x=>{var y;const g=c[x.name];return a.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl border bg-card",children:[a.jsx("div",{className:L("w-2.5 h-2.5 rounded-full shrink-0",x.status==="deployed"?"bg-emerald-500":x.status==="error"?"bg-destructive":"bg-amber-500")}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium truncate",children:x.displayName}),a.jsxs("p",{className:"text-[10px] text-muted-foreground font-mono",children:["/functions/v1/",x.name]})]}),g&&a.jsx("div",{className:"flex items-center gap-1.5",children:g.checking?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin text-muted-foreground"}):g.status&&g.status<400?a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1 text-emerald-600 border-emerald-500/30",children:[a.jsx(mn,{className:"w-3 h-3"})," ",g.latency,"ms"]}):a.jsxs(Ge,{variant:"outline",className:"text-[9px] gap-1 text-destructive border-destructive/30",children:[a.jsx(aa,{className:"w-3 h-3"})," ",((y=g.error)==null?void 0:y.slice(0,20))||`${g.status}`]})}),a.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>h(x.name),disabled:g==null?void 0:g.checking,children:a.jsx(lc,{className:"w-3 h-3"})}),a.jsx(Ge,{variant:x.status==="deployed"?"default":"secondary",className:"text-[9px] gap-1",children:x.status==="deployed"?a.jsxs(a.Fragment,{children:[a.jsx(mn,{className:"w-3 h-3"})," Live"]}):x.status}),x.source==="file-tree"&&a.jsx(Ge,{variant:"outline",className:"text-[9px]",children:"Auto"})]},x.name)})})]}),l.length>0&&a.jsxs("div",{children:[a.jsxs("h4",{className:"text-xs font-semibold mb-3 flex items-center gap-2",children:[a.jsx(Lr,{className:"w-3.5 h-3.5 text-primary"})," Deploy History"]}),a.jsx("div",{className:"space-y-1.5",children:l.map(x=>{var g;return a.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-lg border bg-card",children:[a.jsx(mn,{className:"w-3.5 h-3.5 text-emerald-500 shrink-0"}),a.jsx("p",{className:"text-xs flex-1 truncate",children:((g=x.prompt)==null?void 0:g.slice(0,50))||"Build"}),a.jsxs("span",{className:"text-[10px] text-muted-foreground shrink-0",children:[x.files_generated||0," files · ",x.created_at?$s(new Date(x.created_at),{addSuffix:!0}):""]})]},x.id)})})]})]})}function cye({projectId:e,projectName:t,compact:r}){const{functions:n,secrets:s,loading:i,removeFunction:o,addFunction:l,removeSecret:c,refresh:u}=W1(e),{resolved:d,loading:p}=hM(e),{infra:h,loading:f,refresh:x}=zh(e),g=il(),y=(g==null?void 0:g.files)??[],[b,v]=m.useState(null),[k,N]=m.useState("overview"),[j,w]=m.useState([]),[S,T]=m.useState([]),C=m.useMemo(()=>Kxe(y),[y]);m.useEffect(()=>{e&&(async()=>{const{data:_}=await G.from("build_logs").select("*").eq("project_id",e).order("created_at",{ascending:!1}).limit(100);w(_||[])})()},[e]),m.useEffect(()=>{!e||h.tables.length>0||(async()=>{var I;const{data:_}=await G.from("db_connections").select("cached_schema").eq("project_id",e).eq("is_active",!0).limit(1);if((I=_==null?void 0:_[0])!=null&&I.cached_schema){const D=_[0].cached_schema,M=Array.isArray(D)?D:D.tables||[];T(M.map(B=>{var $;return{name:B.table_name||B.name||"unknown",columns:(($=B.columns)==null?void 0:$.length)||B.column_count||0,rls:B.rls_enabled??!1,rows:B.row_count??null}}))}else T([])})()},[e,h.tables.length,y]);const A=m.useCallback(()=>{u(),x()},[u,x]);if(m.useEffect(()=>{const _=I=>{const D=I.detail;D!=null&&D.projectId&&D.projectId!==e||A()};return window.addEventListener("sj:infra-changed",_),()=>window.removeEventListener("sj:infra-changed",_)},[e,A]),r){const _=n.length+C.filter(I=>!n.some(D=>D.function_name===I.name)).length;return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:L("flex items-center gap-2 rounded-lg px-3 py-2 text-xs",d.source==="byos"?"bg-amber-500/10 text-amber-700":"bg-primary/10 text-primary"),children:d.source==="byos"?a.jsxs(a.Fragment,{children:[a.jsx(Is,{className:"w-3.5 h-3.5"})," Custom Backend (",d.host,")"]}):a.jsxs(a.Fragment,{children:[a.jsx(os,{className:"w-3.5 h-3.5"})," StudioJungle Cloud"]})}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ya,{className:"w-4 h-4 text-primary"}),a.jsx("span",{className:"text-sm font-semibold",children:"Cloud"})]}),a.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[_," functions"]})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[a.jsxs("div",{className:"border rounded-lg p-2",children:[a.jsx("p",{className:"text-lg font-bold",children:_}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Functions"})]}),a.jsxs("div",{className:"border rounded-lg p-2",children:[a.jsx("p",{className:"text-lg font-bold",children:h.tables.length||S.length}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Tables"})]}),a.jsxs("div",{className:"border rounded-lg p-2",children:[a.jsx("p",{className:"text-lg font-bold",children:h.users.length}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Users"})]})]})]})}const P=h.tables.length||S.length,E=[{items:[{id:"overview",label:"Overview",icon:si}]},{heading:"Data",items:[{id:"database",label:"Database",icon:Hn,count:P},{id:"users",label:"Users",icon:Zl,count:h.users.length}]},{heading:"Code",items:[{id:"functions",label:"Edge Functions",icon:sa,count:(h.functions.length||n.length)+C.filter(_=>!n.some(I=>I.function_name===_.name)).length},{id:"secrets",label:"Secrets",icon:Bs,count:s.length}]},{heading:"Activity",items:[{id:"deployments",label:"Deployments",icon:Es},{id:"analytics",label:"Analytics",icon:Sw},{id:"logs",label:"Build Logs",icon:ai,count:j.length},{id:"ai-usage",label:"AI Usage",icon:Ip}]},{heading:"Admin",items:[{id:"settings",label:"Settings",icon:wT}]}];return a.jsxs("div",{className:"h-full flex flex-col bg-background",children:[a.jsx("div",{className:"px-5 py-3 border-b bg-card shrink-0",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center",children:a.jsx(ya,{className:"w-4 h-4 text-primary"})}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-sm font-semibold",children:"Cloud"}),a.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[t||"Project"," ",h.status==="provisioned"&&h.project_ref?`· ${h.project_ref}`:""]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[h.project_status&&(()=>{const _=fM(h.project_status);return a.jsxs(Ge,{variant:"outline",className:L("gap-1.5 px-2 py-0.5 text-[10px]",gM[_.tone]),children:[a.jsx("span",{className:L("w-1.5 h-1.5 rounded-full",mM[_.tone])}),_.label]})})(),a.jsx(Ge,{variant:d.source==="byos"?"outline":"secondary",className:L("gap-1 px-2 py-0.5 text-[10px]",d.source==="byos"&&"border-amber-500/30 text-amber-700 bg-amber-500/5"),children:d.source==="byos"?a.jsxs(a.Fragment,{children:[a.jsx(Is,{className:"w-3 h-3"})," BYOS"]}
8199):a.jsxs(a.Fragment,{children:[a.jsx(os,{className:"w-3 h-3"})," Platform"]})}),a.jsx(Q,{variant:"ghost",size:"sm",onClick:A,className:"h-7 w-7 p-0",children:a.jsx(zr,{className:L("w-3.5 h-3.5",f&&"animate-spin")})})]})]})}),a.jsxs("div",{className:"flex-1 flex overflow-hidden min-h-0",children:[a.jsx("aside",{className:"w-52 shrink-0 border-r bg-card/40 overflow-y-auto py-3",children:E.map((_,I)=>a.jsxs("div",{className:L("px-2",I>0&&"mt-4"),children:[_.heading&&a.jsx("div",{className:"px-3 mb-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/70",children:_.heading}),a.jsx("div",{className:"space-y-0.5",children:_.items.map(D=>{const M=k===D.id;return a.jsxs("button",{onClick:()=>N(D.id),className:L("w-full flex items-center gap-2.5 px-3 py-1.5 rounded-md text-[12.5px] font-medium transition-colors",M?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-secondary/60"),children:[a.jsx(D.icon,{className:L("w-3.5 h-3.5 shrink-0",M&&"text-primary")}),a.jsx("span",{className:"flex-1 text-left",children:D.label}),D.count!=null&&D.count>0&&a.jsx("span",{className:L("text-[10px] px-1.5 py-px rounded-full font-semibold tabular-nums",M?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:D.count})]},D.id)})})]},I))}),a.jsxs("div",{className:"flex-1 overflow-hidden min-w-0",children:[k==="overview"&&a.jsx(Yxe,{functions:n,fileTreeFunctions:C,secrets:s,buildLogs:j,dbTables:S,projectId:e,projectName:t,backend:d,infra:h,onRefreshInfra:x}),k==="functions"&&a.jsx(Jxe,{functions:n,fileTreeFunctions:C,selectedFn:b,setSelectedFn:v,removeFunction:o,loading:i,backend:d,projectId:e,secrets:s,refresh:u,addFunction:l}),k==="database"&&a.jsx(Qxe,{dbTables:S,projectId:e,infra:h,onRefresh:x}),k==="users"&&a.jsx(eye,{projectId:e,infra:h}),k==="deployments"&&a.jsx(lye,{functions:n,fileTreeFunctions:C,buildLogs:j,backend:d}),k==="analytics"&&a.jsx(oye,{projectId:e}),k==="logs"&&a.jsx(tye,{buildLogs:j}),k==="ai-usage"&&a.jsx(nye,{buildLogs:j,projectId:e}),k==="secrets"&&a.jsx(rye,{secrets:s,onRefresh:u,onRemoveSecret:c}),k==="settings"&&a.jsx("div",{className:"h-full overflow-auto p-5",children:a.jsx(Vxe,{projectId:e})})]})]})]})}function uye(e){const[t,r]=m.useState(null),[n,s]=m.useState([]),[i,o]=m.useState([]),[l,c]=m.useState(!1);return m.useEffect(()=>{if(!e){r(null),s([]),o([]);return}c(!0);let u=!1;(async()=>{const[{data:p},{data:h},{data:f}]=await Promise.all([G.from("agent_runs").select("*").eq("id",e).maybeSingle(),G.from("agent_messages").select("*").eq("run_id",e).order("created_at"),G.from("agent_reviews").select("*").eq("run_id",e).order("round")]);u||(p&&r(p),h&&s(h),f&&o(f),c(!1))})();const d=G.channel(`agent_run_${e}`).on("postgres_changes",{event:"*",schema:"public",table:"agent_runs",filter:`id=eq.${e}`},p=>{(p.eventType==="UPDATE"||p.eventType==="INSERT")&&r(p.new)}).on("postgres_changes",{event:"INSERT",schema:"public",table:"agent_messages",filter:`run_id=eq.${e}`},p=>{s(h=>[...h,p.new])}).on("postgres_changes",{event:"INSERT",schema:"public",table:"agent_reviews",filter:`run_id=eq.${e}`},p=>{o(h=>[...h,p.new])}).subscribe();return()=>{u=!0,G.removeChannel(d)}},[e]),{run:t,messages:n,reviews:i,loading:l}}const dye={planner:{label:"Planner",icon:sT,tagline:"Turns prompt into PRD"},architect:{label:"Architect",icon:E$,tagline:"Schema, routes, build order"},builder:{label:"Builder",icon:sa,tagline:"Generates code"},reviewer:{label:"Reviewer",icon:ys,tagline:"Catches bugs before shipping"},tester:{label:"Tester",icon:el,tagline:"Generates Playwright tests"}};function pye(e,t,r){return t?t.current_agent===e?"running":r?t.status==="failed"&&t.current_agent===null?"error":"done":(t.status==="failed","idle"):"idle"}const hye={idle:{label:"Idle",cls:"bg-muted text-muted-foreground",Icon:Lr},running:{label:"Running",cls:"bg-amber-500/10 text-amber-700 animate-pulse",Icon:ze},done:{label:"Done",cls:"bg-emerald-500/10 text-emerald-700",Icon:mn},error:{label:"Error",cls:"bg-rose-500/10 text-rose-700",Icon:Ar}};function fye({name:e,run:t,latestOutput:r,totalRounds:n}){const[s,i]=m.useState(!1),o=dye[e],l=pye(e,t,r),c=hye[l],u=o.icon,d=c.Icon,p=e==="builder"&&n>1,h=((r==null?void 0:r.cost_cents)??0)/100,f=(r==null?void 0:r.duration_ms)??0,x=(r==null?void 0:r.tokens_in)??0,g=(r==null?void 0:r.tokens_out)??0;return a.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[a.jsxs("button",{type:"button",onClick:()=>i(y=>
8199!y),className:"w-full flex items-center gap-3 p-3.5 text-left hover:bg-muted/30 transition-colors",children:[a.jsx("div",{className:L("w-9 h-9 rounded-md flex items-center justify-center shrink-0",l==="running"?"bg-amber-500/10 text-amber-600":l==="done"?"bg-emerald-500/10 text-emerald-600":l==="error"?"bg-rose-500/10 text-rose-600":"bg-foreground/5 text-foreground"),children:a.jsx(u,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("span",{className:"text-sm font-semibold",children:o.label}),a.jsxs("span",{className:L("inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider",c.cls),children:[a.jsx(d,{className:L("w-2.5 h-2.5",l==="running"&&"animate-spin")}),c.label]}),p&&a.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted",children:["Round ",n]})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5 line-clamp-1",children:o.tagline})]}),r&&a.jsxs("div",{className:"text-right shrink-0 text-[10px] text-muted-foreground font-mono space-y-0.5",children:[f>0&&a.jsxs("div",{children:[(f/1e3).toFixed(1),"s"]}),h>0&&a.jsxs("div",{children:["$",h.toFixed(2)]})]}),a.jsx(Yr,{className:L("w-4 h-4 text-muted-foreground shrink-0 transition-transform",s&&"rotate-180")})]}),s&&a.jsx("div",{className:"border-t bg-muted/20 p-3.5 space-y-2 text-[11px]",children:r?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-3 gap-2 font-mono",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"tokens in:"})," ",x.toLocaleString()]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"tokens out:"})," ",g.toLocaleString()]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"model:"})," ",r.model??"—"]})]}),a.jsxs("details",{children:[a.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground select-none",children:"Show raw output"}),a.jsx("pre",{className:"mt-2 max-h-72 overflow-auto bg-background border rounded p-2 text-[10px] font-mono whitespace-pre-wrap break-words",children:JSON.stringify(r.content,null,2)})]})]}):a.jsx("p",{className:"text-muted-foreground italic",children:l==="running"?`${o.label} is working…`:"No output yet."})})]})}const mye={approve:{label:"Approved",cls:"bg-emerald-500/10 text-emerald-700",Icon:el},approve_with_notes:{label:"Approved w/ notes",cls:"bg-amber-500/10 text-amber-700",Icon:J_},reject:{label:"Rejected",cls:"bg-rose-500/10 text-rose-700",Icon:v6},escalate:{label:"Escalated",cls:"bg-rose-500/10 text-rose-700",Icon:Ar}},gye={blocker:"bg-rose-500/10 text-rose-700 border-rose-500/30",major:"bg-amber-500/10 text-amber-700 border-amber-500/30",minor:"bg-muted text-muted-foreground border-border"};function xye({reviews:e}){return e.length===0?a.jsx("div",{className:"rounded-xl border bg-card p-4 text-center",children:a.jsx("p",{className:"text-xs text-muted-foreground",children:"Reviewer hasn't run yet. Reviews will appear here."})}):a.jsx("div",{className:"space-y-3",children:e.map(t=>{const r=mye[t.decision],n=r.Icon;return a.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[a.jsxs("div",{className:"px-4 py-3 border-b bg-muted/30 flex items-center gap-2.5",children:[a.jsxs("span",{className:"text-[10px] font-mono uppercase tracking-wider text-muted-foreground",children:["Round ",t.round]}),a.jsxs("span",{className:L("inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider",r.cls),children:[a.jsx(n,{className:"w-2.5 h-2.5"}),r.label]}),t.issues.length>0&&a.jsxs("span",{className:"text-[11px] text-muted-foreground ml-auto",children:[t.issues.length," ",t.issues.length===1?"issue":"issues"]})]}),t.summary&&a.jsx("div",{className:"px-4 py-2.5 border-b text-xs leading-relaxed",children:t.summary}),t.issues.length===0?a.jsx("div",{className:"px-4 py-3 text-xs text-muted-foreground",children:"No issues flagged."}):a.jsx("ul",{className:"divide-y",children:t.issues.map((s,i)=>a.jsxs("li",{className:"px-4 py-3 space-y-1.5",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("span",{className:L("inline-flex items-center px-1.5 py-0.5 rounded text-[9px] uppercase tracking-wider font-bold border",gye[s.severity]),children:s.severity}),a.jsx("span",{className:"text-[10px] font-mono text-muted-foreground uppercase",children:s.category}),s.file&&a.jsxs("code",{className:"text-[10px] font-mono text-muted-foreground",children:[s.file,s.line?`:${s.line}`:""]})]}),a.jsx("p",{className:"text-xs text-foreground leading-relaxed",children:s.description}),s.suggested_fix&&a.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:[a.jsx("strong",{className:"text-foreground",children:"Fix:"})," ",s.suggested_fix]}),s.evidence&&a.jsxs("details",{className:"text-[11px]",children:[a.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground select-none",children:"Evidence"}),a.jsx("pre",{className:"mt-1 bg-muted/40 rounded p-2 text-[10px] whitespace-pre-wrap font-mono",children:s.evidence})]})]},i))})]},t.id)})})}const yye=["planner","architect","builder","reviewer","tester"],bye=new Set(["succeeded","failed","rejected_max","canceled"]);function vye(e){if(!e)return"unknown";const t=new Date(e);
8199return Number.isNaN(t.getTime())?"unknown":t.toLocaleString([],{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function wye(e){return e==="succeeded"?{label:"Succeeded",Icon:mn,cls:"text-emerald-700 bg-emerald-500/10"}:e==="running"?{label:"Running",Icon:Lr,cls:"text-amber-700 bg-amber-500/10"}:e==="canceled"?{label:"Canceled",Icon:aa,cls:"text-muted-foreground bg-muted"}:{label:e==="rejected_max"?"Needs review":"Failed",Icon:Ar,cls:"text-rose-700 bg-rose-500/10"}}function jye(){const{currentAgentRunId:e,project:t}=gn(),[r,n]=m.useState([]),[s,i]=m.useState(null),o=e||s,{run:l,messages:c,reviews:u,loading:d}=uye(o);m.useEffect(()=>{if(!(t!=null&&t.id)){n([]),i(null);return}let g=!1;const y=async()=>{const{data:v}=await G.from("agent_runs").select("*").eq("project_id",t.id).order("started_at",{ascending:!1}).limit(8);if(g)return;const k=v||[];n(k),i(N=>{var j;return e||N&&k.some(w=>w.id===N)?N:((j=k[0])==null?void 0:j.id)??null})};y();const b=G.channel(`agent_runs_project_${t.id}`).on("postgres_changes",{event:"*",schema:"public",table:"agent_runs",filter:`project_id=eq.${t.id}`},()=>void y()).subscribe();return()=>{g=!0,G.removeChannel(b)}},[e,t==null?void 0:t.id]);const p=!!(e&&l&&!bye.has(l.status)),h=m.useMemo(()=>r.filter(g=>g.id!==e),[e,r]),f={planner:null,architect:null,builder:null,reviewer:null,tester:null},x={planner:0,architect:0,builder:0,reviewer:0,tester:0};for(const g of c){if(g.role!=="output")continue;const y=f[g.agent_name];(!y||g.round>y.round)&&(f[g.agent_name]=g),x[g.agent_name]=Math.max(x[g.agent_name],g.round)}return o?a.jsx($r,{className:"h-full",children:a.jsxs("div",{className:"p-4 space-y-5 max-w-4xl mx-auto",children:[!e&&h.length>0&&a.jsxs("div",{className:"rounded-xl border bg-card p-3",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold",children:"Recent Pipeline Runs"}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No run is active, so this tab is showing saved agent history for this project."})]}),a.jsxs("span",{className:"text-[10px] font-mono px-2 py-1 rounded bg-muted text-muted-foreground",children:[h.length," saved"]})]}),a.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:h.map(g=>{const y=wye(g.status),b=y.Icon,v=g.id===o;return a.jsxs("button",{type:"button",onClick:()=>i(g.id),className:L("min-w-[220px] rounded-lg border p-2.5 text-left transition-colors",v?"border-primary/50 bg-primary/5":"bg-background hover:bg-muted/40"),children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsxs("span",{className:L("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-semibold",y.cls),children:[a.jsx(b,{className:"h-2.5 w-2.5"}),y.label]}),a.jsx("span",{className:"ml-auto text-[10px] text-muted-foreground",children:vye(g.started_at)})]}),a.jsx("p",{className:"mt-1.5 text-xs font-medium line-clamp-2",children:g.prompt||"Pipeline run"}),a.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground font-mono",children:[(g.total_tokens_in+g.total_tokens_out).toLocaleString()," tokens · $",(g.total_cost_cents/100).toFixed(2)]})]},g.id)})})]}),p&&a.jsx("div",{className:"rounded-xl border border-amber-500/25 bg-amber-500/5 px-3 py-2 text-xs text-amber-800",children:"Live Pipeline run in progress. Agent cards update as each stage writes to Supabase."}),a.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(Dn,{className:"w-3.5 h-3.5 text-primary"}),a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-muted-foreground",children:"— Multi-agent run"}),l&&a.jsx("span",{className:"ml-auto text-[10px] font-mono px-2 py-0.5 rounded bg-muted",children:l.status})]}),l?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-foreground line-clamp-2",children:l.prompt}),a.jsxs("div",{className:"flex items-center gap-4 mt-3 text-[11px] text-muted-foreground font-mono",children:[a.jsxs("span",{children:["Rejections: ",l.rejection_rounds]}),a.jsxs("span",{children:["Tokens: ",(l.total_tokens_in+l.total_tokens_out).toLocaleStr
8199ing()]}),a.jsxs("span",{children:["Cost: $",(l.total_cost_cents/100).toFixed(2)]})]}),l.error_message&&a.jsx("p",{className:"mt-2 text-[11px] text-rose-600 bg-rose-500/5 rounded px-2 py-1",children:l.error_message})]}):d?a.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading run…"}):a.jsx("p",{className:"text-xs text-muted-foreground",children:"Run not found."})]}),a.jsx("div",{className:"space-y-2",children:yye.map(g=>a.jsx(fye,{name:g,run:l,latestOutput:f[g],totalRounds:x[g]},g))}),a.jsxs("div",{children:[a.jsx("p",{className:"text-[10px] font-mono uppercase tracking-wider text-muted-foreground mb-2 px-1",children:"— Reviewer rounds"}),a.jsx(xye,{reviews:u})]})]})}):a.jsx("div",{className:"h-full flex flex-col items-center justify-center p-8",children:a.jsxs("div",{className:"max-w-md text-center space-y-4",children:[a.jsx("div",{className:"w-12 h-12 mx-auto rounded-xl bg-foreground/5 flex items-center justify-center",children:a.jsx(Ip,{className:"w-5 h-5 text-foreground"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold",children:"No active agent run"}),a.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed mt-1.5",children:["This tab populates during a ",a.jsx("strong",{children:"Pipeline mode"})," build — a 5-stage AI workflow that swaps the single-call default for a chain of specialist agents."]})]}),a.jsxs("div",{className:"text-left bg-card border rounded-xl p-3 space-y-1.5",children:[a.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground/70 font-semibold mb-1",children:"The pipeline"}),a.jsxs("div",{className:"text-[11px] space-y-1",children:[a.jsxs("div",{children:[a.jsx("span",{className:"font-mono text-foreground",children:"1. Planner"})," ",a.jsx("span",{className:"text-muted-foreground",children:"— breaks your prompt into a plan"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"font-mono text-foreground",children:"2. Architect"})," ",a.jsx("span",{className:"text-muted-foreground",children:"— designs schema + structure"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"font-mono text-foreground",children:"3. Builder"})," ",a.jsx("span",{className:"text-muted-foreground",children:"— writes the code"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"font-mono text-foreground",children:"4. Reviewer"})," ",a.jsx("span",{className:"text-muted-foreground",children:"— audits + can reject + retry"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"font-mono text-foreground",children:"5. Tester"})," ",a.jsx("span",{className:"text-muted-foreground",children:"— generates Playwright tests"})]})]})]}),a.jsxs("div",{className:"bg-primary/5 border border-primary/20 rounded-xl p-3 text-left",children:[a.jsx("p",{className:"text-[11px] font-medium text-foreground mb-1",children:"How to enable Pipeline"}),a.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:["Open the chat composer at the bottom of the screen — click the ",a.jsx("span",{className:"font-mono px-1 py-0.5 rounded bg-card border",children:"Pipeline"})," toggle before sending your prompt. This tab fills with live progress as each agent runs."]}),a.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1.5 italic",children:"Pipeline builds cost 3–5× more credits than single-agent (multiple model calls per turn). Use them when you want higher quality on complex builds or want to see exactly which stage failed."})]})]})})}function iw(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"&&typeof n.content=="string"?r.push({path:s,content:n.content}):n.type==="folder"&&n.children&&r.push(...iw(n.children,s))}return r}function Nye(e){const t={};for(const{path:r,content:n}of e){const s=r.split("/").filter(Boolean);if(s.length===0)continue;let i=t;for(let o=0;o<s.length-1;o++){const l=s[o];i[l]||(i[l]={directory:{}});const c=i[l];if(!("directory"in c))return t;i=c.directory}i[s[s.length-1]]={file:{contents:n}}}return t}function kye(){const{files:e}=gn(),t=m.useRef(null),r=m.useRef(null),n=m.useRef(null),s=m.useRef(null),i=m.useRef(null),o=m.useRef(""),l=m.useRef(e);m.useEffect(()=>{l.current=e},[e]);const[c,u]=m.useState("booting"),[d,p]=m.useState(null),[h,f]=m.useState(!1),[x,g]=m.useState(""),[y,b]=m.useState(!1),[v,k]=m.useState(null),[N,j]=m.useState(null);m.useEffect(()=>{if(!t.current)return;let C=!1;const A=new P$({cursorBlink:!0,fontFamily:'"JetBrains Mono", "Fira Code", Menlo, Monaco, ui-monospace, monospace',fontSize:13,lineHeight:1.3,theme:{background:"#0a0a0a",foreground:"#e7e5e4",cursor:"#10b981",cursorAccent:"#0a0a0a",black:"#0a0a0a",red:"#ef4444",green:"#10b981",yellow:"#fbbf24",blue:"#3b82f6",magenta:"#a855f7",cyan:"#06b6d4",white:"#e7e5e4",brightBlack:"#525252",brightRed:"#f87171",brightGreen:"#34d399",brightYellow:"#fcd34d",brightBlue:"#60a5fa",brightMagenta:"#c084fc",brightCyan:"#22d3ee",brightWhite:"#ffffff"},allowTransparency:!1,convertEol:!0,scrollback:5e3}),P=new A$;A.loadAddon(P),A.open(t.current),P.fit(),r.current=A,n.current=P,A.writeln("\x1B[1;32m Studio Jungle Terminal \x1B[0m"),A.writeln("\x1B[2;37m A real shell on your project files. Try: ls, npm test, git status \x1B[0m"),A.writeln(""),
8199(async()=>{try{const _=await t3();if(C)return;if(!eU()){const B=iw(l.current);if(B.length>0){A.writeln(`\x1B[2;37m Mounting ${B.length} project file${B.length===1?"":"s"}…\x1B[0m`);try{await _.mount(Nye(B)),tU(),A.writeln("\x1B[2;32m ✓ Project files mounted at /home — try `ls`, `cat package.json`, `npm install`.\x1B[0m"),A.writeln("")}catch($){A.writeln(`\x1B[2;33m ⚠ Mount warning: ${$.message}\x1B[0m`)}}}const I=await _.spawn("jsh",{terminal:{cols:A.cols,rows:A.rows}});if(C){I.kill();return}s.current=I;const D=/\x1b\[[0-9;]*[A-Za-z]/g;I.output.pipeTo(new WritableStream({write(B){A.write(B);try{const $=B.replace(D,"");o.current=(o.current+$).slice(-8e3)}catch{}}})).catch(()=>{});const M=I.input.getWriter();i.current=M,A.onData(B=>{M.write(B).catch(()=>{})}),A.onResize(({cols:B,rows:$})=>{try{I.resize({cols:B,rows:$})}catch{}}),u("ready"),I.exit.then(B=>{A.writeln(`\r
8200\x1B[2;37m[ shell exited with code ${B} ]\x1B[0m`),u($=>$==="ready"?"error":$),p(`Shell exited (code ${B})`)}).catch(()=>{})}catch(_){if(C)return;const I=_ instanceof Error?_.message:String(_);console.error("[terminal] boot failed:",I),u("error"),p(I.includes("SharedArrayBuffer")||I.includes("isolat")?"Browser blocked the sandboxed environment. Reload the page; the terminal needs cross-origin isolation headers (already set on production).":I),A.writeln(`\r
8201\x1B[1;31mFailed to start terminal:\x1B[0m ${I}`)}})();const E=new ResizeObserver(()=>{try{P.fit()}catch{}});return E.observe(t.current),()=>{var _,I;C=!0,E.disconnect();try{(_=i.current)==null||_.releaseLock()}catch{}try{(I=s.current)==null||I.kill()}catch{}try{A.dispose()}catch{}r.current=null,n.current=null,s.current=null,i.current=null}},[]);const w=()=>{p(null),u("booting"),window.location.hash=`term-${Date.now()}`,window.location.reload()},S=m.useCallback(async C=>{var A;b(!0),k(null),j(null);try{const E=iw(l.current).slice(0,30).map(O=>O.path),_=o.current.slice(-1500),D=((A=(await G.auth.getSession()).data.session)==null?void 0:A.access_token)||"",M=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/terminal-ai",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D}`},body:JSON.stringify({prompt:C,recentOutput:_,filePaths:E})});if(!M.ok)throw new Error(`AI ${M.status}`);const B=await M.json();if(B.cmd){k(B.cmd),j(B.note||null);return}const $=B.raw||"",K=$.match(/```(?:bash|sh|shell|console)?\s*\n?([^\n`]+)/),R=$.match(/(?:^|\n)\s*[$>]\s+(.+?)(?:\n|$)/),Y=$.match(/(?:^|\n)\s*((?:ls|cat|grep|find|sed|awk|head|tail|wc|sort|uniq|cut|npm|node|git|echo|pwd|tree|du|df)\b[^\n]+)/),Z=((K==null?void 0:K[1])||(R==null?void 0:R[1])||(Y==null?void 0:Y[1])||"").trim();if(Z){k(Z),j("Parsed from AI response (the model returned prose instead of JSON — review carefully)");return}j(B.error||"AI did not return a command")}catch(P){const E=P.message||"AI request failed";j(`Error: ${E}`),W.error(E)}finally{b(!1)}},[]),T=m.useCallback(()=>{var C;!v||!i.current||(i.current.write(v+`
8202`).catch(()=>{}),(C=r.current)==null||C.focus(),f(!1),k(null),g(""))},[v]);return m.useEffect(()=>{function C(A){var _;!(A.metaKey||A.ctrlKey)||A.shiftKey||A.altKey||A.key.toLowerCase()!=="l"||!((_=t.current)!=null&&_.closest)||!(t.current.offsetParent!==null)||(A.preventDefault(),A.stopPropagation(),f(!0))}return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[]),a.jsxs("div",{className:"h-full flex flex-col bg-[#0a0a0a]",children:[a.jsxs("div",{className:"px-3 py-1.5 border-b border-zinc-800 flex items-center gap-2 shrink-0 bg-zinc-950",children:[a.jsx("span",{className:"text-[11px] font-mono text-zinc-400",children:"terminal"}),c==="booting"&&a.jsxs("span",{className:"text-[10px] text-amber-400 inline-flex items-center gap-1",children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"})," Booting sandbox…"]}),c==="ready"&&a.jsxs("span",{className:"text-[10px] text-emerald-400 inline-flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500"})," Ready"]}),c==="error"&&a.jsxs("span",{className:"text-[10px] text-rose-400 inline-flex items-center gap-1",children:[a.jsx(Ar,{className:"w-3 h-3"})," ",d||"Failed"]}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[a.jsxs(Q,{variant:"outline",size:"sm",className:"h-6 px-2 text-[10px] gap-1 bg-zinc-900 border-zinc-700 text-emerald-300 hover:bg-zinc-800",onClick:()=>f(!0),title:"Ask Studio Jungle AI for a command (⌘L)",children:[a.jsx(ri,{className:"h-4 w-4"}),"Studio Jungle AI ",a.jsx("span",{className:"text-[9px] font-mono opacity-60 ml-0.5",children:"⌘L"})]}),a.jsx("span",{className:"text-[10px] text-zinc-500 hidden sm:inline",children:"Studio Jungle Mode"}),c==="error"&&a.jsxs(Q,{variant:"outline",size:"sm",className:"h-6 px-2 text-[10px] gap-1 bg-zinc-900 border-zinc-700 text-zinc-300 hover:bg-zinc-800",onClick:w,children:[a.jsx(zr,{className:"w-3 h-3"})," Restart"]})]})]}),a.jsx("div",{ref:t,className:"flex-1 min-h-0 px-2 py-1"}),h&&a.jsxs("div",{className:"border-t border-zinc-800 bg-zinc-950 px-3 py-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(ri,{className:"h-5 w-5"}),a.jsx("span",{className:"text-[11px] font-semibold text-zinc-200",children:"Studio Jungle AI Terminal"}),a.jsx("span",{className:"text-[10px] text-zinc-500",children:"Describe what you want; Studio Jungle AI returns one command."}),a.jsx("button",{onClick:()=>{f(!1),k(null),g("")},className:"ml-auto p-1 rounded hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200","aria-label":"Close",children:a.jsx(qn,{
8202className:"w-3.5 h-3.5"})})]}),a.jsxs("form",{onSubmit:C=>{C.preventDefault(),!(!x.trim()||y)&&S(x.trim())},className:"flex items-center gap-2",children:[a.jsx("input",{autoFocus:!0,value:x,onChange:C=>g(C.target.value),placeholder:"Find files with TODO • Show failing tests • Diff the last commit • List the largest files",className:"flex-1 bg-zinc-900 border border-zinc-700 rounded-md px-3 py-2 text-[12px] text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:ring-1 focus:ring-emerald-500/50",disabled:y}),a.jsxs(Q,{type:"submit",size:"sm",disabled:!x.trim()||y,className:"h-9 px-3 text-[11px] gap-1 bg-emerald-600 hover:bg-emerald-500 text-white",children:[y?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(_k,{className:"w-3 h-3"}),"Ask"]})]}),v&&a.jsxs("div",{className:"mt-2 rounded-md border border-emerald-700/50 bg-emerald-950/30 p-2.5",children:[a.jsxs("div",{className:"text-[10px] text-emerald-300 mb-1",children:["Suggested command",N?` — ${N}`:""]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("code",{className:"flex-1 font-mono text-[12px] text-emerald-100 bg-black/40 rounded px-2 py-1 overflow-x-auto whitespace-nowrap",children:["$ ",v]}),a.jsxs(Q,{size:"sm",className:"h-7 px-2.5 text-[11px] gap-1 bg-emerald-600 hover:bg-emerald-500 text-white shrink-0",onClick:T,children:[a.jsx(_k,{className:"w-3 h-3"})," Run"]}),a.jsx(Q,{size:"sm",variant:"outline",className:"h-7 px-2.5 text-[11px] bg-zinc-900 border-zinc-700 text-zinc-300 hover:bg-zinc-800 shrink-0",onClick:()=>{k(null),g("")},children:"Discard"})]})]}),N&&!v&&!y&&a.jsx("div",{className:"mt-2 text-[11px] text-rose-400",children:N})]})]})}function Sye(){const{target:e,setTarget:t,buildMode:r,setBuildMode:n,architecture:s,setArchitecture:i,lifecycleStage:o,setLifecycleStage:l}=gn(),c=({value:u,options:d,onChange:p})=>a.jsx("div",{className:"flex flex-wrap gap-1",children:d.map(h=>a.jsxs("button",{onClick:()=>p(h.id),className:L("flex items-center gap-1 px-2 py-1 rounded-md border text-[11.5px] font-medium transition-all",u===h.id?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:border-primary/30 hover:text-foreground"),children:[h.icon&&a.jsx(h.icon,{className:"w-3 h-3"}),h.label]},h.id))});return a.jsxs("div",{className:"space-y-4 p-1",children:[a.jsxs("div",{children:[a.jsxs("p",{className:"flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5",children:[a.jsx(V$,{className:"w-3 h-3"})," Build Mode"]}),a.jsx(c,{value:r,onChange:n,options:[{id:"ai-guided",label:"AI-Guided",icon:Dn},{id:"ui-first",label:"UI-First",icon:Ai},{id:"api-first",label:"API-First",icon:sd},{id:"advanced",label:"Advanced",icon:al}]})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5",children:[a.jsx(C6,{className:"w-3 h-3"})," Target"]}),a.jsx(c,{value:e,onChange:t,options:[{id:"web",label:"Web",icon:Br},{id:"mobile",label:"Mobile",icon:Nc},{id:"both",label:"Both",icon:tl}]})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5",children:[a.jsx(Gg,{className:"w-3 h-3"})," Lifecycle"]}),a.jsx(c,{value:o,onChange:l,options:[{id:"prototype",label:"Prototype"},{id:"mvp",label:"MVP"},{id:"scale-ready",label:"Scale"},{id:"production",label:"Production",icon:Es}]})]}),a.jsxs("div",{className:"pt-2 border-t -mx-1 px-1",children:[a.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:"Architecture"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"space-y-1",children:[a.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Frontend"}),a.jsxs(Ns,{value:s.frontend,onValueChange:u=>i({...s,frontend:u}),children:[a.jsx(hs,{className:"h-7 text-[11.5px]",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"React",children:"React"}),a.jsx(Dt,{value:"Next.js",children:"Next.js"}),a.jsx(Dt,{value:"Vue",children:"Vue"})]})]})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Backend"}),a.jsxs(Ns,{value:s.backend,onValueChange:u=>i({...s,backend:u}),children:[a.jsx(hs,{className:"h-7 text-[11.5px]",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"FastAPI (Python)",children:"FastAPI (Python)"}),a.jsx(Dt,{value:"Node.js (NestJS)",children:"Node.js (NestJS)"}),a.jsx(Dt,{value:"Serverless Functions",children:"Serverless"})]})]})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Database"}),a.jsxs(Ns,{value:s.database,onValueChange:u=>i({...s,database:u}),children:[a.jsx(hs,{className:"h-7 text-[11.5px]",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"PostgreSQL",children:"PostgreSQL"}),a.jsx(Dt,{value:"Supabase",children:"Supabase"}),a.jsx(Dt,{value:"MongoDB",children:"MongoDB"}),a.jsx(Dt,{value:"Firestore",children:"Firestore"})]})]})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Auth"}),a.jsxs(Ns,{value:s.auth,onValueChange:u=>i({...s,auth:u}),children:[a.jsx(hs,{className:"h-7 text-[11.5px]",children:a.jsx(ks,{})}),a.jsxs(fs,{children:[a.jsx(Dt,{value:"Built-in Auth",children:"Built-in"}),a.jsx(Dt,{value:"OAuth",children:"OAuth"}
8202),a.jsx(Dt,{value:"External",children:"External"}),a.jsx(Dt,{value:"Firebase Auth",children:"Firebase"})]})]})]})]})]})]})}function Cye(){const{isBuilding:e,generatedBlockCount:t,triggerBuildRef:r,project:n,files:s,setActiveWorkspaceTab:i,lastBuildErrors:o}=gn(),{canEdit:l}=Ih(),c=kw(),u=nd(),[d,p]=m.useState(!1),[h,f]=m.useState(!1),[x,g]=m.useState(!1),y=(N,j,w,S="starter")=>()=>{if(!N){const T=c.plan!=="none";Mt({title:`${j} requires ${S==="starter"?"any paid plan":S==="pro"?"the Pro plan":"the Studio plan"}`,description:T?`Your ${c.label} plan doesn't include this — open billing to switch tier.`:"Pick a Starter, Pro, or Studio plan to unlock this."}),u(T?"/studio/billing":"/pricing");return}w()},b=()=>{var N,j;if(!r.current){Mt({title:"Chat not ready",description:"Open the chat panel first, then click Repair Agent again.",variant:"destructive"});return}if(o&&o.length>0){Mt({title:`Repair Agent fixing ${o.length} error${o.length===1?"":"s"}`,description:o[0].slice(0,120)});const w=o.slice(0,10).map((S,T)=>`${T+1}. ${S}`).join(`
8203`);(N=r.current)==null||N.call(r,`🔧 **Repair Agent activated.** You are a focused bug-fix specialist for this build session.
8204
8205The app currently has these specific build errors blocking it:
8206
8207${w}
8208
8209Your job: fix each error. NO PROSE BETWEEN FIXES. NO "Let me check…", NO "I see the issue…", NO commentary. Begin the response with the first write_file/str_replace tool call.
8210
8211For each error: emit the minimal patch that resolves it. No rewrites if a 2-line patch will do. Don't touch imports/types/RLS/routes that aren't part of the error.
8212
8213Do NOT add features, refactor unrelated code, or change UI/design. End with a one-line summary of what you fixed in ask_next_phase.intro. That intro is the ONLY text you write.`,{overrideModel:"claude-haiku-4-5",isAutoFix:!0})}else Mt({title:"Repair Agent running 7-category audit",description:"No queued errors — scanning for runtime, import, route, RLS, CORS, env, and UI issues."}),(j=r.current)==null||j.call(r,`🔧 **Repair Agent activated.** You are a focused bug-fix specialist for this build session.
8214
8215No build errors queued. Run a 7-category audit. NO PROSE between checks. NO "I see…", NO "Let me look…", NO commentary. Emit fixes (write_file or str_replace) ONLY where you find real problems — not speculative refactors. Begin with the first tool call:
8216
82171. **Runtime errors** — console.error or unhandled exceptions in the browser
82182. **Broken imports** — files importing missing modules or paths
82193. **Missing routes** — App.tsx / router referencing pages that don't exist
82204. **RLS / auth gaps** — DB policies that might block legitimate user queries OR endpoints that skip JWT verification
82215. **CORS / preflight** — edge functions missing OPTIONS handlers
82226. **Env var typos** — code referencing env keys that don't match what's set
82237. **UI glitches** — overlapping text, broken links, missing alt tags, unhandled loading/empty/error states
8224
8225Do NOT add new features, change visual design, or rewrite working code. Repair only. End with a one-line summary listing each fix you made (e.g. "Fixed broken import in Header.tsx, added OPTIONS handler to api-bookings, added empty-state to dashboard").`,{overrideModel:"claude-haiku-4-5",isAutoFix:!0})},v=async()=>{if(t===0){Mt({title:"Nothing to export",description:"Build something first, then export."});return}g(!0);try{const N=new k$,j=(C,A="")=>{for(const P of C){const E=A?`${A}/${P.name}`:P.name;P.type==="folder"&&P.children?j(P.children,E):P.type==="file"&&P.content&&N.file(E,P.content)}};if(j(s),Object.keys(N.files).length===0){Mt({title:"No files to export",description:"Generated files have no content yet."});return}const w=await N.generateAsync({type:"blob"}),S=URL.createObjectURL(w),T=document.createElement("a");T.href=S,T.download=`${(n==null?void 0:n.name)||"project"}-export.zip`,document.body.appendChild(T),T.click(),document.body.removeChild(T),URL.revokeObjectURL(S),Mt({title:"✅ Exported!",description:"ZIP file downloaded."})}catch(N){console.error("Export failed:",N),Mt({title:"Export failed",description:"Could not generate ZIP file."})}finally{g(!1)}},k=({icon:N,label:j,onClick:w,disabled:S,busy:T,locked:C,lockedTier:A})=>a.jsxs(Q,{variant:"ghost",size:"sm",className:L("h-8 gap-1.5 px-2 rounded-md text-[11.5px] font-medium hover:bg-secondary/80",C?"text-muted-foreground
8225/70 hover:text-foreground":"text-muted-foreground hover:text-foreground"),onClick:w,disabled:S,title:C?`${j} · requires ${A==="pro"?"Pro":A==="studio"?"Studio":"any paid plan"}`:j,"aria-label":j,children:[T?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(N,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden lg:inline",children:j}),C&&a.jsx(Bs,{className:"w-2.5 h-2.5 text-amber-600/80"})]});return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-0.5",children:[l&&a.jsx(k,{icon:al,label:o.length>0?`Repair (${o.length})`:"Repair Agent",onClick:y(c.features.repairMode,"Repair Agent",b,"pro"),locked:!c.features.repairMode,lockedTier:"pro",disabled:e||t===0&&o.length===0}),a.jsx(k,{icon:os,label:"Auth",onClick:()=>p(!0)}),a.jsx(k,{icon:Hb,label:"Export",onClick:y(c.features.zipExport,"Export",v),locked:!c.features.zipExport,busy:x,disabled:x}),a.jsx(k,{icon:oo,label:"GitHub",onClick:y(c.features.githubPush,"GitHub",()=>i("github")),locked:!c.features.githubPush}),a.jsx(k,{icon:Es,label:"Publish",onClick:y(c.atLeast("starter"),"Publish",()=>f(!0)),locked:!c.atLeast("starter")})]}),a.jsxs(B1,{children:[a.jsx(U1,{asChild:!0,children:a.jsxs(Q,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 px-2 rounded-md ml-0.5 text-[11.5px] font-medium text-muted-foreground hover:text-foreground",title:"Build settings","aria-label":"Build settings",children:[a.jsx(wT,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden lg:inline",children:"Settings"})]})}),a.jsx(fx,{align:"end",className:"w-80 p-3",children:a.jsx(Sye,{})})]})]}),a.jsx(l3,{open:d,onOpenChange:p}),a.jsx(dM,{open:h,onOpenChange:f})]})}const Pye={critical:"bg-red-500/10 text-red-700 border-red-500/25",high:"bg-orange-500/10 text-orange-700 border-orange-500/25",medium:"bg-amber-500/10 text-amber-700 border-amber-500/25",low:"bg-blue-500/10 text-blue-700 border-blue-500/25"},Aye={Secrets:Ep,Auth:Bs,XSS:J_,Network:Is,Headers:os,Data:sd,Dependencies:Ar},_ye=[/(?:api[_-]?key|secret|token|private[_-]?key|service[_-]?role|password)\s*[:=]\s*['"`][^'"`\n]{16,}['"`]/i,/sk-[A-Za-z0-9_-]{20,}/,/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/,/SUPABASE_SERVICE_ROLE_KEY/i,/service_role/i];function xM(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"&&typeof n.content=="string"?r.push({path:s,content:n.content}):n.type==="folder"&&n.children&&r.push(...xM(n.children,s))}return r}function yM(e){return/\.(tsx?|jsx?|html?|css|json|env|sql)$/i.test(e)&&!/node_modules|dist|package-lock\.json/i.test(e)}function El(e,t,r){var o;const s=e.content.slice(0,t).split(`
8226`).length,i=((o=e.content.split(`
8227`)[s-1])==null?void 0:o.trim().slice(0,220))||"";return{...r,id:`${e.path}:${s}:${r.title}`,path:e.path,line:s,snippet:i}}function Tye(e){const t=[];for(const r of e.filter(n=>yM(n.path))){const n=r.content||"";for(const d of _ye){const p=n.match(d);if((p==null?void 0:p.index)!=null){t.push(El(r,p.index,{title:"Possible secret committed in client code",description:"This file appears to contain an API key, token, password, or service-role style secret. Anything shipped to the browser can be extracted by users.",recommendation:"Move the secret into Supabase Edge Function secrets or server-side environment variables, then call it through a backend endpoint.",severity:/service[_-]?role|SUPABASE_SERVICE_ROLE_KEY/i.test(p[0])?"critical":"high",category:"Secrets",fixPrompt:`Fix the security issue in ${r.path}: remove hardcoded secrets from client-visible code. Move secret usage to a secure edge function or environment variable pattern, preserve behavior, and do not redesign the UI.`}));break}}const s=n.indexOf("dangerouslySetInnerHTML");s>=0&&t.push(El(r,s,{title:"Unsafe HTML injection surface",description:"dangerouslySetInnerHTML can create XSS vulnerabilities if any value is user-controlled or comes from an API.",recommendation:"Render structured React content instead, or sanitize HTML with a trusted sanitizer before injection.",severity:"high",category:"XSS",fixPrompt:`Fix the XSS risk in ${r.path}: remove or sanitize dangerouslySetInnerHTML safely. Keep the visual output the same and make the smallest code change.`}));const i=n.search(/\b(eval|Function)\s*\(/);i>=0&&t.push(El(r,i,{title:"Dynamic code execution",description:"eval/new Function executes strings as code and can become remote code execution if data is user-controlled.",recommendation:"Replace dynamic execution with explicit parsing, lookup tables, or safe expression handling.",severity:"critical",category:"XSS",fixPrompt:`Fix the dynamic-code security issue in ${r.path}: remove eval/new Function usage and replace it with a safe explicit implementation. Preserve behavior.`}));const o=n.search(/localStorage\.(setItem|getItem)\([^)]*(token|password|secret|session|jwt)/i);o>=0&&t.push(El(r,o,{title:"Sensitive value stored in localStorage",description:"Tokens or secrets in localStorage are exposed to any successful XSS and are difficult to revoke safely.",recommendation:"Use Supabase auth session handling or httpOnly server cookies where possible; avoid storing raw secrets manually.",severity:"medium",category:"Auth",fixPrompt:`Fix the auth storage risk in ${r.path}: stop manually storing sensitive tokens/secrets in localStorage. Use the existing auth/session helper pattern and keep behavior intact.`}));const l=n.search(/['"`]http:\/\/(?!localhost|127\.0\.0\.1)/i);l>=0&&t.push(El(r,l,{title:"Insecure HTTP endpoint",description:"Plain HTTP can leak user data and be modified in transit on published apps.",recommendation:"Use HTTPS endpoints or proxy through a secure backend.",severity:"medium",category:"Network",fixPrompt:`Fix the insecure network URL in ${r.path}: replace non-local http:// usage with https:// or a secure backend proxy. Preserve the same feature behavior.`}));const c=n.search(/target=["']_blank["'](?![^>]*rel=)/i);c>=0&&t.push(El(r,c,{title:"External link missing rel protection",description:'Links opened with target="_blank" should include rel="noopener noreferrer" to prevent tabnabbing.',recommendation:'Add rel="noopener noreferrer" to external blank-target links.',severity:"low",category:"Headers",fixPrompt:`Fix external link security in ${r.path}: add rel="noopener noreferrer" to target="_blank" links that do not have it. Do not change design.`}));const u=n.search(/Access-Control-Allow-Origin["']?\s*:\s*["']\*/i);u>=0&&/supabase\/functions|server|api/i.test(r.path)&&t.push(El(r,u,{title:"Wildcard CORS on backend endpoint",description:"Wildcard CORS may be too broad for endpoints that handle private data or authenticated actions.",recommendation:"Restrict allowed origins to the published app domain and local development origins.",severity:"medium",category:"Network",fixPrompt:`Fix CORS hardening in ${r.path}: replace wildcard CORS with a safe allowlist for published and local development origins. Preserve OPTIONS handling.`}))}return t.sort((r,n)=>{const s={critical:0,high:1,medium:2,low:3};return s[r.severity]-s[n.severity]||r.path.localeCompare(n.path)})}function Eye(e){return`Fix the current project security scan issues only. Make the smallest safe code changes, preserve UI/design and existing behavior, and do not add unrelated features.
8228
8229Issues to fix:
8230${e.slice(0,8).map(r=>`- ${r.severity.toUpperCase()} ${r.category}: ${r.title} in ${r.path}:${r.line}`).join(`
8231`)}
8232
8233After editing, ensure the app still builds.`}function Iye(){const{files:e,triggerBuildRef:t,setActiveWorkspaceTab:r}=gn(),[n,s]=m.useState(!1),[i,o]=m.useState("all"),[l,c]=m.useState(0),u=m.useMemo(()=>xM(e),[e]),d=m.useMemo(()=>Tye(u),[u,l]),p=i==="all"?d:d.filter(y=>y.severity===i),h=d.filter(y=>y.severity==="critical").length,f=d.filter(y=>y.severity==="high").length,x=d.filter(y=>y.severity==="medium").length,g=y=>{var b;(b=t.current)==null||b.call(t,y),r("preview")};return a.jsx("div",{className:"h-full overflow-hidden bg-background",children:a.jsx($r,{className:"h-full",children:a.jsxs("div",{className:"p-5 space-y-5",children:[a.jsx("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center",children:a.jsx(os,{className:"h-5 w-5 text-primary"})}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-base font-semibold",children:"Security scan"}),a.jsx(Ge,{variant:"outline",className:L("text-[10px]",d.length===0?"border-emerald-500/30 text-emerald-700 bg-emerald-500/10":"border-amber-500/30 text-amber-700 bg-amber-500/10"),children:d.length===0?"Up to date":`${d.length} issue${d.length===1?"":"s"}`})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Static scan of generated project files. It c
8233atches common risks, not every possible vulnerability."})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("label",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:[a.jsx("input",{type:"checkbox",checked:n,onChange:y=>s(y.target.checked),className:"accent-primary"}),"Advanced view"]}),a.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>c(y=>y+1),className:"gap-1.5",children:[a.jsx(zr,{className:"h-3.5 w-3.5"}),"Update scan"]}),a.jsxs(Q,{size:"sm",disabled:d.length===0||!t.current,onClick:()=>g(Eye(d)),className:"gap-1.5",children:[a.jsx(Dn,{className:"h-3.5 w-3.5"}),"Try to fix all"]})]})]})}),a.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[a.jsx(Vf,{label:"Critical",value:h,tone:"critical"}),a.jsx(Vf,{label:"High",value:f,tone:"high"}),a.jsx(Vf,{label:"Medium",value:x,tone:"medium"}),a.jsx(Vf,{label:"Files scanned",value:u.filter(y=>yM(y.path)).length,tone:"low"})]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:["all","critical","high","medium","low"].map(y=>a.jsx("button",{onClick:()=>o(y),className:L("rounded-full border px-3 py-1 text-xs font-medium capitalize transition-colors",i===y?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-secondary"),children:y},y))}),d.length===0?a.jsx("div",{className:"min-h-[360px] rounded-xl border border-dashed bg-card/50 flex items-center justify-center p-8 text-center",children:a.jsxs("div",{children:[a.jsx("div",{className:"mx-auto mb-4 h-12 w-12 rounded-xl bg-emerald-500/10 flex items-center justify-center",children:a.jsx(mn,{className:"h-6 w-6 text-emerald-600"})}),a.jsx("h3",{className:"font-semibold",children:"All clear"}),a.jsx("p",{className:"mt-2 max-w-sm text-sm text-muted-foreground",children:"No common security issues were spotted in the generated files. Keep in mind this scan is a guardrail, not a full penetration test."})]})}):a.jsx("div",{className:"space-y-3",children:p.map(y=>{const b=Aye[y.category];return a.jsx("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:a.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start",children:[a.jsxs("div",{className:"flex flex-1 gap-3",children:[a.jsx("div",{className:"mt-0.5 h-9 w-9 shrink-0 rounded-lg bg-secondary flex items-center justify-center",children:a.jsx(b,{className:"h-4 w-4 text-muted-foreground"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("h3",{className:"text-sm font-semibold",children:y.title}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] capitalize",Pye[y.severity]),children:y.severity}),a.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:y.category})]}),a.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:y.description}),a.jsx("p",{className:"mt-2 text-xs font-medium text-foreground",children:y.recommendation}),a.jsxs("div",{className:"mt-3 rounded-lg bg-muted/60 px-3 py-2 font-mono text-[11px] text-muted-foreground",children:[y.path,":",y.line,n&&y.snippet&&a.jsx("div",{className:"mt-1 truncate text-foreground/80",children:y.snippet})]})]})]}),a.jsxs(Q,{variant:"outline",size:"sm",disabled:!t.current,onClick:()=>g(y.fixPrompt),className:"gap-1.5 lg:ml-auto",children:[a.jsx(Dn,{className:"h-3.5 w-3.5"}),"Fix"]})]})},y.id)})})]})})})}function Vf({label:e,value:t,tone:r}){return a.jsxs("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:[a.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:e}),a.jsx("p",{className:"mt-3 text-2xl font-semibold tracking-tight",children:t}),a.jsx("div",{className:L("mt-3 h-1 rounded-full",r==="critical"?"bg-red-500/70":r==="high"?"bg-orange-500/70":r==="medium"?"bg-amber-500/70":"bg-primary/40")})]})}const Fg={performance:"Performance",accessibility:"Accessibility","best-practices":"Best Practices",seo:"SEO"},bM={performance:Gg,accessibility:lc,"best-practices":mn,seo:ja},ow={high:16,medium:9,low:4},Oye={high:"bg-red-500/10 text-red-700 border-red-500/25",medium:"bg-amber-500/10 text-amber-700 border-amber-500/25",low:"bg-blue-500/10 text-blue-700 border-blue-500/25"};function vM(e,t=""){const r=[];for(const n of e){const s=t?`${t}/${n.name}`:n.name;n.type==="file"&&typeof n.content=="string"?r.push({path:s,content:n.content}):n.type==="folder"&&n.children&&r.push(...vM(n.children,s))}return r}function Rye(e){return/\.(tsx?|jsx?|html?|css|json)$/i.test(e)&&!/node_modules|dist|package-lock\.json/i.test(e)}function Ka(e,t,r){var o;const s=e.content.slice(0,Math.max(0,t)).split(`
8234`).length,i=((o=e.content.split(`
8235`)[s-1])==null?void 0:o.trim().slice(0,220))||"";return{...r,id:`${e.path}:${s}:${r.title}`,path:e.path,line:s,snippet:i}}function Dye(e,t){const r=[],n=e.map(i=>i.content).join(`
8236`),s=e.find(i=>/(^|\/)index\.html$/i.test(i.path));for(const i of e.filter(o=>Rye(o.path))){const o=i.content,l=t==="mobile"?9e4:15e4;o.length>l&&/\.(tsx?|jsx?)$/i.test(i.path)&&r.push(Ka(i,0,{category:"performance",severity:t==="mobile"?"high":"medium",title:"Large client file",description:"This source file is large enough to slow parsing and rebuilds, especially after bundling.",recommendation:"Split heavy sections into smaller lazy-loaded components and move large static data into separate files.",fixPrompt:`Improve performance in ${i.path}: split large client code into smaller components or lazy-loaded chunks where safe. Preserve UI and behavior.`}));const c=o.search(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]{12000,}/);c>=0&&r.push(Ka(i,c,{category:"performance",severity:"high",title:"Large inline image data",description:"Base64 images inside source inflate JavaScript/HTML and block rendering.",recommendation:"Move images to project assets or public files and reference them by URL.",fixPrompt:`Fix performance in ${i.path}: move large inline base64 image data into a proper asset reference or public file pattern. Preserve visuals.`}));const u=o.search(/<img(?![^>]*loading=)/i);u>=0&&r.push(Ka(i,u,{category:"performance",severity:"medium",title:"Images not lazy-loaded",description:'Images without loading="lazy" can delay initial page rendering.',recommendation:'Add loading="lazy" and decoding="async" to non-critical images.',fixPrompt:`Improve image performance in ${i.path}: add loading="lazy" and decoding="async" to non-critical image tags. Preserve layout and design.`}));const d=o.search(/<img(?![^>]*alt=)/i);d>=0&&r.push(Ka(i,d,{category:"accessibility",severity:"medium",title:"Image missing alt text",description:"Images without alt text are hard for screen readers and can hurt SEO.",recommendation:'Add descriptive alt text, or alt="" for decorative images.',fixPrompt:`Fix accessibility in ${i.path}: add appropriate alt attributes to image tags. Use descriptive alt for content images and empty alt for decorative images.`}));const p=o.search(/<button(?![^>]*(aria-label|aria-labelledby))/i);p>=0&&/<button[^>]*>\s*(<[^>
8236]+>\s*){1,3}<\/button>/i.test(o)&&r.push(Ka(i,p,{category:"accessibility",severity:"low",title:"Icon button may need an accessible label",description:"Icon-only buttons need an aria-label so assistive technology can describe the action.",recommendation:"Add aria-label to icon-only buttons.",fixPrompt:`Fix accessibility in ${i.path}: add aria-labels to icon-only buttons without changing visuals.`}));const h=o.search(/\bconsole\.(log|debug|trace)\(/);h>=0&&r.push(Ka(i,h,{category:"best-practices",severity:"low",title:"Debug logging in client code",description:"Console debug logs can leak implementation details and create noise in production.",recommendation:"Remove debug logs or guard them behind development checks.",fixPrompt:`Clean production best practices in ${i.path}: remove or dev-guard console.log/debug/trace calls. Preserve errors/warnings that are useful.`}));const f=o.search(/localStorage\.(getItem|setItem)/);f>=0&&t==="mobile"&&r.push(Ka(i,f,{category:"performance",severity:"low",title:"Synchronous storage on mobile path",description:"localStorage is synchronous and can block the main thread if used repeatedly during render.",recommendation:"Read once during initialization or move repeated access into effects/cached state.",fixPrompt:`Improve mobile performance in ${i.path}: avoid repeated localStorage access during render; cache values in state/effects. Preserve behavior.`}))}if(s&&(/<title>[^<]{8,}<\/title>/i.test(s.content)||r.push(Ka(s,0,{category:"seo",severity:"medium",title:"Missing useful page title",description:"A descriptive title improves search previews and browser tab clarity.",recommendation:"Add a concise, project-specific title tag.",fixPrompt:"Add a strong project-specific <title> to index.html. Keep the app behavior unchanged."})),/<meta\s+name=["']description["']/i.test(s.content)||r.push(Ka(s,0,{category:"seo",severity:"medium",title:"Missing meta description",description:"Search engines and link previews use meta descriptions to explain the page.",recommendation:"Add a concise description meta tag.",fixPrompt:"Add a concise project-specific meta description to index.html. Do not redesign the app."})),/<meta\s+name=["']viewport["']/i.test(s.content)||r.push(Ka(s,0,{category:"performance",severity:"high",title:"Missing viewport meta tag",description:"Without a viewport tag mobile browsers may render a desktop-sized layout.",recommendation:'Add <meta name="viewport" content="width=device-width, initial-scale=1.0" />.',fixPrompt:"Add the correct viewport meta tag to index.html. Preserve all existing tags."}))),/from ['"]framer-motion['"]/.test(n)&&t==="mobile"){const i=e.find(o=>/from ['"]framer-motion['"]/.test(o.content));i&&r.push(Ka(i,i.content.search(/framer-motion/),{category:"performance",severity:"low",title:"Animation library on mobile",description:"Heavy animation libraries can be fine, but mobile pages should avoid unnecessary motion work during initial render.",recommendation:"Lazy-load animated sections or reduce initial animations for mobile.",fixPrompt:`Review mobile animation performance in ${i.path}: reduce initial render motion or lazy-load heavy animated sections while preserving the design.`}))}return r.sort((i,o)=>{const l={performance:0,accessibility:1,"best-practices":2,seo:3};return l[i.category]-l[o.category]||ow[o.severity]-ow[i.severity]})}function Gf(e,t,r){const s=t.filter(o=>o.category===e).reduce((o,l)=>o+ow[l.severity],0),i=r==="mobile"&&e==="performance"?5:0;return Math.max(0,Math.min(100,100-s-i))}function Mye(e,t){const r=e.slice(0,8).map(n=>`- ${Fg[n.category]} ${n.severity}: ${n.title} in ${n.path}:${n.line}`).join(`
8237`);return`Fix the current ${t} performance scan issues only. Make the smallest safe code changes, preserve the visual design and behavior, and do not add unrelated features.
8238
8239Issues:
8240${r}
8241
8242After editing, ensure the app still builds.`}function Lye(){const{files:e,triggerBuildRef:t,setActiveWorkspaceTab:r}=gn(),[n,s]=m.useState("desktop"),[i,o]=m.useState("all"),[l,c]=m.useState(0),u=m.useMemo(()=>vM(e),[e]),d=m.useMemo(()=>Dye(u,n),[u,n,l]),p=i==="all"?d:d.filter(x=>x.category===i),h={performance:Gf("performance",d,n),accessibility:Gf("accessibility",d,n),"best-practices":Gf("best-practices",d,n),seo:Gf("seo",d,n)},f=x=>{var g;(g=t.current)==null||g.call(t,x),r("preview")};return a.jsx("div",{className:"h-full overflow-hidden bg-background",children:a.jsx($r,{className:"h-full",children:a.jsxs("div",{className:"p-5 space-y-5",children:[a.jsx("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-base font-semibold flex items-center gap-2",children:[a.jsx(Gg,{className:"h-5 w-5 text-primary"}),"Speed"]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Checks the latest generated project files. Published Lighthouse data can plug into this view next."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ge,{variant:"outline",className:"h-8 gap-1.5",children:[a.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground"}),d.length===0?"Up to date":`${d.length} finding${d.length===1?"":"s"}`]}),a.jsx("div",{className:"rounded-lg border bg-secondary/50 p-0.5",children:["desktop","mobile"].map(x=>{const g=x==="desktop"?Aw:Nc;return a.jsxs("button",{onClick:()=>s(x),className:L("inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium capitalize",n===x?"bg-card shadow-sm text-foreground":"text-muted-foreground"),children:[a.jsx(g,{className:"h-3.5 w-3.5"}),x]},x)})}),a.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>c(x=>x+1),className:"h-8 gap-1.5",children:[a.jsx(zr,{className:"h-3.5 w-3.5"}),"Update"]}),a.jsxs(Q,{size:"sm",disabled:d.length===0||!t.current,onClick:()=>f(Mye(d,n)),className:"h-8 gap-1.5",children:[a.jsx(Dn,{className:"h-3.5 w-3.5"}),"Fix all"]})]})]})}),a.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:Object.keys(h).map(x=>a.jsx($ye,{category:x,score:h[x],active:i===x,onClick:()=>o(x)},x))}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:["all","performance","accessibility","best-practices","seo"].map(x=>a.jsx("button",{onClick:()=>
8242o(x),className:L("rounded-full border px-3 py-1 text-xs font-medium transition-colors",i===x?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-secondary"),children:x==="all"?"All":Fg[x]},x))}),d.length===0?a.jsx("div",{className:"min-h-[360px] rounded-xl border border-dashed bg-card/50 flex items-center justify-center p-8 text-center",children:a.jsxs("div",{children:[a.jsx("div",{className:"mx-auto mb-4 h-12 w-12 rounded-xl bg-emerald-500/10 flex items-center justify-center",children:a.jsx(mn,{className:"h-6 w-6 text-emerald-600"})}),a.jsx("h3",{className:"font-semibold",children:"Looks fast from the static scan"}),a.jsx("p",{className:"mt-2 max-w-sm text-sm text-muted-foreground",children:"No common performance, accessibility, best-practice, or SEO issues were spotted."})]})}):a.jsx("div",{className:"space-y-3",children:p.map(x=>{const g=bM[x.category];return a.jsx("div",{className:"rounded-xl border bg-card p-4 shadow-sm",children:a.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start",children:[a.jsxs("div",{className:"flex flex-1 gap-3",children:[a.jsx("div",{className:"mt-0.5 h-9 w-9 shrink-0 rounded-lg bg-secondary flex items-center justify-center",children:a.jsx(g,{className:"h-4 w-4 text-muted-foreground"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("h3",{className:"text-sm font-semibold",children:x.title}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] capitalize",Oye[x.severity]),children:x.severity}),a.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:Fg[x.category]})]}),a.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:x.description}),a.jsx("p",{className:"mt-2 text-xs font-medium text-foreground",children:x.recommendation}),a.jsxs("div",{className:"mt-3 rounded-lg bg-muted/60 px-3 py-2 font-mono text-[11px] text-muted-foreground",children:[x.path,":",x.line,x.snippet&&a.jsx("div",{className:"mt-1 truncate text-foreground/80",children:x.snippet})]})]})]}),a.jsxs(Q,{variant:"outline",size:"sm",disabled:!t.current,onClick:()=>f(x.fixPrompt),className:"gap-1.5 lg:ml-auto",children:[a.jsx(Dn,{className:"h-3.5 w-3.5"}),"Fix"]})]})},x.id)})})]})})})}function $ye({category:e,score:t,active:r,onClick:n}){const s=bM[e],i=t>=90?"text-emerald-600":t>=70?"text-amber-600":"text-red-600";return a.jsxs("button",{onClick:n,className:L("rounded-xl border bg-card p-4 text-left shadow-sm transition-colors hover:bg-secondary/40",r&&"border-primary/50 ring-1 ring-primary/20"),children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("p",{className:L("text-sm font-semibold",r&&"text-primary"),children:Fg[e]}),a.jsx(s,{className:"h-4 w-4 text-muted-foreground"})]}),a.jsxs("div",{className:"mt-5 flex items-end gap-2",children:[a.jsx("span",{className:L("text-3xl font-semibold tracking-tight",i),children:t}),a.jsx("span",{className:"pb-1 text-xs text-muted-foreground",children:"/100"})]}),a.jsx("div",{className:"mt-4 h-1.5 rounded-full bg-secondary overflow-hidden",children:a.jsx("div",{className:L("h-full rounded-full",t>=90?"bg-emerald-500":t>=70?"bg-amber-500":"bg-red-500"),style:{width:`${t}%`}})})]})}const p_=[{id:"preview",label:"Preview",icon:ys},{id:"files",label:"Files",icon:K$},{id:"agents",label:"Agents",icon:Ip},{id:"cloud",label:"Cloud",icon:ya}],Rb=[{id:"api",label:"API",icon:Br},{id:"schema",label:"Schema",icon:S6},{id:"diagram",label:"Diagram",icon:oo},{id:"query",label:"Query",icon:Yg},{id:"autodb",label:"Auto DB",icon:Op}],Db=[{id:"performance",label:"Speed",icon:Gg},{id:"security",label:"Security",icon:os},{id:"mcp",label:"MCP",icon:Ma},{id:"github",label:"GitHub",icon:oo},{id:"terminal",label:"Terminal",icon:j6},{id:"tools",label:"Quick Starts",icon:al},{id:"logs",label:"Logs",icon:ai},{id:"history",label:"History",icon:_p}];function Fye(e){return e===".sj"||e===".studiojungle"}function wM(e){return e.reduce((t,r)=>Fye(r.name)?t:r.type==="file"?t+1:t+wM(r.children||[]),0)}function Bye(){var y,b;const{mode:e,activeWorkspaceTab:t,setActiveWorkspaceTab:r,files:n,project:s}=gn(),i=wM(n),c=e==="data-copilot"?[{id:"sql",label:"SQL",icon:Hn},{id:"preview",label:"Charts",icon:U$}]:e==="workflow"?[{id:"preview",label:"Preview",icon:ys},{id:"library",label:"Library",icon:mT},{id:"mcp",label:"MCP",icon:Ma}]:[...p_,...Rb,...Db],u=c.find(v=>v.id===t)?t:c[0].id,d=m.useRef(!1);u==="preview"&&(d.current=!0),m.useEffect(()=>{try{sessionStorage.getItem("sj_open_wp_tab")==="1"&&(sessionStorage.removeItem("sj_open_wp_tab"),r("wordpress"))}catch{}},[r]);const p=e!=="data-copilot"&&e!=="workflow",h=(y=Rb.find(v=>v.id===u))==null?void 0:y.label,f=(b=Db.find(v=>v.id===u))==null?void 0:b.label,x=({tab:v})=>a.jsxs("button",{onClick:()=>r(v.id),className:L("flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors whitespace-nowrap shrink-0",u===v.id?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-secondary"),children:[a.jsx(v.icon,{className:"w-3.5 h-3.5"}),v.label,v.id==="files"&&i>0&&a.jsx("span",{className:L("ml-0.5 min-w-[16px] h-[16px] px-1 rounded-full text-[9px] font-semibold flex items-center justify-center","bg-primary/15 text-primary"),children:i})]},v.id),g=({icon:v,label:k,activeLabel:N})=>{const j=!!N;return a.jsxs("button",{type:"button",className:L("flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors whitespace-nowrap shrink-0",j?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-secondary"),children:[a.jsx(v,{className:"w-3.5 h-3.5"}),j?N:k,a.jsx(Yr,{className:"w-3 h-3 opacity-60"})]})};return a.jsxs("div",{className:"h-full flex flex-col min-w-0 bg-card border-l border-t shadow-sm",children:[a.jsx(LZ,{}),a.jsxs("div",{className:"h-11 border-b flex items-center pl-1.5 pr-2 gap-2 shrink-0",children:[a.jsx("div",{className:"flex-1 flex items-center gap-0 overflow-x-auto scrollbar-hide min-w-0",children:p?a.jsxs(a.Fragment,{children:[p_.map(v=>a.jsx(x,{tab:v},v.id)),a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,children:a.jsx("span",{children:a.jsx(g,{icon:Hn,label:"Data",activeLabel:h})})}),a.jsxs(Jl,{align:"start",className:"w-44",children:[a.jsx(hu,{className:"text-[10px] uppercase tracking-wider text-muted-foreground
8242/70 font-semibold",children:"Data"}),a.jsx(ki,{}),Rb.map(v=>a.jsxs(Qr,{onClick:()=>r(v.id),className:L("text-[12.5px] gap-2",u===v.id&&"bg-primary/10 text-primary"),children:[a.jsx(v.icon,{className:"w-3.5 h-3.5"})," ",v.label]},v.id))]})]}),a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,children:a.jsx("span",{children:a.jsx(g,{icon:Cw,label:"More",activeLabel:f})})}),a.jsxs(Jl,{align:"start",className:"w-44",children:[a.jsx(hu,{className:"text-[10px] uppercase tracking-wider text-muted-foreground/70 font-semibold",children:"More"}),a.jsx(ki,{}),Db.map(v=>a.jsxs(Qr,{onClick:()=>r(v.id),className:L("text-[12.5px] gap-2",u===v.id&&"bg-primary/10 text-primary"),children:[a.jsx(v.icon,{className:"w-3.5 h-3.5"})," ",v.label]},v.id))]})]})]}):c.map(v=>a.jsx(x,{tab:v},v.id))}),a.jsx(Cye,{})]}),a.jsxs("div",{className:"flex-1 overflow-hidden",children:[u==="files"&&a.jsx(DZ,{}),u==="agents"&&a.jsx(jye,{}),u==="sql"&&a.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-muted-foreground p-8",children:[a.jsx(Hn,{className:"w-10 h-10 text-muted-foreground/40 mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"SQL Viewer"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Generated queries will appear here"})]}),d.current&&a.jsx("div",{className:"h-full",style:{display:u==="preview"?"block":"none"},children:a.jsx(Xme,{})}),u==="api"&&a.jsx(mge,{}),u==="schema"&&a.jsx(wge,{}),u==="diagram"&&a.jsx(Nge,{}),u==="query"&&a.jsx(jge,{}),u==="autodb"&&a.jsx(Rge,{}),u==="terminal"&&a.jsx(kye,{}),u==="tools"&&a.jsx(Ixe,{}),u==="library"&&a.jsx(Sge,{}),u==="mcp"&&a.jsx(Age,{}),u==="cloud"&&a.jsx(cye,{projectId:(s==null?void 0:s.id)||null,projectName:s==null?void 0:s.name}),u==="logs"&&a.jsx(Mxe,{projectId:(s==null?void 0:s.id)||null,onBack:()=>r("preview")}),u==="history"&&a.jsx(qxe,{}),u==="security"&&a.jsx(Iye,{}),u==="performance"&&a.jsx(Lye,{}),u==="github"&&a.jsx(oM,{}),u==="wordpress"&&a.jsx(_D,{})]})]})}const Uye=12*6e4;function h_(e){if(!e||e.status!=="running"||(e.events_count||0)>0||(e.files_count||0)>0)return!1;const t=new Date(e.started_at).getTime();return!Number.isNaN(t)&&Date.now()-t>Uye}function f_(e){G.from("build_jobs").update({status:"canceled",finished_at:new Date().toISOString(),error_message:"Cancelled automatically — server build stream never produced events."}).eq("id",e.id).catch(t=>{console.warn("[build_jobs] failed to auto-cancel zero-event job:",t)})}function zye(e){const{user:t}=Us(),r=(t==null?void 0:t.id)||null,[n,s]=m.useState(null),[i,o]=m.useState(!0);return m.useEffect(()=>{if(!e||!r){s(null);return}let l=!1;return(async()=>{try{const c=new Date(Date.now()-6e5).toISOString(),{data:u,error:d}=await G.from("build_jobs").select("id, status, started_at, finished_at, events_count, files_count, prompt, error_message, model").eq("user_id",r).eq("project_id",e).gte("started_at",c).in("status",["running","paused"]).order("started_at",{ascending:!1}).limit(1);if(l)return;if(d){String(d.message||"").match(/relation .* does not exist/i)&&o(!1),s(null);return}const p=u&&u[0]||null;if(h_(p)){f_(p),s(null);return}s(p)}catch{l||s(null)}})(),()=>{l=!0}},[e,r]),m.useEffect(()=>{if(!e||!r||!i)return;const l=G.channel(`build_jobs_${r}_${e}`).on("postgres_changes",{event:"*",schema:"public",table:"build_jobs",filter:`user_id=eq.${r}`},c=>{const u=c.new||c.old;!u||u.project_id!==e||(c.eventType==="DELETE"?s(null):h_(u)?(f_(u),s(null)):u.status==="running"||u.status==="paused"?s(u):(s(u),setTimeout(()=>{s(p=>(p==null?void 0:p.id)===u.id?null:p)},5e3)))}).subscribe();return()=>{G.removeChannel(l)}},[e,r,i]),{activeJob:n,supported:i}}function hm(e,t,r=""){for(const n of e){const s=r?`${r}/${n.name}`:n.name;if(n.type==="file"&&s===t)return n.content??"";if(n.type==="folder"&&n.children){const i=hm(n.children,t,s);if(i!==null)return i}}return null}async function qye(e,t,r){var n,s,i,o,l,c;try{const{data:u,error:d}=await G.from("build_events").select("seq,kind,payload").eq("job_id",e).order("seq",{ascending:!0}).limit(2e3);if(d)return{ok:!1,error:d.message,appliedCount:0,totalEvents:0};const p=u||[];let h=0;const f=new Map;for(const x of p){if(x.kind!=="tool_use")continue;const g=x.payload;if(!(g!=null&&g.name))continue;const y=typeof((n=g.input)==null?void 0:n.path)=="string"?g.input.path:null,b=String(g.id||`${x.seq}-replay`);if(g.name==="write_file"&&y&&typeof((s=g.input)==null?void 0:s.content)=="str
8242ing"){const v=g.input.content,k=f.has(y)?f.get(y):hm(t,y);r({path:y,newContent:v,oldContent:k,kind:k===null?"create":"modify",toolUseId:b}),f.set(y,v),h++}else if((g.name==="str_replace"||g.name==="edit_file")&&y){const v=((i=g.input)==null?void 0:i.old_str)??((o=g.input)==null?void 0:o.search),k=((l=g.input)==null?void 0:l.new_str)??((c=g.input)==null?void 0:c.replace),N=f.has(y)?f.get(y):hm(t,y);if(N!==null&&typeof v=="string"&&typeof k=="string"){const j=N.includes(v)?N.replace(v,k):N;r({path:y,newContent:j,oldContent:N,kind:"modify",toolUseId:b}),f.set(y,j),h++}}else if(g.name==="delete_file"&&y){const v=f.has(y)?f.get(y):hm(t,y);v!==null&&(r({path:y,newContent:"",oldContent:v,kind:"delete",toolUseId:b}),f.delete(y),h++)}}return{ok:!0,appliedCount:h,totalEvents:p.length}}catch(u){return{ok:!1,error:u.message,appliedCount:0,totalEvents:0}}}function Hye(){const{isMultiAgentRun:e,setIsMultiAgentRun:t,pendingFileChanges:r,acceptAllPendingChanges:n,rejectAllPendingChanges:s,setActiveWorkspaceTab:i,isBuilding:o,project:l,files:c,addPendingChange:u,lastBuildErrors:d,triggerBuildRef:p}=gn(),{activeJob:h}=zye((l==null?void 0:l.id)||null),[f,x]=m.useState(!1),[g,y]=m.useState(null),b=async()=>{if(h)try{await G.from("build_jobs").update({status:"canceled",finished_at:new Date().toISOString(),error_message:"Cancelled — build appeared stuck (no events recorded in >90s)."}).eq("id",h.id),y(h.id),W.success("Stuck server build cleared. You can continue without refreshing.")}catch(_){W.error(`Cancel failed: ${_.message}`)}},v=()=>{var I;if(!d.length)return;const _=d.slice(0,12).map((D,M)=>`${M+1}. ${D}`).join(`
8243`);(I=p.current)==null||I.call(p,`Fix the current build errors only. Make the smallest possible code edits and do not redesign or add features.
8244
8245Current build errors:
8246${_}
8247
8248After fixing, summarize only the files changed and why.`),h&&y(h.id),W.message("Repair prompt sent",{description:"The AI will patch only the failing build errors."})},k=async()=>{if(h){x(!0);try{const _=await qye(h.id,c,u);_.ok?_.appliedCount===0?W.info("Replay completed — no file changes recorded for this build."):(W.success(`Replayed ${_.appliedCount} change${_.appliedCount===1?"":"s"} from server.`),i("files")):W.error(`Replay failed: ${_.error}`)}finally{x(!1)}}},N=h&&(()=>{const _=new Date(h.started_at).getTime();return!Number.isNaN(_)&&Date.now()-_>10*60*1e3})(),j=h&&(()=>{if(h.status!=="running")return!1;const _=new Date(h.started_at).getTime();return Number.isNaN(_)?!1:Date.now()-_>6e4&&(h.events_count||0)===0})();if(!!h&&h.id!==g&&!N&&!j&&!o&&!e&&h){const _=h.status==="succeeded"||h.status==="failed"||h.status==="canceled",I=h.status==="failed";return a.jsxs("div",{role:"region","aria-label":"Server build status",className:L("flex items-center gap-3 px-4 py-2.5 border-b text-[13px]",I?"bg-destructive/10 border-destructive/25 text-foreground":_?"bg-emerald-500/10 border-emerald-500/25 text-foreground":"bg-primary/5 border-primary/15 text-foreground"),children:[I?a.jsx(Ar,{className:"w-4 h-4 text-destructive shrink-0"}):_?a.jsx(el,{className:"w-4 h-4 text-emerald-600 shrink-0"}):a.jsx(lc,{className:"w-4 h-4 text-primary shrink-0 animate-pulse"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"font-semibold truncate",children:I?"A previous build failed on the server":_?"Previous build completed — refresh to see the result":j&&d.length>0?"Build failed and needs a repair":j?"Server build lost connection":"A build is still running on the server"}),a.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5 truncate",children:j&&d.length>0?d[0].replace(/\s+/g," ").slice(0,140):I&&h.error_message?`Error: ${h.error_message.slice(0,120)}`:`Job ${h.id.slice(0,8)} · ${h.events_count} event${h.events_count===1?"":"s"}`})]}),j&&a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[d.length>0&&a.jsx("button",{onClick:v,className:"text-xs px-2.5 py-1 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition",title:"Ask the repair agent to patch the current build errors only",children:"Fix build"}),a.jsx("button",{onClick:b,className:"text-xs px-2.5 py-1 rounded-md border bg-background hover:bg-muted transition",title:"Dismiss this stale server build so you can keep working",children:"Dismiss"})]}),_&&!I&&a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsxs("button",{onClick:k,disabled:f,className:"text-xs px-2.5 py-1 rounded-md border bg-background hover:bg-muted transition flex items-center gap-1.5 disabled:opacity-50",title:"Replay this build's tool calls into the diff panel for review",children:[f?a.jsx(ze,{className:"w-3 h-3 animate-spin"}):a.jsx(y6,{className:"w-3 h-3"}),f?"Replaying…":"Replay & review"]}),a.jsx("button",{onClick:()=>window.location.reload(),className:"text-xs px-2.5 py-1 rounded-md bg-emerald-600 text-white hover:bg-emerald-700 transition",children:"Refresh"})]})]})}if(!e)return null;if(r.length===0&&!o)return t(!1),null;const S=r.reduce((_,I)=>(I.kind==="create"?_.create++:I.kind==="delete"?_.delete++:_.modify++,_),{create:0,modify:0,delete:0}),T=o||r.length===0,C=r.length,A=()=>{i("files"),requestAnimationFrame(()=>{const _=document.querySelector("[data-pending-changes-panel]");_==null||_.scrollIntoView({behavior:"smooth",block:"start"})})},P=()=>{n(),t(!1)},E=()=>{confirm(`Discard all ${C} pending change${C===1?"":"s"}? This cannot be undone.`)&&(s(),t(!1))};return a.jsxs("div",{role:"region","aria-label":"Multi-agent build approval",className:L("flex items-center gap-3 px-4 py-2.5 border-b text-[13px]",T?"bg-primary/5 border-primary/15 text-foreground":"bg-emerald-500/10 border-emerald-500/25 text-foreground"),children:[T?a.jsx(ze,{className:"w-4 h-4 text-primary animate-spin shrink-0"}):a.jsx(el,{className:"w-4 h-4 text-emerald-600 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"font-semibold truncate",children:T?"Pipeline running — staging changes for your review":"Build approved · ready to apply"}),C>0&&a.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-3 mt-0.5",children:[S.create>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(hT,{className:"w-3 h-3 text-green-600"}),S.create," new"]}),S.modify>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Vg,{className:"w-3 h-3 text-amber-600"}),S.modify," edited"]}),S.delete>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(pT,{className:"w-3 h-3 text-red-600"}),S.delete," removed"]})]})]}),!T&&C>0&&a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsxs("button",{onClick:A,className:"text-xs px-2.5 py-1 rounded-md border bg-background hover:bg-muted transition flex items-center gap-1.5",children:[a.jsx(ys,{className:"w-3 h-3"})," Review"]}),a.jsx("button",{onClick:E,className:"text-xs px-2.5 py-1 rounded-md border bg-background hover:bg-muted transition",children:"Discard"}),a.jsx("button",{onClick:P,className:"text-xs px-2.5 py-1 rounded-md bg-emerald-600 text-white hover:bg-emerald-700 transition font-medium",children:"Apply all"})]})]})}function Wye(){let e=null;try{e=sessionStorage.getItem("sj_pending_cloud_provision")}catch{return null}if(!e)return null;try{return JSON.parse(e)}
8248catch{try{sessionStorage.removeItem("sj_pending_cloud_provision")}catch{}return null}}function Vye(){var n,s;const e=il(),{provision:t}=a1(),r=m.useRef(!1);m.useEffect(()=>{var l;if(r.current)return;let i=!1;try{i=sessionStorage.getItem("sj_oauth_just_completed")==="1"}catch{}if(!i||!((l=e==null?void 0:e.project)!=null&&l.id))return;r.current=!0;try{sessionStorage.removeItem("sj_oauth_just_completed")}catch{}const o=Wye();if(!o||o.projectId!==e.project.id||!o.region){if(o)try{sessionStorage.removeItem("sj_pending_cloud_provision")}catch{}W.success("Supabase connected!",{description:"Open Cloud → Provision when you want a live database.",duration:8e3});return}try{sessionStorage.removeItem("sj_pending_cloud_provision")}catch{}(async()=>{var u;W.info("Provisioning your database…",{description:`Region: ${o.region}`});const c=await t(o.projectId,o.projectName||e.project.name,o.region);if(c.success){const d=(u=c.supabase_url)==null?void 0:u.replace(/^https?:\/\//,"").split("/")[0];W.success("Database ready",{description:d?`${d} · ${c.region||o.region}`:void 0,duration:8e3}),window.dispatchEvent(new CustomEvent("sj:infra-changed",{detail:{projectId:o.projectId}}));try{const{data:p}=await G.functions.invoke("sync-supabase-auth-url",{body:{projectId:o.projectId}});p!=null&&p.site_url&&W.success("Auth URL synced",{description:String(p.site_url),duration:5e3})}catch{}}else c.needs_connect||W.error("Database provisioning failed",{description:c.error})})()},[(n=e==null?void 0:e.project)==null?void 0:n.id,(s=e==null?void 0:e.project)==null?void 0:s.name,t])}const sy=m.createContext(null);sy.displayName="PanelGroupContext";const Gr={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"},Gj=10,sc=m.useLayoutEffect,m_=B_.useId,Gye=typeof m_=="function"?m_:()=>null;let Kye=0;function Kj(e=null){const t=Gye(),r=m.useRef(e||t||null);return r.current===null&&(r.current=""+Kye++),e??r.current}function jM({children:e,className:t="",collapsedSize:r,collapsible:n,defaultSize:s,forwardedRef:i,id:o,maxSize:l,minSize:c,onCollapse:u,onExpand:d,onResize:p,order:h,style:f,tagName:x="div",...g}){const y=m.useContext(sy);if(y===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:b,expandPanel:v,getPanelSize:k,getPanelStyle:N,groupId:j,isPanelCollapsed:w,reevaluatePanelConstraints:S,registerPanel:T,resizePanel:C,unregisterPanel:A}=y,P=Kj(o),E=m.useRef({callbacks:{onCollapse:u,onExpand:d,onResize:p},constraints:{collapsedSize:r,collapsible:n,defaultSize:s,maxSize:l,minSize:c},id:P,idIsFromProps:o!==void 0,order:h});m.useRef({didLogMissingDefaultSizeWarning:!1}),sc(()=>{const{callbacks:I,constraints:D}=E.current,M={...D};E.current.id=P,E.current.idIsFromProps=o!==void 0,E.current.order=h,I.onCollapse=u,I.onExpand=d,I.onResize=p,D.collapsedSize=r,D.collapsible=n,D.defaultSize=s,D.maxSize=l,D.minSize=c,(M.collapsedSize!==D.collapsedSize||M.collapsible!==D.collapsible||M.maxSize!==D.maxSize||M.minSize!==D.minSize)&&S(E.current,M)}),sc(()=>{const I=E.current;return T(I),()=>{A(I)}},[h,P,T,A]),m.useImperativeHandle(i,()=>({collapse:()=>{b(E.current)},expand:I=>{v(E.current,I)},getId(){return P},getSize(){return k(E.current)},isCollapsed(){return w(E.current)},isExpanded(){return!w(E.current)},resize:I=>{C(E.current,I)}}),[b,v,k,w,P,C]);const _=N(E.current,s);return m.createElement(x,{...g,children:e,className:t,id:P,style:{..._,...f},[Gr.groupId]:j,[Gr.panel]:"",[Gr.panelCollapsible]:n||void 0,[Gr.panelId]:P,[Gr.panelSize]:parseFloat(""+_.flexGrow).toFixed(1)})}const NM=m.forwardRef((e,t)=>m.createElement(jM,{...e,forwardedRef:t}));jM.displayName="Panel";NM.displayName="forwardRef(Panel)";let lw=null,fm=-1,Ho=null;function Yye(e,t){if(t){const r=(t&AM)!==0,n=(t&_M)!==0,s=(t&TM)!==0,i=(t&EM)!==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(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function Jye(){Ho!==null&&(document.head.removeChild(Ho),lw=null,Ho=null,fm=-1)}function Mb(e,t){var r,n;const s=Yye(e,t);
8248if(lw!==s){if(lw=s,Ho===null&&(Ho=document.createElement("style"),document.head.appendChild(Ho)),fm>=0){var i;(i=Ho.sheet)===null||i===void 0||i.removeRule(fm)}fm=(r=(n=Ho.sheet)===null||n===void 0?void 0:n.insertRule(`*{cursor: ${s} !important;}`))!==null&&r!==void 0?r:-1}}function kM(e){return e.type==="keydown"}function SM(e){return e.type.startsWith("pointer")}function CM(e){return e.type.startsWith("mouse")}function ay(e){if(SM(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(CM(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Xye(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function Zye(e,t,r){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Qye(e,t){if(e===t)throw new Error("Cannot compare node with itself");const r={a:y_(e),b:y_(t)};let n;for(;r.a.at(-1)===r.b.at(-1);)e=r.a.pop(),t=r.b.pop(),n=e;jn(n,"Stacking order can only be calculated for elements with a common ancestor");const s={a:x_(g_(r.a)),b:x_(g_(r.b))};if(s.a===s.b){const i=n.childNodes,o={a:r.a.at(-1),b:r.b.at(-1)};let l=i.length;for(;l--;){const c=i[l];if(c===o.a)return 1;if(c===o.b)return-1}}return Math.sign(s.a-s.b)}const ebe=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function tbe(e){var t;const r=getComputedStyle((t=PM(e))!==null&&t!==void 0?t:e).display;return r==="flex"||r==="inline-flex"}function nbe(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||tbe(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||ebe.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function g_(e){let t=e.length;for(;t--;){const r=e[t];if(jn(r,"Missing node"),nbe(r))return r}return null}function x_(e){return e&&Number(getComputedStyle(e).zIndex)||0}function y_(e){const t=[];for(;e;)t.push(e),e=PM(e);return t}function PM(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const AM=1,_M=2,TM=4,EM=8,rbe=Xye()==="coarse";let ui=[],wu=!1,Bl=new Map,iy=new Map;const jh=new Set;function sbe(e,t,r,n,s){var i;const{ownerDocument:o}=t,l={direction:r,element:t,hitAreaMargins:n,setResizeHandlerState:s},c=(i=Bl.get(o))!==null&&i!==void 0?i:0;return Bl.set(o,c+1),jh.add(l),Bg(),function(){var d;iy.delete(e),jh.delete(l);const p=(d=Bl.get(o))!==null&&d!==void 0?d:1;if(Bl.set(o,p-1),Bg(),p===1&&Bl.delete(o),ui.includes(l)){const h=ui.indexOf(l);h>=0&&ui.splice(h,1),Jj(),s("up",!0,null)}}}function abe(e){const{target:t}=e,{x:r,y:n}=ay(e);wu=!0,Yj({target:t,x:r,y:n}),Bg(),ui.length>0&&(Ug("down",e),e.preventDefault(),IM(t)||e.stopImmediatePropagation())}function Lb(e){const{x:t,y:r}=ay(e);if(wu&&e.buttons===0&&(wu=!1,Ug("up",e)),!wu){const{target:n}=e;Yj({target:n,x:t,y:r})}Ug("move",e),Jj(),ui.length>0&&e.preventDefault()}function $b(e){const{target:t}=e,{x:r,y:n}=ay(e);iy.clear(),wu=!1,ui.length>0&&(e.preventDefault(),IM(t)||e.stopImmediatePropagation()),Ug("up",e),Yj({target:t,x:r,y:n}),Jj(),Bg()}function IM(e){let t=e;for(;t;){if(t.hasAttribute(Gr.resizeHandle))return!0;t=t.parentElement}return!1}function Yj({target:e,x:t,y:r}){ui.splice(0);let n=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(n=e),jh.forEach(s=>{const{element:i,hitAreaMargins:o}=s,l=i.getBoundingClientRect(),{bottom:c,left:u,right:d,top:p}=l,h=rbe?o.coarse:o.fine;if(t>=u-h&&t<=d+h&&r>=p-h&&r<=c+h){if(n!==null&&document.contains(n)&&i!==n&&!i.contains(n)&&!n.contains(i)&&Qye(n,i)>0){let x=n,g=!1;for(;x&&!x.contains(i);){if(Zye(x.getBoundingClientRect(),l)){g=!0;break}x=x.parentElement}if(g)return}ui.push(s)}})}function Fb(e,t){iy.set(e,t)}function Jj(){let e=!1,t=!1;ui.forEach(n=>{const{direction:s}=n;s==="horizontal"?e=!0:t=!0});let r=0;iy.forEach(n=>{r|=n}),e&&t?Mb("intersection",r):e?Mb("horizontal",r):t?Mb("vertical",r):Jye()}let Bb=new AbortController;function Bg(){Bb.abort(),Bb=new AbortController;const e={capture:!0,signal:Bb.signal};jh.size&&(wu?(ui.length>0&&Bl.forEach((t,r)=>{const{body:n}=r;t>0&&(n.addEventListener("contextmenu",$b,e),n.addEventListener("pointerleave",Lb,e),n.addEventListener("pointermove",Lb,e))}),window.addEventListener("pointerup",$b,e),window.addEventListener("pointercancel",$b,e)):Bl.forEach((t,r)=>{const{body:n}=r;t>0&&(n.addEventListener("pointerdown",abe,e),n.addEventListener("pointermove",Lb,e))}))}
8248function Ug(e,t){jh.forEach(r=>{const{setResizeHandlerState:n}=r,s=ui.includes(r);n(e,s,t)})}function ibe(){const[e,t]=m.useState(0);return m.useCallback(()=>t(r=>r+1),[])}function jn(e,t){if(!e)throw console.error(t),Error(t)}function wc(e,t,r=Gj){return e.toFixed(r)===t.toFixed(r)?0:e>t?1:-1}function eo(e,t,r=Gj){return wc(e,t,r)===0}function ma(e,t,r){return wc(e,t,r)===0}function obe(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(!ma(s,i,r))return!1}return!0}function pu({panelConstraints:e,panelIndex:t,size:r}){const n=e[t];jn(n!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:s=0,collapsible:i,maxSize:o=100,minSize:l=0}=n;if(wc(r,l)<0)if(i){const c=(s+l)/2;wc(r,c)<0?r=s:r=l}else r=l;return r=Math.min(o,r),r=parseFloat(r.toFixed(Gj)),r}function cp({delta:e,initialLayout:t,panelConstraints:r,pivotIndices:n,prevLayout:s,trigger:i}){if(ma(e,0))return t;const o=[...t],[l,c]=n;jn(l!=null,"Invalid first pivot index"),jn(c!=null,"Invalid second pivot index");let u=0;if(i==="keyboard"){{const p=e<0?c:l,h=r[p];jn(h,`Panel constraints not found for index ${p}`);const{collapsedSize:f=0,collapsible:x,minSize:g=0}=h;if(x){const y=t[p];if(jn(y!=null,`Previous layout not found for panel index ${p}`),ma(y,f)){const b=g-y;wc(b,Math.abs(e))>0&&(e=e<0?0-b:b)}}}{const p=e<0?l:c,h=r[p];jn(h,`No panel constraints found for index ${p}`);const{collapsedSize:f=0,collapsible:x,minSize:g=0}=h;if(x){const y=t[p];if(jn(y!=null,`Previous layout not found for panel index ${p}`),ma(y,g)){const b=y-f;wc(b,Math.abs(e))>0&&(e=e<0?0-b:b)}}}}{const p=e<0?1:-1;let h=e<0?c:l,f=0;for(;;){const g=t[h];jn(g!=null,`Previous layout not found for panel index ${h}`);const b=pu({panelConstraints:r,panelIndex:h,size:100})-g;if(f+=b,h+=p,h<0||h>=r.length)break}const x=Math.min(Math.abs(e),Math.abs(f));e=e<0?0-x:x}{let h=e<0?l:c;for(;h>=0&&h<r.length;){const f=Math.abs(e)-Math.abs(u),x=t[h];jn(x!=null,`Previous layout not found for panel index ${h}`);const g=x-f,y=pu({panelConstraints:r,panelIndex:h,size:g});if(!ma(x,y)&&(u+=x-y,o[h]=y,u.toPrecision(3).localeCompare(Math.abs(e).toPrecision(3),void 0,{numeric:!0})>=0))break;e<0?h--:h++}}if(obe(s,o))return s;{const p=e<0?c:l,h=t[p];jn(h!=null,`Previous layout not found for panel index ${p}`);const f=h+u,x=pu({panelConstraints:r,panelIndex:p,size:f});if(o[p]=x,!ma(x,f)){let g=f-x,b=e<0?c:l;for(;b>=0&&b<r.length;){const v=o[b];jn(v!=null,`Previous layout not found for panel index ${b}`);const k=v+g,N=pu({panelConstraints:r,panelIndex:b,size:k});if(ma(v,N)||(g-=N-v,o[b]=N),ma(g,0))break;e>0?b--:b++}}}const d=o.reduce((p,h)=>h+p,0);return ma(d,100)?o:s}function lbe({layout:e,panelsArray:t,pivotIndices:r}){let n=0,s=100,i=0,o=0;const l=r[0];jn(l!=null,"No pivot index found"),t.forEach((p,h)=>{const{constraints:f}=p,{maxSize:x=100,minSize:g=0}=f;h===l?(n=g,s=x):(i+=g,o+=x)});const c=Math.min(s,100-i),u=Math.max(n,100-o),d=e[l];return{valueMax:c,valueMin:u,valueNow:d}}function Nh(e,t=document){return Array.from(t.querySelectorAll(`[${Gr.resizeHandleId}][data-panel-group-id="${e}"]`))}function OM(e,t,r=document){const s=Nh(e,r).findIndex(i=>i.getAttribute(Gr.resizeHandleId)===t);return s??null}function RM(e,t,r){const n=OM(e,t,r);return n!=null?[n,n+1]:[-1,-1]}function DM(e,t=document){var r;if(t instanceof HTMLElement&&(t==null||(r=t.dataset)===null||r===void 0?void 0:r.panelGroupId)==e)return t;
8248const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function oy(e,t=document){const r=t.querySelector(`[${Gr.resizeHandleId}="${e}"]`);return r||null}function cbe(e,t,r,n=document){var s,i,o,l;const c=oy(t,n),u=Nh(e,n),d=c?u.indexOf(c):-1,p=(s=(i=r[d])===null||i===void 0?void 0:i.id)!==null&&s!==void 0?s:null,h=(o=(l=r[d+1])===null||l===void 0?void 0:l.id)!==null&&o!==void 0?o:null;return[p,h]}function ube({committedValuesRef:e,eagerValuesRef:t,groupId:r,layout:n,panelDataArray:s,panelGroupElement:i,setLayout:o}){m.useRef({didWarnAboutMissingResizeHandle:!1}),sc(()=>{if(!i)return;const l=Nh(r,i);for(let c=0;c<s.length-1;c++){const{valueMax:u,valueMin:d,valueNow:p}=lbe({layout:n,panelsArray:s,pivotIndices:[c,c+1]}),h=l[c];if(h!=null){const f=s[c];jn(f,`No panel data found for index "${c}"`),h.setAttribute("aria-controls",f.id),h.setAttribute("aria-valuemax",""+Math.round(u)),h.setAttribute("aria-valuemin",""+Math.round(d)),h.setAttribute("aria-valuenow",p!=null?""+Math.round(p):"")}}return()=>{l.forEach((c,u)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[r,n,s,i]),m.useEffect(()=>{if(!i)return;const l=t.current;jn(l,"Eager values not found");const{panelDataArray:c}=l,u=DM(r,i);jn(u!=null,`No group found for id "${r}"`);const d=Nh(r,i);jn(d,`No resize handles found for group id "${r}"`);const p=d.map(h=>{const f=h.getAttribute(Gr.resizeHandleId);jn(f,"Resize handle element has no handle id attribute");const[x,g]=cbe(r,f,c,i);if(x==null||g==null)return()=>{};const y=b=>{if(!b.defaultPrevented)switch(b.key){case"Enter":{b.preventDefault();const v=c.findIndex(k=>k.id===x);if(v>=0){const k=c[v];jn(k,`No panel data found for index ${v}`);const N=n[v],{collapsedSize:j=0,collapsible:w,minSize:S=0}=k.constraints;if(N!=null&&w){const T=cp({delta:ma(N,j)?S-j:j-N,initialLayout:n,panelConstraints:c.map(C=>C.constraints),pivotIndices:RM(r,f,i),prevLayout:n,trigger:"keyboard"});n!==T&&o(T)}}break}}};return h.addEventListener("keydown",y),()=>{h.removeEventListener("keydown",y)}});return()=>{p.forEach(h=>h())}},[i,e,t,r,n,s,o])}function b_(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function MM(e,t){const r=e==="horizontal",{x:n,y:s}=ay(t);return r?n:s}function dbe(e,t,r,n,s){const i=r==="horizontal",o=oy(t,s);jn(o,`No resize handle element found for id "${t}"`);const l=o.getAttribute(Gr.groupId);jn(l,"Resize handle element has no group id attribute");let{initialCursorPosition:c}=n;const u=MM(r,e),d=DM(l,s);jn(d,`No group element found for id "${l}"`);const p=d.getBoundingClientRect(),h=i?p.width:p.height;return(u-c)/h*100}function pbe(e,t,r,n,s,i){if(kM(e)){const o=r==="horizontal";let l=0;e.shiftKey?l=100:s!=null?l=s:l=10;let c=0;switch(e.key){case"ArrowDown":c=o?0:l;break;case"ArrowLeft":c=o?-l:0;break;case"ArrowRight":c=o?l:0;break;case"ArrowUp":c=o?0:-l;break;case"End":c=100;break;case"Home":c=-100;break}return c}else return n==null?0:dbe(e,t,r,n,i)}function hbe({panelDataArray:e}){const t=Array(e.length),r=e.map(i=>i.constraints);let n=0,s=100;for(let i=0;i<e.length;i++){const o=r[i];jn(o,`Panel constraints not found for index ${i}`);const{defaultSize:l}=o;l!=null&&(n++,t[i]=l,s-=l)}for(let i=0;i<e.length;i++){const o=r[i];jn(o,`Panel constraints not found for index ${i}`);const{defaultSize:l}=o;if(l!=null)continue;const c=e.length-n,u=s/c;n++,t[i]=u,s-=u}return t}function Zc(e,t,r){t.forEach((n,s)=>{const i=e[s];jn(i,`Panel data not found for index ${s}`);const{callbacks:o,constraints:l,id:c}=i,{collapsedSize:u=0,collapsible:d}=l,p=r[c];if(p==null||n!==p){r[c]=n;const{onCollapse:h,onExpand:f,onResize:x}=o;x&&x(n,p),d&&(h||f)&&(f&&(p==null||eo(p,u))&&!eo(n,u)&&f(),h&&(p==null||!eo(p,u))&&eo(n,u)&&h())}})}function Kf(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!=t[r])return!1;return!0}function fbe({defaultSize:e,dragState:t,layout:r,panelData:n,panelIndex:s,precision:i=3}){const o=r[s];let l;return o==null?l=e!=null?e.toPrecision(i):"1":n.length===1?l="1":l=o.toPrecision(i),{flexBasis:0,flexGrow:l,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function mbe(e,t=10){let r=null;return(...s)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...s)},t)}}function v_(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,r)=>{localStorage.setItem(t,r)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function LM(e){return`react-resizable-panels:${e}`}function $M(e){return e.map(t=>{const{constraints:r,id:n,idIsFromProps:s,order:i}=t;return s?n:i?`${i}:${JSON.stringify(r)}`:JSON.stringify(r)}).sort((t,r)=>t.localeCompare(r)).join(",")}function FM(e,t){try{const r=LM(e),n=t.getItem(r);if(n){const s=JSON.parse(n);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function gbe(e,t,r){var n,s;const i=(n=FM(e,r))!==null&&n!==void 0?n:{},o=$M(t);return(s=i[o])!==null&&s!==void 0?s:null}function xbe(e,t,r,n,s){var i;const o=LM(e),l=$M(t),c=(i=FM(e,s))!==null&&i!==void 0?i:{};c[l]={expandToSizes:Object.fromEntries(r.entries()),layout:n};try{s.setItem(o,JSON.stringify(c))}catch(u){console.error(u)}}function w_({layout:e,panelConstraints:t}){const r=[...e],n=r.reduce((i,o)=>i+o,0);if(r.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${r.map(i=>`${i}%`).join(", ")}`);
8248if(!ma(n,100)&&r.length>0)for(let i=0;i<t.length;i++){const o=r[i];jn(o!=null,`No layout data found for index ${i}`);const l=100/n*o;r[i]=l}let s=0;for(let i=0;i<t.length;i++){const o=r[i];jn(o!=null,`No layout data found for index ${i}`);const l=pu({panelConstraints:t,panelIndex:i,size:o});o!=l&&(s+=o-l,r[i]=l)}if(!ma(s,0))for(let i=0;i<t.length;i++){const o=r[i];jn(o!=null,`No layout data found for index ${i}`);const l=o+s,c=pu({panelConstraints:t,panelIndex:i,size:l});if(o!==c&&(s-=c-o,r[i]=c,ma(s,0)))break}return r}const ybe=100,up={getItem:e=>(v_(up),up.getItem(e)),setItem:(e,t)=>{v_(up),up.setItem(e,t)}},j_={};function BM({autoSaveId:e=null,children:t,className:r="",direction:n,forwardedRef:s,id:i=null,onLayout:o=null,keyboardResizeBy:l=null,storage:c=up,style:u,tagName:d="div",...p}){const h=Kj(i),f=m.useRef(null),[x,g]=m.useState(null),[y,b]=m.useState([]),v=ibe(),k=m.useRef({}),N=m.useRef(new Map),j=m.useRef(0),w=m.useRef({autoSaveId:e,direction:n,dragState:x,id:h,keyboardResizeBy:l,onLayout:o,storage:c}),S=m.useRef({layout:y,panelDataArray:[],panelDataArrayChanged:!1});m.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),m.useImperativeHandle(s,()=>({getId:()=>w.current.id,getLayout:()=>{const{layout:O}=S.current;return O},setLayout:O=>{const{onLayout:ne}=w.current,{layout:oe,panelDataArray:he}=S.current,ae=w_({layout:O,panelConstraints:he.map(ve=>ve.constraints)});b_(oe,ae)||(b(ae),S.current.layout=ae,ne&&ne(ae),Zc(he,ae,k.current))}}),[]),sc(()=>{w.current.autoSaveId=e,w.current.direction=n,w.current.dragState=x,w.current.id=h,w.current.onLayout=o,w.current.storage=c}),ube({committedValuesRef:w,eagerValuesRef:S,groupId:h,layout:y,panelDataArray:S.current.panelDataArray,setLayout:b,panelGroupElement:f.current}),m.useEffect(()=>{const{panelDataArray:O}=S.current;if(e){if(y.length===0||y.length!==O.length)return;let ne=j_[e];ne==null&&(ne=mbe(xbe,ybe),j_[e]=ne);const oe=[...O],he=new Map(N.current);ne(e,oe,he,y,c)}},[e,y,c]),m.useEffect(()=>{});const T=m.useCallback(O=>{const{onLayout:ne}=w.current,{layout:oe,panelDataArray:he}=S.current;if(O.constraints.collapsible){const ae=he.map(le=>le.constraints),{collapsedSize:ve=0,panelSize:re,pivotIndices:se}=Il(he,O,oe);if(jn(re!=null,`Panel size not found for panel "${O.id}"`),!eo(re,ve)){N.current.set(O.id,re);const te=ru(he,O)===he.length-1?re-ve:ve-re,We=cp({delta:te,initialLayout:oe,panelConstraints:ae,pivotIndices:se,prevLayout:oe,trigger:"imperative-api"});Kf(oe,We)||(b(We),S.current.layout=We,ne&&ne(We),Zc(he,We,k.current))}}},[]),C=m.useCallback((O,ne)=>{const{onLayout:oe}=w.current,{layout:he,panelDataArray:ae}=S.current;if(O.constraints.collapsible){const ve=ae.map(Me=>Me.constraints),{collapsedSize:re=0,panelSize:se=0,minSize:le=0,pivotIndices:te}=Il(ae,O,he),We=ne??le;if(eo(se,re)){const Me=N.current.get(O.id),Te=Me!=null&&Me>=We?Me:We,st=ru(ae,O)===ae.length-1?se-Te:Te-se,xt=cp({delta:st,initialLayout:he,panelConstraints:ve,pivotIndices:te,prevLayout:he,trigger:"imperative-api"});Kf(he,xt)||(b(xt),S.current.layout=xt,oe&&oe(xt),Zc(ae,xt,k.current))}}},[]),A=m.useCallback(O=>{const{layout:ne,panelDataArray:oe}=S.current,{panelSize:he}=Il(oe,O,ne);return jn(he!=null,`Panel size not found for panel "${O.id}"`),he},[]),P=m.useCallback((O,ne)=>{const{panelDataArray:oe}=S.current,he=ru(oe,O);return fbe({defaultSize:ne,dragState:x,layout:y,panelData:oe,panelIndex:he})},[x,y]),E=m.useCallback(O=>{const{layout:ne,panelDataArray:oe}=S.current,{collapsedSize:he=0,collapsible:ae,panelSize:ve}=Il(oe,O,ne);return jn(ve!=null,`Panel size not found for panel "${O.id}"`),ae===!0&&eo(ve,he)},[]),_=m.useCallback(O=>{const{layout:ne,panelDataArray:oe}=S.current,{collapsedSize:he=0,collapsible:ae,panelSize:ve}=Il(oe,O,ne);return jn(ve!=null,`Panel size not found for panel "${O.id}"`),!ae||wc(ve,he)>0},[]),I=m.useCallback(O=>{const{panelDataArray:ne}=S.current;ne.push(O),ne.sort((oe,he)=>{const ae=oe.order,ve=he.order;return ae==null&&ve==null?0:ae==null?-1:ve==null?1:ae-ve}),S.current.panelDataArrayChanged=!0,v()},[v]);sc(()=>
8248{if(S.current.panelDataArrayChanged){S.current.panelDataArrayChanged=!1;const{autoSaveId:O,onLayout:ne,storage:oe}=w.current,{layout:he,panelDataArray:ae}=S.current;let ve=null;if(O){const se=gbe(O,ae,oe);se&&(N.current=new Map(Object.entries(se.expandToSizes)),ve=se.layout)}ve==null&&(ve=hbe({panelDataArray:ae}));const re=w_({layout:ve,panelConstraints:ae.map(se=>se.constraints)});b_(he,re)||(b(re),S.current.layout=re,ne&&ne(re),Zc(ae,re,k.current))}}),sc(()=>{const O=S.current;return()=>{O.layout=[]}},[]);const D=m.useCallback(O=>{let ne=!1;const oe=f.current;return oe&&window.getComputedStyle(oe,null).getPropertyValue("direction")==="rtl"&&(ne=!0),function(ae){ae.preventDefault();const ve=f.current;if(!ve)return()=>null;const{direction:re,dragState:se,id:le,keyboardResizeBy:te,onLayout:We}=w.current,{layout:Me,panelDataArray:Te}=S.current,{initialLayout:Ee}=se??{},st=RM(le,O,ve);let xt=pbe(ae,O,re,se,te,ve);const on=re==="horizontal";on&&ne&&(xt=-xt);const Yt=Te.map(at=>at.constraints),mt=cp({delta:xt,initialLayout:Ee??Me,panelConstraints:Yt,pivotIndices:st,prevLayout:Me,trigger:kM(ae)?"keyboard":"mouse-or-touch"}),ln=!Kf(Me,mt);(SM(ae)||CM(ae))&&j.current!=xt&&(j.current=xt,!ln&&xt!==0?on?Fb(O,xt<0?AM:_M):Fb(O,xt<0?TM:EM):Fb(O,0)),ln&&(b(mt),S.current.layout=mt,We&&We(mt),Zc(Te,mt,k.current))}},[]),M=m.useCallback((O,ne)=>{const{onLayout:oe}=w.current,{layout:he,panelDataArray:ae}=S.current,ve=ae.map(Me=>Me.constraints),{panelSize:re,pivotIndices:se}=Il(ae,O,he);jn(re!=null,`Panel size not found for panel "${O.id}"`);const te=ru(ae,O)===ae.length-1?re-ne:ne-re,We=cp({delta:te,initialLayout:he,panelConstraints:ve,pivotIndices:se,prevLayout:he,trigger:"imperative-api"});Kf(he,We)||(b(We),S.current.layout=We,oe&&oe(We),Zc(ae,We,k.current))},[]),B=m.useCallback((O,ne)=>{const{layout:oe,panelDataArray:he}=S.current,{collapsedSize:ae=0,collapsible:ve}=ne,{collapsedSize:re=0,collapsible:se,maxSize:le=100,minSize:te=0}=O.constraints,{panelSize:We}=Il(he,O,oe);We!=null&&(ve&&se&&eo(We,ae)?eo(ae,re)||M(O,re):We<te?M(O,te):We>le&&M(O,le))},[M]),$=m.useCallback((O,ne)=>{const{direction:oe}=w.current,{layout:he}=S.current;if(!f.current)return;const ae=oy(O,f.current);jn(ae,`Drag handle element not found for id "${O}"`);const ve=MM(oe,ne);g({dragHandleId:O,dragHandleRect:ae.getBoundingClientRect(),initialCursorPosition:ve,initialLayout:he})},[]),K=m.useCallback(()=>{g(null)},[]),R=m.useCallback(O=>{const{panelDataArray:ne}=S.current,oe=ru(ne,O);oe>=0&&(ne.splice(oe,1),delete k.current[O.id],S.current.panelDataArrayChanged=!0,v())},[v]),Y=m.useMemo(()=>({collapsePanel:T,direction:n,dragState:x,expandPanel:C,getPanelSize:A,getPanelStyle:P,groupId:h,isPanelCollapsed:E,isPanelExpanded:_,reevaluatePanelConstraints:B,registerPanel:I,registerResizeHandle:D,resizePanel:M,startDragging:$,stopDragging:K,unregisterPanel:R,panelGroupElement:f.current}),[T,x,n,C,A,P,h,E,_,B,I,D,M,$,K,R]),Z={display:"flex",flexDirection:n==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return m.createElement(sy.Provider,{value:Y},m.createElement(d,{...p,children:t,className:r,id:i,ref:f,style:{...Z,...u},[Gr.group]:"",[Gr.groupDirection]:n,[Gr.groupId]:h}))}const UM=m.forwardRef((e,t)=>m.createElement(BM,{...e,forwardedRef:t}));BM.displayName="PanelGroup";UM.displayName="forwardRef(PanelGroup)";function ru(e,t){return e.findIndex(r=>r===t||r.id===t.id)}function Il(e,t,r){const n=ru(e,t),i=n===e.length-1?[n-1,n]:[n,n+1],o=r[n];return{...t.constraints,panelSize:o,pivotIndices:i}}function bbe({disabled:e,handleId:t,resizeHandler:r,panelGroupElement:n}){m.useEffect(()=>{if(e||r==null||n==null)return;const s=oy(t,n);if(s==null)return;const i=o=>{if(!o.defaultPrevented)switch(o.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{o.preventDefault(),r(o);break}case"F6":{o.preventDefault();const l=s.getAttribute(Gr.groupId);jn(l,`No group element found for id "${l}"`);const c=Nh(l,n),u=OM(l,t,n);jn(u!==null,`No resize element found for id "${t}"`);const d=o.shiftKey?u>0?u-1:c.length-1:u+1<c.length?u+1:0;c[d].focus();break}}};return s.addEventListener("keydown",i),()=>{s.removeEventListener("keydown",i)}},[n,e,t,r])}function zM({children:e=null,className:t="",disabled:r=!1,hitAreaMargins:n,id:s,onBlur:i,onClick:o,onDragging:l,onFocus:c,onPointerDown:u,onPointerUp:d,style:p={},tabIndex:h=0,tagName:f="div",...x}){var g,y;const b=m.useRef(null),v=m.useRef({onClick:o,onDragging:l,onPointerDown:u,onPointerUp:d});m.useEffect(()=>{v.current.onClick=o,v.current.onDragging=l,v.current.onPointerDown=u,v.current.onPointerUp=d});const k=m.useContext(sy);if(k===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:N,groupId:j,registerResizeHandle:w,startDragging:S,stopDragging:T,panelGroupElement:C}=k,A=Kj(s),[P,E]=m.useState("inactive"),[_,I]=m.useState(!1),[D,M]=m.useState(null),B=m.useRef({state:P});sc(()=>{B.current.state=P}),m.useEffect(()=>{if(r)M(null);else{const Y=w(A);M(()=>Y)}},[r,A,w]);const $=(g=n==null?void 0:n.coarse)!==null&&g!==void 0?g:15,K=(y=n==null?void 0:n.fine)!==null&&y!==void 0?y:5;m.useEffect(()=>{if(r||D==null)return;const Y=b.current;jn(Y,"Element ref not attached");let Z=!1;return sbe(A,Y,N,{coarse:$,fine:K},(ne,oe,he)=>{if(!oe){E("inactive");return}switch(ne){case"down":{E("drag"),Z=!1,jn(he,'Expected event to be defined for "down" action'),S(A,he);const{onDragging:ae,onPointerDown:ve}=v.current;ae==null||ae(!0),ve==null||ve();break}case"move":{const{state:ae}=B.current;Z=!0,ae!=="drag"&&E("hover"),jn(he,'Expected event to be defined for "move" action'),D(he);break}case"up":{E("hover"),T();const{onClick:ae,onDragging:ve,onPointerUp:re}=v.current;
8248ve==null||ve(!1),re==null||re(),Z||ae==null||ae();break}}})},[$,N,r,K,w,A,D,S,T]),bbe({disabled:r,handleId:A,resizeHandler:D,panelGroupElement:C});const R={touchAction:"none",userSelect:"none"};return m.createElement(f,{...x,children:e,className:t,id:s,onBlur:()=>{I(!1),i==null||i()},onFocus:()=>{I(!0),c==null||c()},ref:b,role:"separator",style:{...R,...p},tabIndex:h,[Gr.groupDirection]:N,[Gr.groupId]:j,[Gr.resizeHandle]:"",[Gr.resizeHandleActive]:P==="drag"?"pointer":_?"keyboard":void 0,[Gr.resizeHandleEnabled]:!r,[Gr.resizeHandleId]:A,[Gr.resizeHandleState]:P})}zM.displayName="PanelResizeHandle";const qM=({className:e,...t})=>a.jsx(UM,{className:L("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),zg=NM,HM=({withHandle:e,className:t,...r})=>a.jsx(zM,{className:L("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:e&&a.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:a.jsx(fT,{className:"h-2.5 w-2.5"})})});function WM(){const e=new Date().getFullYear();return a.jsx("footer",{className:"shrink-0 border-t bg-card/70 backdrop-blur-sm px-4 py-2.5 relative z-20",children:a.jsxs("div",{className:"mx-auto flex w-full items-center justify-between gap-3 text-xs text-muted-foreground",children:[a.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[a.jsxs("a",{href:"https://studiojungle.ai",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 hover:opacity-80 transition-opacity",children:[a.jsx("img",{src:"/studio-jungle-mark.svg",alt:"",className:"h-6 w-6 rounded-lg object-contain",loading:"lazy"}),a.jsx("img",{src:"/logo.png",alt:"Studiojungle",className:"h-8 w-auto object-contain cursor-pointer",loading:"lazy"})]}),a.jsx("span",{className:"truncate",children:"Build faster in the jungle."})]}),a.jsxs("span",{className:"shrink-0",children:["© ",e," Studiojungle"]})]})})}function vbe({initialPrompt:e,onGoHome:t}){const r=il(),n=m.useRef(!1),[s,i]=m.useState(!1),o=m.useRef(null);Vye(),m.useEffect(()=>{if(!e||n.current)return;let c=!1,u=0;const d=120,p=()=>{var f;if(c||n.current)return;const h=(f=r==null?void 0:r.triggerBuildRef)==null?void 0:f.current;if(h){n.current=!0,console.log("[studio] Triggering initial build from StudioLayout"),h(e);return}if(u+=1,u<d){window.setTimeout(p,100);return}console.warn("[studio] triggerBuildRef never became ready — dispatching sj:trigger-initial-build fallback");try{window.dispatchEvent(new CustomEvent("sj:trigger-initial-build",{detail:{prompt:e}}))}catch{}};return window.setTimeout(p,50),()=>{c=!0}},[e,r]);const l=m.useCallback(()=>{var c,u;s?((c=o.current)==null||c.expand(),i(!1)):((u=o.current)==null||u.collapse(),i(!0))},[s]);return m.useEffect(()=>{function c(u){var d;if(u.key==="Escape"){try{document.fullscreenElement&&document.exitFullscreen().catch(()=>null)}catch{}s&&((d=o.current)==null||d.expand(),i(!1))}else(u.metaKey||u.ctrlKey)&&u.key==="\\"&&(u.preventDefault(),l())}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[s,l]),r?a.jsxs("div",{className:"h-screen flex flex-col overflow-hidden bg-background relative",children:[a.jsx(J9,{onGoHome:t,chatCollapsed:s,onToggleChat:l}),a.jsx(Hye,{}),a.jsxs("div",{className:"flex-1 overflow-hidden relative",children:[a.jsxs(qM,{direction:"horizontal",className:"h-full",autoSaveId:"studio-layout-v5",children:[a.jsx(zg,{ref:o,defaultSize:33,minSize:18,maxSize:50,collapsible:!0,collapsedSize:0,onCollapse:()=>i(!0),onExpand:()=>i(!1),className:L("bg-card",s&&"min-w-0"),children:a.jsx(kZ,{chatCollapsed:s,onToggleChat:l})}),a.jsx(HM,{withHandle:!0}),a.jsx(zg,{defaultSize:67,minSize:40,children:a.jsx(Bye,{})})]}),s&&a.jsx("button",{type:"button",onClick:l,title:"Show chat panel (Esc or ⌘\\\\)",className:"absolute left-3 top-1/2 -translate-y-1/2 z-[60] h-12 w-9 rounded-r-xl bg-card border border-l-0 shadow-lg flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:a.jsx(bT,{className:"w-4 h-4"})})]}),a.jsx(WM,{})]}):a.jsx("div",{className:"h-screen flex items-center justify-center bg-background text-muted-foreground text-sm",children:"Loading studio..."})}const N_=[{from:"from-violet-500/80",to:"to-fuchsia-500/80"},{from:"from-sky-500/80",to:"to-cyan-400/80"},{from:"from-emerald-500/80",to:"to-teal-400/80"},{from:"from-orange-500/80",to:"to-amber-400/80"},{from:"from-rose-500/80",to:"to-pink-400/80"},{from:"from-indigo-500/80",to:"to-blue-400/80"}],k_=[Br,tl,Nc,sd,Es];function wbe(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)|0;return Math.abs(t)}function S_(e){try{const t=rx(e);return DE(t)?"Today":C9(t)?"Yesterday":RE(t)?$s(t,{addSuffix:!0}):OE(t,"MMM d, yyyy")}catch{return""}}function jbe({project:e,onSelect:t,onDelete:r,onDescriptionGenerated:n}){const[s,i]=m.useState(!1),o=wbe(e.id),l=N_[o%N_.length],c=k_[o%k_.length],u=async d=>{d.stopPropagation(),i(!0);try{const{data:p}=await G.from("project_messages").select("role, content").eq("project_id",e.id).order("created_at",{ascending:!0}).limit(6),{data:h,error:f}=await G.functions.invoke("generate-description",{body:{projectName:e.name,messages:p||[]}});if(f)throw f;const x=(h==null?void 0:h.description)||"A new project";await G.from("projects").update({description:x}).eq("id",e.id),n(e.id,x),W.success("Description generated!")}catch(p){console.error(p),W.error("Failed to generate description")}finally{i(!1)}};return a.jsxs("div",{className:"group relative bg-card border rounded-2xl overflow-hidden hover:shadow-lg hover:border-primary/30 transition-all duration-300 cursor-pointer",onClick:t,children:[a.jsxs("div",{className:L("relative h-36 overflow-hidden",!e.thumbnail_url&&`bg-gradient-to-br ${l.from} ${l.to}`),children:[e.thumbnail_url?a.jsx("img",{src:e.thumbnail_url,alt:e.name,className:"w-full h-full object-cover object-top",loading:"lazy"}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0 opacity-10",style:{backgroundImage:"linear-gradient(white 1px, transparent 1px), linear-gradient(90deg, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),a.jsx("div",{className:"absolute top-4 right-4 w-20 h-20 rounded-xl border border-white/20 bg-white/10 backdrop-blur-sm rotate-12 group-hover:rotate-6 transition-transform duration-500"}),a.jsx("div",{className:"absolute bottom-6 left-6 w-14 h-14 roun
8248ded-lg border border-white/15 bg-white/10 backdrop-blur-sm -rotate-6 group-hover:rotate-0 transition-transform duration-500"}),a.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:a.jsx("div",{className:"w-16 h-16 rounded-2xl bg-white/20 backdrop-blur-md flex items-center justify-center shadow-lg",children:a.jsx(c,{className:"w-8 h-8 text-white"})})})]}),a.jsx("button",{onClick:d=>{d.stopPropagation(),r()},className:"absolute top-2.5 right-2.5 opacity-0 group-hover:opacity-100 p-1.5 rounded-lg bg-black/30 backdrop-blur-sm text-white/70 hover:text-white hover:bg-destructive/80 transition-all",children:a.jsx(oa,{className:"w-3.5 h-3.5"})})]}),a.jsxs("div",{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("h3",{className:"font-semibold text-foreground text-sm truncate",children:e.name}),a.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-[11px] text-muted-foreground
8248/70",children:[a.jsx(lT,{className:"w-3 h-3"}),a.jsx("span",{children:S_(e.created_at)}),e.updated_at!==e.created_at&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"mx-0.5",children:"·"}),a.jsxs("span",{children:["edited ",S_(e.updated_at)]})]})]}),a.jsxs("div",{className:"flex items-start gap-1.5 mt-1.5",children:[a.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",children:e.description||"No description yet"}),a.jsx("button",{onClick:u,disabled:s,className:"shrink-0 p-1 rounded-md hover:bg-primary/10 text-muted-foreground hover:text-primary transition-all disabled:opacity-50",title:"Generate AI description",children:s?a.jsx(ze,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(Dn,{className:"w-3.5 h-3.5"})})]})]}),a.jsx("div",{className:"shrink-0 opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center",children:a.jsx(Sh,{className:"w-4 h-4 text-primary"})})})]}),a.jsx("div",{className:"mt-2 flex items-center gap-1",children:a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground/50",children:["#",e.id.slice(0,8)]})})]})]})}function C_({projects:e,onSelectProject:t,onDeleteProject:r,headerTitle:n,headerDescription:s,emptyTitle:i,emptyDescription:o}){const[l,c]=m.useState(""),[u,d]=m.useState("recent"),[p,h]=m.useState("all"),[f,x]=m.useState({}),g=m.useCallback((N,j)=>{x(w=>({...w,[N]:j}))},[]),y=m.useMemo(()=>e.map(N=>({...N,description:f[N.id]||N.description})),[e,f]),b=m.useMemo(()=>{let N=[...y];if(p!=="all"&&(N=N.filter(j=>{try{const w=rx(j.created_at);if(p==="today")return DE(w);if(p==="week")return RE(w);if(p==="month")return k9(w)}catch{return!0}return!0})),l.trim()){const j=l.toLowerCase();N=N.filter(w=>{var S;return w.name.toLowerCase().includes(j)||((S=w.description)==null?void 0:S.toLowerCase().includes(j))||w.id.toLowerCase().startsWith(j)})}switch(u){case"recent":N.sort((j,w)=>new Date(w.updated_at).getTime()-new Date(j.updated_at).getTime());break;case"oldest":N.sort((j,w)=>new Date(j.created_at).getTime()-new Date(w.created_at).getTime());break;case"name":N.sort((j,w)=>j.name.localeCompare(w.name));break;case"name-desc":N.sort((j,w)=>w.name.localeCompare(j.name));break}return N},[y,l,u,p]),v=[{id:"recent",label:"Recent",icon:Lr},{id:"oldest",label:"Oldest",icon:Ck},{id:"name",label:"A→Z",icon:Ck},{id:"name-desc",label:"Z→A",icon:D$}],k=[{id:"all",label:"All Time"},{id:"today",label:"Today"},{id:"week",label:"This Week"},{id:"month",label:"This Month"}];return a.jsxs("div",{className:"flex-1 flex flex-col items-center px-4 pt-12 pb-8 overflow-y-auto relative z-10",children:[a.jsx("h1",{className:"text-2xl md:text-3xl font-bold text-foreground mb-2",children:n||"My Projects"}),a.jsxs("p",{className:"text-sm text-muted-foreground mb-8",children:[s||"All your projects in one place. Click to resume building.",a.jsxs("span",{className:"ml-2 text-muted-foreground/50",children:["(",e.length," total)"]})]}),a.jsxs("div",{className:"w-full max-w-4xl flex flex-col sm:flex-row items-stretch sm:items-center gap-3 mb-6",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(Cn,{value:l,onChange:N=>c(N.target.value),placeholder:"Search by name, description, or ID...",className:"pl-9"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex items-center gap-0.5 bg-card border rounded-lg p-1",children:k.map(N=>a.jsx("button",{onClick:()=>h(N.id),className:L("px-2.5 py-1.5 rounded-md text-xs font-medium transition-all whitespace-nowrap",p===N.id?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground"),children:N.label},N.id))}),a.jsx("div",{className:"flex items-center gap-0.5 bg-card border rounded-lg p-1",children:v.map(N=>a.jsxs("button",{onClick:()=>d(N.id),className:L("flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium transition-all whitespace-nowrap",u===N.id?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground"),children:[a.jsx(N.icon,{className:"w-3 h-3"}),N.label]},N.id))})]})]}),a.jsxs("div",{className:"w-full max-w-4xl grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[b.length===0&&a.jsxs("div",{className:"col-span-3 text-center py-20",children:[a.jsx(cc,{className:"w-12 h-12 text-muted-foreground
8248/20 mx-auto mb-3"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:l||p!=="all"?"No projects match your filters":i||"No projects yet — go build something!"}),!l&&p==="all"&&o&&a.jsx("p",{className:"text-xs text-muted-foreground mt-1.5 max-w-sm mx-auto",children:o})]}),b.map(N=>a.jsx(jbe,{project:N,onSelect:()=>t(N.id),onDelete:()=>r(N.id),onDescriptionGenerated:g},N.id))]})]})}const P_="sj_welcome_dismissed_v1";function Nbe({hasProjects:e,className:t}){const{balance:r,plan:n}=ld(),[s,i]=m.useState(()=>typeof window<"u"&&localStorage.getItem(P_)==="1");if(e||s||!n)return null;const o=()=>{localStorage.setItem(P_,"1"),i(!0)};return a.jsxs("div",{className:L("rounded-2xl border bg-gradient-to-br from-primary/5 via-primary/3 to-transparent overflow-hidden relative",t),children:[a.jsx("button",{type:"button",onClick:o,className:"absolute top-2.5 right-2.5 w-7 h-7 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center transition-colors","aria-label":"Dismiss welcome",children:a.jsx(qn,{className:"w-3.5 h-3.5"})}),a.jsxs("div",{className:"p-4 sm:p-5 flex items-start gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/15 flex items-center justify-center shrink-0",children:a.jsx(Dn,{className:"w-5 h-5 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0 pr-8",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[a.jsx("h3",{className:"text-sm font-bold text-foreground",children:"Welcome to Studio Jungle"}),a.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] uppercase tracking-wider font-bold px-1.5 py-0.5 rounded bg-primary/10 text-primary",children:[a.jsx(hr,{className:"w-2.5 h-2.5"}),r," credit",r===1?"":"s"," · ",n]})]}),a.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed max-w-2xl",children:["You're on the ",a.jsx("strong",{className:"text-foreground capitalize",children:n})," plan with"," ",a.jsxs("strong",{className:"text-foreground",children:[r," credits"]})," ready to spend. Pick a starter prompt below or describe your own idea — the AI ships a working app in seconds."]})]})]})]})}const kbe="https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/workflow-api";async function _a(e,t={}){try{const{data:{session:r}}=await G.auth.getSession(),n=r==null?void 0:r.access_token;if(!n)return console.warn("No auth session for workflow API"),null;const s=await fetch(`${kbe}${e}`,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo",...t.headers||{}}});if(!s.ok){const i=await s.json().catch(()=>({error:s.statusText}));return console.error(`workflow-api ${e}:`,i),null}return await s.json()}catch(r){return console.error(`workflow-api fetch failed ${e}:`,r),null}}function Do(e){return{id:e.id,project_id:e.project_id,name:e.name,description:e.description,status:e.status,version:e.version,trigger_type:e.trigger_type,published:e.published,published_url:e.published_url,created_at:e.created_at,updated_at:e.updated_at,runs_count:e.runs_count,nodes:(e.nodes||[]).map(t=>({id:t.id,workflow_id:t.workflow_id,type:t.type,label:t.label,description:t.description,config:t.config,position_x:t.position_x,position_y:t.position_y})),edges:(e.edges||[]).map(t=>({id:t.id,workflow_id:t.workflow_id,source_node_id:t.source_node_id,target_node_id:t.target_node_id,source_handle:t.source_handle,condition_label:t.condition_label}))}}function Ub(e){return{id:e.id,workflow_id:e.workflow_id,workflow_name:e.workflow_name,status:e.status,trigger_payload:e.trigger_payload,started_at:e.started_at,completed_at:e.completed_at,duration_ms:e.duration_ms,output_summary:e.output_summary,channel:e.channel,steps:(e.steps||[]).map(t=>({id:t.id,run_id:t.run_id,node_id:t.node_id||"",node_type:t.node_type,node_label:t.node_label,status:t.status,input_data:t.input_data,output_data:t.output_data,error_message:t.error_message,started_at:t.started_at,completed_at:t.completed_at,duration_ms:t.duration_ms}))}}const ho=()=>crypto.randomUUID().slice(0,8),mm=[{id:"wf_"+ho(),project_id:crypto.randomUUID(),name:"Cleaning Booking Bot",description:"Collects address, preferred date and confirms booking for cleaning services.",status:"published",version:3,trigger_type:"user_message",published:!0,published_url:"https://bot.pointspay.io/cleaning-booking",created_at:"2026-03-01T10:00:00Z",updated_at:"2026-03-10T14:30:00Z",runs_count:247,nodes:[{id:"n1",workflow_id:"",type:"user_message",label:"User Message",description:"Entry point",config:{},position_x:100,position_y:100},{id:"n2",workflow_id:"",type:"intent_detection",label:"Detect Intent",description:"Classify user intent",config:{intents:["book_cleaning","price_query","supp
8248ort"]},position_x:100,position_y:250},{id:"n3",workflow_id:"",type:"condition",label:"Route Intent",description:"Branch on intent",config:{rules:[{if:"intent == 'book_cleaning'",go_to:"n4"},{if:"intent == 'price_query'",go_to:"n5"}]},position_x:100,position_y:400},{id:"n4",workflow_id:"",type:"collect_input",label:"Collect Address",description:"Ask for cleaning address",config:{field:"address",question:"What is the address for cleaning?",validation:"text",required:!0},position_x:-100,position_y:550},{id:"n5",workflow_id:"",type:"send_message",label:"Send Pricing",description:"Reply with pricing info",config:{text:"Our prices start at $50/hour. Would you like to book?"},position_x:300,position_y:550},{id:"n6",workflow_id:"",type:"save_lead",label:"Save Lead",description:"Store booking in DB",config:{destination:"leads",fields:["name","address","date"]},position_x:-100,position_y:700},{id:"n7",workflow_id:"",type:"send_message",label:"Confirm Booking",description:"Send confirmation",config:{text:"Your cleaning is booked! We'll see you on {{date}}."},position_x:-100,position_y:850}],edges:[{id:"e1",workflow_id:"",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",workflow_id:"",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",workflow_id:"",source_node_id:"n3",target_node_id:"n4",source_handle:"true",condition_label:"book_cleaning"},{id:"e4",workflow_id:"",source_node_id:"n3",target_node_id:"n5",source_handle:"false",condition_label:"price_query"},{id:"e5",workflow_id:"",source_node_id:"n4",target_node_id:"n6",source_handle:"default",condition_label:""},{id:"e6",workflow_id:"",source_node_id:"n6",target_node_id:"n7",source_handle:"default",condition_label:""}]},{id:"wf_"+ho(),project_id:crypto.randomUUID(),name:"FAQ Assistant",description:"Answers frequently asked questions using knowledge base search.",status:"published",version:2,trigger_type:"user_message",published:!0,published_url:"https://bot.pointspay.io/faq",created_at:"2026-02-15T09:00:00Z",updated_at:"2026-03-08T11:20:00Z",runs_count:1024,nodes:[{id:"n1",workflow_id:"",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",workflow_id:"",type:"knowledge_search",label:"Search FAQ",description:"Search knowledge base",config:{source:"faq_db",top_k:3},position_x:100,position_y:250},{id:"n3",workflow_id:"",type:"ai_reply",label:"Generate Answer",description:"AI generates response from context",config:{prompt:"Answer based on FAQ context",temperature:.3},position_x:100,position_y:400},{id:"n4",workflow_id:"",type:"send_message",label:"Reply",description:"Send answer to user",config:{text:"{{ai_response}}"},position_x:100,position_y:550}],edges:[{id:"e1",workflow_id:"",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",workflow_id:"",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",workflow_id:"",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""}]},{id:"wf_"+ho(),project_id:crypto.randomUUID(),name:"Customer Support Triage",description:"Routes support requests by category and escalates complex issues to humans.",status:"draft",version:1,trigger_type:"user_message",published:!1,published_url:null,created_at:"2026-03-09T16:00:00Z",updated_at:"2026-03-10T09:15:00Z",runs_count:12,nodes:[{id:"n1",workflow_id:"",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",workflow_id:"",type:"intent_detection",label:"Classify Issue",description:"Detect support category",config:{intents:["billing","technical","general","urgent"]},position_x:100,position_y:250},{id:"n3",workflow_id:"",type:"condition",label:"Is Urgent?",description:"Check urgency",config:{rules:[{if:"intent == 'urgent'",go_to:"n5"}],default_go_to:"n4"},position_x:100,position_y:400},{id:"n4",workflow_id:"",type:"ai_reply",label:"Auto Response",description:"Generate auto reply",config:{prompt:"Respond helpfully to the support request"},position_x:-50,position_y:550},{id:"n5",workflow_id:"",type:"human_handoff",label:"Escalate",description:"Hand off to agent",config:{team:"support-urgent"},position_x:250,position_y:550},{id:"n6",workflow_id:"",type:"create_ticket",label:"Create Ticket",description:"Log in ticketing system",config:{system:"internal"},position_x:100,position_y:700}],edges:[{id:"e1",workflow_id:"",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",workflow_id:"",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",workflow_id:"",source_node_id:"n3",target_node_id:"n4",source_handle:"false",condition_label:"Not urgent"},{id:"e4",workflow_id:"",source_node_id:"n3",target_node_id:"n5",source_handle:"true",condition_label:"Urgent"},{id:"e5",workflow_id:"",source_node_id:"n4",target_node_id:"n6",source_handle:"default",condition_label:""},{id:"e6",workflow_id:"",source_node_id:"n5",target_node_id:"n6",source_handle:"default",condition_label:""}]}],Sbe=[{id:"run_"+ho(),workflow_id:mm[0].id,workflow_name:"Cleaning Booking Bot",status:"completed",trigger_payload:'{"message": "I want to book a cleaning"}',started_at:"2026-03-10T14:00:00Z",completed_at:"2026-03-10T14:00:03Z",duration_ms:3200,output_summary:"Booking confirmed for March 15",channel:"Website",steps:[{id:"s1",run_id:"",node_id:"n1",node_type:"user_message",node_label:"User Message",status:"success",input_data:'"I want to book a cleaning"',output_data:'"message received"',error_message:null,started_at:"2026-03-10T14:00:00Z",completed_at:"2026-03-10T14:00:00Z",duration_ms:50},{id:"s2",run_id:"",node_id:"n2",node_type:"intent_detection",node_label:"Detect Intent",status:"success",input_data:'"I want to book a cleaning"',output_data:'{"intent": "book_cleaning", "confidence": 0.95}',error_message:null,started_at:"2026-03-10T14:00:00Z",completed_at:"2026-03-10T14:00:01Z",duration_ms:800},{id:"s3",run_id:"",node_id:"n3",node_type:"condition",node_label:"Route Intent",status:"success",input_data:'{"intent": "book_cleaning"}',output_data:'{"branch": "book_cleaning", "next": "n4"}',error_message:null,started_at:"2026-03-10T14:00:01Z",completed_at:"2026-03-10T14:00:01Z",duration_ms:20},{id:"s4",run_id:"",node_id:"n4",node_type:"collect_input",node_label:"Collect Address",status:"success",input_data:"{}",output_data:'{"address": "123 Main St"}',error_message:null,started_at:"2026-03-10T14:00:01Z",completed_at:"2026-03-10T14:00:02Z",duration_ms:1500},{id:"s5",run_id:"",node_id:"n6",node_type:"save_lead",node_label:"Save Lead",status:"success",input_data:'{"address": "123 Main St", "date": "March 15"}',output_data:'{"lead_id": "ld_abc123"}',error_message:null,started_at:"2026-03-10T14:00:02Z",completed_at:"2026-03-10T14:00:03Z",duration_ms:600},{id:"s6",run_id:"",node_id:"n7",node_type:"send_message",node_label:"Confirm Booking",status:"success",input_data:"{}
8248",output_data:'"Message sent"',error_message:null,started_at:"2026-03-10T14:00:03Z",completed_at:"2026-03-10T14:00:03Z",duration_ms:200}]},{id:"run_"+ho(),workflow_id:mm[0].id,workflow_name:"Cleaning Booking Bot",status:"failed",trigger_payload:'{"message": "Clean my place"}',started_at:"2026-03-09T11:30:00Z",completed_at:"2026-03-09T11:30:02Z",duration_ms:2100,output_summary:"Failed at API call — timeout",channel:"API",steps:[{id:"s1",run_id:"",node_id:"n1",node_type:"user_message",node_label:"User Message",status:"success",input_data:'"Clean my place"',output_data:'"received"',error_message:null,started_at:"2026-03-09T11:30:00Z",completed_at:"2026-03-09T11:30:00Z",duration_ms:40},{id:"s2",run_id:"",node_id:"n2",node_type:"intent_detection",node_label:"Detect Intent",status:"success",input_data:'"Clean my place"',output_data:'{"intent": "book_cleaning"}',error_message:null,started_at:"2026-03-09T11:30:00Z",completed_at:"2026-03-09T11:30:01Z",duration_ms:900},{id:"s3",run_id:"",node_id:"n6",node_type:"save_lead",node_label:"Save Lead",status:"failed",input_data:"{}",output_data:"",error_message:"Connection timeout after 5000ms",started_at:"2026-03-09T11:30:01Z",completed_at:"2026-03-09T11:30:02Z",duration_ms:1100}]},{id:"run_"+ho(),workflow_id:mm[1].id,workflow_name:"FAQ Assistant",status:"completed",trigger_payload:'{"message": "What are your hours?"}',started_at:"2026-03-10T09:15:00Z",completed_at:"2026-03-10T09:15:02Z",duration_ms:1800,output_summary:"Answered: Business hours are Mon-Fri 9am-5pm",channel:"Website",steps:[{id:"s1",run_id:"",node_id:"n1",node_type:"user_message",node_label:"User Message",status:"success",input_data:'"What are your hours?"',output_data:'"received"',error_message:null,started_at:"2026-03-10T09:15:00Z",completed_at:"2026-03-10T09:15:00Z",duration_ms:30},{id:"s2",run_id:"",node_id:"n2",node_type:"knowledge_search",node_label:"Search FAQ",status:"success",input_data:'"What are your hours?"',output_data:'{"results": 3}',error_message:null,started_at:"2026-03-10T09:15:00Z",completed_at:"2026-03-10T09:15:01Z",duration_ms:600},{id:"s3",run_id:"",node_id:"n3",node_type:"ai_reply",node_label:"Generate Answer",status:"success",input_data:'{"context": "Business hours FAQ"}',output_data:'"Mon-Fri 9am-5pm"',error_message:null,started_at:"2026-03-10T09:15:01Z",completed_at:"2026-03-10T09:15:02Z",duration_ms:1e3},{id:"s4",run_id:"",node_id:"n4",node_type:"send_message",node_label:"Reply",status:"success",input_data:'"Mon-Fri 9am-5pm"',output_data:'"sent"',error_message:null,started_at:"2026-03-10T09:15:02Z",completed_at:"2026-03-10T09:15:02Z",duration_ms:150}]}],A_=[{id:"tpl_lead",name:"Lead Qualification",description:"Qualify leads with smart questions and scoring",icon:"🎯",category:"Sales",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"collect_input",label:"Ask Company",description:"",config:{field:"company",question:"What company are you from?"},position_x:100,position_y:250},{id:"n3",type:"collect_input",label:"Ask Budget",description:"",config:{field:"budget",question:"What is your budget range?"},position_x:100,position_y:400},{id:"n4",type:"save_lead",label:"Save Lead",description:"",config:{},position_x:100,position_y:550}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""}]},{id:"tpl_support",name:"Customer Support",description:"Triage and respond to support requests automatically",icon:"🛟",category:"Support",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"intent_detection",label:"Classify Issue",description:"",config:{intents:["billing","technical","general"]},position_x:100,position_y:250},{id:"n3",type:"condition",label:"Is Urgent?",description:"",config:{rules:[{if:"intent == 'urgent'",go_to:"escalate"}]},position_x:100,position_y:400}
8248,{id:"n4",type:"ai_reply",label:"Auto Response",description:"",config:{prompt:"Respond helpfully to the support request"},position_x:-50,position_y:550},{id:"n5",type:"human_handoff",label:"Escalate",description:"",config:{team:"support"},position_x:250,position_y:550}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"false",condition_label:"Not urgent"},{id:"e4",source_node_id:"n3",target_node_id:"n5",source_handle:"true",condition_label:"Urgent"}]},{id:"tpl_booking",name:"Appointment Booking",description:"Collect details and book appointments seamlessly",icon:"📅",category:"Operations",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"collect_input",label:"Ask Service",description:"",config:{field:"service",question:"What service would you like to book?"},position_x:100,position_y:250},{id:"n3",type:"collect_input",label:"Ask Date",description:"",config:{field:"date",question:"What date works for you?"},position_x:100,position_y:400},{id:"n4",type:"collect_input",label:"Ask Time",description:"",config:{field:"time",question:"What time do you prefer?"},position_x:100,position_y:550},{id:"n5",type:"book_appointment",label:"Book It",description:"",config:{},position_x:100,position_y:700},{id:"n6",type:"send_message",label:"Confirm",description:"",config:{text:"Your appointment is booked for {{date}} at {{time}}!"},position_x:100,position_y:850}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""},{id:"e4",source_node_id:"n4",target_node_id:"n5",source_handle:"default",condition_label:""},{id:"e5",source_node_id:"n5",target_node_id:"n6",source_handle:"default",condition_label:""}]},{id:"tpl_faq",name:"FAQ Assistant",description:"Answer common questions from your knowledge base",icon:"❓",category:"Support",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"knowledge_search",label:"Search FAQ",description:"",config:{source:"faq_db",top_k:3},position_x:100,position_y:250},{id:"n3",type:"ai_reply",label:"Generate Answer",description:"",config:{prompt:"Answer based on FAQ context"},position_x:100,position_y:400},{id:"n4",type:"send_message",label:"Reply",description:"",config:{text:"{{ai_response}}"},position_x:100,position_y:550}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""}]},{id:"tpl_sales",name:"Sales Assistant",description:"Guide prospects through your offerings",icon:"💼",category:"Sales",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"intent_detection",label:"Detect Interest",description:"",config:{intents:["pricing","demo","features"]},position_x:100,position_y:250},{id:"n3",type:"ai_reply",label:"Sales Pitch",description:"",config:{prompt:"Present relevant product info based on user interest"},position_x:100,position_y:400},{id:"n4",type:"collect_input",label:"Ask Email",description:"",config:{field:"email",question:"Want to learn more? Share your email!"},position_x:100,position_y:550},{id:"n5",type:"save_lead",label:"Save Lead",description:"",config:{},position_x:100,position_y:700}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""},{id:"e4",source_node_id:"n4",target_node_id:"n5",source_handle:"default",condition_label:""}]},{id:"tpl_cleaning",name:"Cleaning Booking",description:"Book cleaning services with date and address collection",icon:"🧹",category:"Operations",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"collect_input",label:"Ask Address",description:"",config:{field:"address",question:"What is the address for cleaning?"},position_x:100,position_y:250},{id:"n3",type:"collect_input",label:"Ask Date",description:"",config:{field:"date",question:"When would you like the cleaning?"},position_x:100,position_y:400},{id:"n4",type:"save_lead",label:"Save Booking",description:"",config:{fields:["address","date"]},position_x:100,position_y:550},{id:"n5",type:"send_message",label:"Confirm",description:"",config:{text:"Cleaning booked at {{address}} on {{date}}!"},position_x:100,position_y:700}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""},{id:"e4",source_node_id:"n4",target_node_id:"n5",source_handle:"default",condition_label:""}]},{id:"tpl_restaurant",name:"Restaurant Reservation",description:"Take restaurant reservations via chat",icon:"🍽️",category:"Operations",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"collect_input",label:"Ask Party Size",description:"",config:{field:"party_size",question:"How many guests?"},position_x:100,position_y:250},{id:"n3",type:"collect_input",label:"Ask Date",description:"",config:{field:"date",question:"What date?"},position_x:100,position_y:400},{id:"n4",type:"collect_input",label:"Ask Time",description:"",config:{field:"time",question:"What time?"},position_x:100,position_y:550},{id:"n5",type:"book_appointment",label:"Reserve Table",description:"",config:{},position_x:100,position_y:700},{id:"n6",type:"send_message",label:"Confirm",description:"",config:{text:"Table for {{party_size}} booked on {{date}} at {{time}}!"},position_x:100,position_y:850}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""},{id:"e4",source_node_id:"n4",target_node_id:"n5",source_handle:"default",condition_label:""},{id:"e5",source_node_id:"n5",target_node_id:"n6",source_handle:"default",condition_label:""}]},{id:"tpl_handoff",name:"Human Handoff Support",description:"Auto-respond then escalate to human when needed",icon:"👤",category:"Support",nodes:[{id:"n1",type:"user_message",label:"User Message",description:"",config:{},position_x:100,position_y:100},{id:"n2",type:"ai_reply",label:"Auto Reply",description:"",config:{prompt:"Try to answer the support question"},position_x:100,position_y:250}
8248,{id:"n3",type:"collect_input",label:"Ask Satisfied",description:"",config:{field:"satisfied",question:"Did that answer your question? (yes/no)"},position_x:100,position_y:400},{id:"n4",type:"condition",label:"Check Answer",description:"",config:{rules:[{if:"satisfied == 'no'",go_to:"handoff"}]},position_x:100,position_y:550},{id:"n5",type:"send_message",label:"Close",description:"",config:{text:"Glad I could help! Have a great day."},position_x:-50,position_y:700},{id:"n6",type:"human_handoff",label:"Handoff",description:"",config:{team:"support"},position_x:250,position_y:700}],edges:[{id:"e1",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""},{id:"e4",source_node_id:"n4",target_node_id:"n5",source_handle:"false",condition_label:"Satisfied"},{id:"e5",source_node_id:"n4",target_node_id:"n6",source_handle:"true",condition_label:"Not satisfied"}]}];let Ur=[...mm],Yf=[...Sbe];function wi(e){return new Promise(t=>setTimeout(t,e))}const ra={listFlows:async e=>{const t=new URLSearchParams;e&&t.set("status",e);const r=await _a(`/flows?${t}`);return r?r.data.map(Do):(await wi(200),e?Ur.filter(n=>n.status===e):[...Ur])},getFlow:async e=>{const t=await _a(`/flows/${e}`);return t?Do(t):(await wi(100),Ur.find(r=>r.id===e)||null)},createFlow:async e=>{var s,i;const t={project_id:e.project_id||crypto.randomUUID(),name:e.name||"Untitled Flow",description:e.description,trigger_type:e.trigger_type||"user_message",nodes:(s=e.nodes)==null?void 0:s.map(o=>({id:o.id,type:o.type,label:o.label,description:o.description,config:o.config,position_x:o.position_x,position_y:o.position_y})),edges:(i=e.edges)==null?void 0:i.map(o=>({source_node_id:o.source_node_id,target_node_id:o.target_node_id,source_handle:o.source_handle,condition_label:o.condition_label}))},r=await _a("/flows",{method:"POST",body:JSON.stringify(t)});if(r)return Do(r);await wi(300);const n={id:"wf_"+ho(),project_id:e.project_id||crypto.randomUUID(),name:e.name||"Untitled Flow",description:e.description||"",status:"draft",version:1,trigger_type:e.trigger_type||"user_message",published:!1,published_url:null,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),runs_count:0,nodes:e.nodes||[{id:"n1",workflow_id:"",type:"user_message",label:"User Message",description:"Entry point",config:{},position_x:100,position_y:100}],edges:e.edges||[]};return Ur=[n,...Ur],n},updateFlow:async(e,t)=>{const r={};t.name!==void 0&&(r.name=t.name),t.description!==void 0&&(r.description=t.description),t.status!==void 0&&(r.status=t.status),t.trigger_type!==void 0&&(r.trigger_type=t.trigger_type);const n=await _a(`/flows/${e}`,{method:"PATCH",body:JSON.stringify(r)});if(n)return Do(n);await wi(200);const s=Ur.findIndex(i=>i.id===e);return s===-1?null:(Ur[s]={...Ur[s],...t,updated_at:new Date().toISOString()},Ur[s])},deleteFlow:async e=>{await _a(`/flows/${e}`,{method:"DELETE"}),Ur=Ur.filter(t=>t.id!==e)},publishFlow:async e=>{const t=await _a(`/flows/${e}/publish`,{method:"POST",body:"{}"});if(t)return Do(t.flow);await wi(500);const r=Ur.findIndex(n=>n.id===e);return r===-1?null:(Ur[r]={...Ur[r],status:"published",published:!0,published_url:`https://bot.pointspay.io/${Ur[r].name.toLowerCase().replace(/\s+/g,"-")}`,updated_at:new Date().toISOString()},Ur[r])},unpublishFlow:async e=>{const t=await _a(`/flows/${e}/unpublish`,{method:"POST",body:"{}"});if(t)return Do(t);await wi(300);const r=Ur.findIndex(n=>n.id===e);return r===-1?null:(Ur[r]={...Ur[r],status:"draft",published:!1,published_url:null,updated_at:new Date().toISOString()},Ur[r])},duplicateFlow:async e=>{const t=await _a(`/flows/${e}/duplicate`,{method:"POST"});if(t)return Do(t);await wi(300);const r=Ur.find(s=>s.id===e);if(!r)return null;const n={...r,id:"wf_"+ho(),name:r.name+" (Copy)",status:"draft",published:!1,published_url:null,runs_count:0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return Ur=[n,...Ur],n}
8248,listRuns:async(e,t)=>{const r=new URLSearchParams;e&&r.set("workflow_id",e),t&&r.set("status",t);const n=await _a(`/runs?${r}`);if(n)return n.data.map(Ub);await wi(200);let s=[...Yf];return e&&(s=s.filter(i=>i.workflow_id===e)),t&&(s=s.filter(i=>i.status===t)),s},getRun:async e=>{const t=await _a(`/runs/${e}`);return t?Ub(t):(await wi(100),Yf.find(r=>r.id===e)||null)},testFlow:async(e,t)=>{const r={message:t,channel:"test"},n=await _a(`/flows/${e.id}/test`,{method:"POST",body:JSON.stringify(r)});if(n)return Ub(n.run);await wi(1200);const s={id:"run_"+ho(),workflow_id:e.id,workflow_name:e.name,status:"completed",trigger_payload:JSON.stringify({message:t}),started_at:new Date().toISOString(),completed_at:new Date().toISOString(),duration_ms:1200,output_summary:`Processed: "${t}"`,channel:"Test",steps:e.nodes.slice(0,4).map((i,o)=>({id:"s"+o,run_id:"",node_id:i.id,node_type:i.type,node_label:i.label,status:"success",input_data:o===0?`"${t}"`:"{}",output_data:'"ok"',error_message:null,started_at:new Date().toISOString(),completed_at:new Date().toISOString(),duration_ms:200+o*100}))};return Yf=[s,...Yf],s},saveFullFlow:async(e,t)=>{const r=await _a(`/flows/${e}/save-full`,{method:"POST",body:JSON.stringify(t)});return r?Do(r):null}};function Cbe({onClose:e,onCreated:t}){const{project:r}=gn(),n=r==null?void 0:r.id,[s,i]=m.useState("blank"),[o,l]=m.useState(""),[c,u]=m.useState(""),[d,p]=m.useState(!1),h=async()=>{p(!0);const b=await ra.createFlow({name:o.trim()||"Untitled Chat Flow",project_id:n||""});t(b)},f=async()=>{if(!c.trim())return;p(!0);const b=await ra.createFlow({name:c.slice(0,40),description:c,project_id:n||"",nodes:[{id:"n1",workflow_id:"",type:"user_message",label:"User Message",description:"Entry",config:{},position_x:100,position_y:100},{id:"n2",workflow_id:"",type:"intent_detection",label:"Detect Intent",description:"AI-generated",config:{intents:["main_intent","fallback"]},position_x:100,position_y:250},{id:"n3",workflow_id:"",type:"ai_reply",label:"AI Response",description:"Generated response",config:{prompt:c},position_x:100,position_y:400},{id:"n4",workflow_id:"",type:"send_message",label:"Reply",description:"Send to user",config:{text:"{{ai_response}}"},position_x:100,position_y:550}],edges:[{id:"e1",workflow_id:"",source_node_id:"n1",target_node_id:"n2",source_handle:"default",condition_label:""},{id:"e2",workflow_id:"",source_node_id:"n2",target_node_id:"n3",source_handle:"default",condition_label:""},{id:"e3",workflow_id:"",source_node_id:"n3",target_node_id:"n4",source_handle:"default",condition_label:""}]});t(b)},x=async b=>{p(!0);const v=A_.find(N=>N.id===b);if(!v)return;const k=await ra.createFlow({name:v.name,description:v.description,project_id:n||"",nodes:v.nodes.map(N=>({...N,workflow_id:""})),edges:v.edges.map(N=>({...N,workflow_id:""}))});t(k)},g=["Create a chatbot that books cleaning services, collects address and date, then confirms.","Build a lead qualification flow that asks company size, budget, and timeline.","Make a customer support bot that triages issues and escalates urgent ones."],y=[{id:"blank",label:"Start Blank",icon:Kr},{id:"ai",label:"Generate with AI",icon:Dn},{id:"template",label:"Use Template",icon:Wg}];return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",onClick:e,children:a.jsxs("div",{className:"bg-card border rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] overflow-hidden",onClick:b=>b.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[a.jsx("h2",{className:"text-lg font-bold text-foreground",children:"Create Chat Flow"}),a.jsx("button",{onClick:e,className:"text-muted-foreground hover:text-foreground transition-colors",children:a.jsx(qn,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex items-center gap-1 px-6 pt-4",children:y.map(b=>a.jsxs("button",{onClick:()=>i(b.id),className:L("flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all",s===b.id?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-secondary"),children:[a.jsx(b.
8248icon,{className:"w-4 h-4"}),b.label]},b.id))}),a.jsxs("div",{className:"p-6 overflow-y-auto max-h-[60vh]",children:[s==="blank"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm font-medium text-foreground mb-1.5 block",children:"Flow Name"}),a.jsx("input",{value:o,onChange:b=>l(b.target.value),placeholder:"My Chat Flow",className:"w-full px-3 py-2 border rounded-lg bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Creates an empty flow with a User Message trigger node. You can add more nodes in the builder."}),a.jsxs(Q,{onClick:h,disabled:d,className:"gap-1.5",children:[d?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(Sh,{className:"w-4 h-4"}),"Create Flow"]})]}),s==="ai"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm font-medium text-foreground mb-1.5 block",children:"Describe the workflow you want to create"}),a.jsx("textarea",{value:c,onChange:b=>u(b.target.value),placeholder:"Create a chatbot that books cleaning services, collects the address and preferred date, then saves the lead and offers confirmation.",rows:4,className:"w-full px-3 py-2 border rounded-lg bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 resize-none"})]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:g.map((b,v)=>a.jsxs("button",{onClick:()=>u(b),className:"text-[11px] px-3 py-1.5 rounded-full bg-secondary text-muted-foreground hover:text-foreground transition-colors",children:[b.slice(0,50),"..."]},v))}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"AI will generate a draft flow that you can customize in the builder."}),a.jsxs(Q,{onClick:f,disabled:d||!c.trim(),className:"gap-1.5",children:[d?a.jsx(ze,{className:"w-4 h-4 animate-spin"}):a.jsx(Dn,{className:"w-4 h-4"}),"Generate Flow"]})]}),s==="template"&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:A_.map(b=>a.jsxs("button",{onClick:()=>x(b.id),disabled:d,className:"text-left bg-background border rounded-xl p-4 hover:border-primary/30 hover:shadow-sm transition-all",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-lg",children:b.icon}),a.jsx("h4",{className:"font-semibold text-sm text-foreground",children:b.name})]}),a.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:b.description}),a.jsx("span",{className:"inline-block mt-2 text-[10px] px-2 py-0.5 rounded-full bg-secondary text-muted-foreground",children:b.category})]},b.id))})]})]})})}const Qo=[{type:"user_message",label:"User Message",description:"Triggered when user sends a message",category:"Triggers",icon:"💬"},{type:"webhook",label:"Webhook",description:"Triggered by external HTTP request",category:"Triggers",icon:"🔗"},{type:"schedule",label:"Schedule",description:"Triggered on a time schedule",category:"Triggers",icon:"⏰"},{type:"intent_detection",label:"Intent Detection",description:"Detect user intent using AI",category:"AI",icon:"🎯"},{type:"ai_reply",label:"AI Reply",description:"Generate AI-powered response",category:"AI",icon:"🤖"},{type:"knowledge_search",label:"Knowledge Search",description:"Search knowledge base for context",category:"AI",icon:"📚"},{type:"summarize_context",label:"Summarize Context",description:"Summarize conversation context",category:"AI",icon:"📝"},{type:"condition",label:"Condition",description:"Branch based on rules",category:"Logic",icon:"🔀"},{type:"router",label:"Router",description:"Route to multiple paths",category:"Logic",icon:"🔄"},{type:"wait",label:"Wait",description:"Pause execution for a delay",category:"Logic",icon:"⏳"},{type:"fallback",label:"Fallback",description:"Handle unmatched inputs",category:"Logic",icon:"🔙"},{type:"send_message",label:"Send Message",description:"Send a message to the user",category:"Actions",icon:"📤"},{type:"save_lead",label:"Save Lead",description:"Save lead to database",category:"Actions",icon:"💾"},{type:"api_call",label:"API Call",description:"Call an external API",category:"Actions",icon:"🌐"},{type:"create_ticket",label:"Create Ticket",description:"Create a support ticket",category:"Actions",icon:"🎫"},{type:"book_appointment",label:"Book Appointment",description:"Schedule an appointment",category:"Actions",icon:"📅"},{type:"human_handoff",label:"Human Handoff",description:"Transfer to human agent",category:"Actions",icon:"👤"},{type:"send_email",label:"Send Email",description:"Send an email notification",category:"Actions",icon:"📧"},{type:"collect_input",label:"Collect Input",description:"Ask user for specific information",category:"Data",icon:"📋"}
8248,{type:"set_variable",label:"Set Variable",description:"Set a flow variable",category:"Data",icon:"📌"},{type:"update_variable",label:"Update Variable",description:"Update an existing variable",category:"Data",icon:"🔧"},{type:"tool_schema_builder",label:"Schema Builder",description:"Create/modify database schema via Studio tool",category:"Tools",icon:"🗂️",toolId:"schema-builder"},{type:"tool_query_runner",label:"Query Runner",description:"Execute SQL queries via Studio tool",category:"Tools",icon:"⚡",toolId:"query-optimizer"},{type:"tool_edge_function",label:"Edge Function",description:"Deploy/invoke edge functions via Studio tool",category:"Tools",icon:"⚡",toolId:"edge-fn-gen"},{type:"tool_connector_slack",label:"Slack",description:"Send Slack messages via connector",category:"Tools",icon:"💬",toolId:"connector-slack"},{type:"tool_connector_email",label:"Send Email",description:"Send emails via connector",category:"Tools",icon:"📧",toolId:"connector-email"},{type:"tool_connector_stripe",label:"Stripe Payment",description:"Process payment via Stripe connector",category:"Tools",icon:"💳",toolId:"connector-stripe"}];function Pbe({nodes:e,edges:t,selectedNodeId:r,onSelectNode:n,onDeleteNode:s,onMoveNode:i}){const[o,l]=m.useState(1),[c,u]=m.useState({x:0,y:0}),[d,p]=m.useState(null),[h,f]=m.useState(null),x=m.useRef(null),g=C=>{var A;return((A=Qo.find(P=>P.type===C))==null?void 0:A.icon)||"⚙️"},y=C=>{var P;const A=(P=Qo.find(E=>E.type===C))==null?void 0:P.category;return A==="Triggers"?"border-l-emerald-500":A==="AI"?"border-l-violet-500":A==="Logic"?"border-l-amber-500":A==="Actions"?"border-l-sky-500":A==="Data"?"border-l-rose-500":"border-l-border"},b=C=>{var P;const A=(P=Qo.find(E=>E.type===C))==null?void 0:P.category;return A==="Triggers"?"bg-emerald-500/5":A==="AI"?"bg-violet-500/5":A==="Logic"?"bg-amber-500/5":A==="Actions"?"bg-sky-500/5":A==="Data"?"bg-rose-500/5":""},v=224,k=72,N=m.useCallback((C,A)=>{C.stopPropagation(),C.preventDefault();const P=e.find(E=>E.id===A);P&&(n(A),p({nodeId:A,startX:C.clientX,startY:C.clientY,origX:P.position_x,origY:P.position_y}))},[e,n]),j=m.useCallback(C=>{(C.target===x.current||C.target.tagName==="svg")&&(n(null),f({startX:C.clientX,startY:C.clientY,origPanX:c.x,origPanY:c.y}))},[n,c]);m.useEffect(()=>{const C=P=>{if(d){const E=(P.clientX-d.startX)/o,_=(P.clientY-d.startY)/o;i==null||i(d.nodeId,d.origX+E,d.origY+_)}h&&u({x:h.origPanX+(P.clientX-h.startX),y:h.origPanY+(P.clientY-h.startY)})},A=()=>{p(null),f(null)};return window.addEventListener("mousemove",C),window.addEventListener("mouseup",A),()=>{window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",A)}},[d,h,o,i]);const w=m.useCallback(C=>{C.ctrlKey||C.metaKey?(C.preventDefault(),l(A=>Math.min(2,Math.max(.3,A-C.deltaY*.002)))):u(A=>({x:A.x-C.deltaX,y:A.y-C.deltaY}))},[]),S=m.useCallback(()=>{if(e.length===0)return;const C=Math.min(...e.map(K=>K.position_x)),A=Math.max(...e.map(K=>K.position_x))+v,P=Math.min(...e.map(K=>K.position_y)),E=Math.max(...e.map(K=>K.position_y))+k,_=x.current;if(!_)return;const I=_.clientWidth,D=_.clientHeight,M=(I-80)/(A-C),B=(D-80)/(E-P),$=Math.min(1.2,Math.max(.3,Math.min(M,B)));l($),u({x:(I-(A-C)*$)/2-C*$,y:(D-(E-P)*$)/2-P*$})},[e]),T=t.map(C=>{const A=e.find($=>$.id===C.source_node_id),P=e.find($=>$.id===C.target_node_id);if(!A||!P)return null;const E=A.position_x+v/2,_=A.position_y+k,I=P.position_x+v/2,D=P.position_y,M=Math.abs(D-_),B=Math.max(40,M*.4);return{...C,x1:E,y1:_,x2:I,y2:D,cp:B}}).filter(Boolean);return a.jsxs("div",{ref:x,className:"w-full h-full overflow-hidden relative select-none",style:{backgroundImage:"radial-gradient(circle, hsl(var(--border) / 0.5) 1px, transparent 1px)",backgroundSize:`${20*o}px ${20*o}px`,backgroundPosition:`${c.x}px ${c.y}px`,cursor:h?"grabbing":"grab"},onMouseDown:j,onWheel:w,children:[a.jsxs("div",{className:"absolute bottom-4 left-4 z-20 flex items-center gap-1 bg-card border rounded-lg p-1 shadow-sm",children:[a.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>l(C=>Math.min(2,C+.15)),children:a.jsx(CT,{className:"w-3.5 h-3.5"})}),a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground w-10 text-center",children:[Math.round(o*100),"%"]}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>l(C=>Math.max(.3,C-.15)),children:a.jsx(PT,{className:"w-3.5 h-3.5"})}),a.jsx("div",{className:"w-px h-5 bg-border mx-0.5"}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:S,children:a.jsx(xT,{className:"w-3.5 h-3.5"})})]}),a.jsxs("div",{className:"absolute top-3 right-3 z-20 text-[10px] text-muted-foreground
8248/60 bg-card/80 border rounded-md px-2 py-1",children:[e.length," nodes · ",t.length," edges"]}),a.jsxs("div",{style:{transform:`translate(${c.x}px, ${c.y}px) scale(${o})`,transformOrigin:"0 0",position:"absolute",top:0,left:0},children:[a.jsxs("svg",{className:"absolute inset-0 pointer-events-none",style:{width:3e3,height:3e3,overflow:"visible"},children:[a.jsx("defs",{children:a.jsx("marker",{id:"arrowhead",markerWidth:"8",markerHeight:"6",refX:"8",refY:"3",orient:"auto",children:a.jsx("polygon",{points:"0 0, 8 3, 0 6",fill:"hsl(var(--primary) / 0.4)"})})}),T.map(C=>a.jsxs("g",{children:[a.jsx("path",{d:`M ${C.x1} ${C.y1} C ${C.x1} ${C.y1+C.cp}, ${C.x2} ${C.y2-C.cp}, ${C.x2} ${C.y2}`,fill:"none",stroke:"hsl(var(--primary) / 0.25)",strokeWidth:"2",strokeDasharray:C.condition_label?"6 3":void 0,markerEnd:"url(#arrowhead)"}),C.condition_label&&a.jsx("foreignObject",{x:(C.x1+C.x2)/2-40,y:(C.y1+C.y2)/2-10,width:80,height:20,children:a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-card border text-muted-foreground whitespace-nowrap",children:C.condition_label})})})]},C.id))]}),e.map(C=>a.jsxs("div",{onMouseDown:A=>N(A,C.id),className:L("absolute bg-card border rounded-xl shadow-sm transition-shadow hover:shadow-md border-l-4 group",y(C.type),b(C.type),r===C.id&&"ring-2 ring-primary/30 shadow-lg",(d==null?void 0:d.nodeId)===C.id&&"shadow-xl opacity-90"),style:{left:C.position_x,top:C.position_y,width:v,cursor:(d==null?void 0:d.nodeId)===C.id?"grabbing":"grab"},children:[a.jsxs("div",{className:"p-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-base shrink-0",children:g(C.type)}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:C.label}),a.jsx("p",{className:"text-[10px] text-muted-foreground capitalize",children:C.type.replace(/_/g," ")})]}),a.jsx("button",{onMouseDown:A=>A.stopPropagation(),onClick:A=>{A.stopPropagation(),s(C.id)},className:"opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-all",children:a.jsx(oa,{className:"w-3 h-3"})})]}),C.description&&a.jsx("p",{className:"text-[10px] text-muted-foreground mt-1 line-clamp-1",children:C.description})]}),a.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-3 h-3 rounded-full bg-background border-2 border-primary/30 hover:border-primary transition-colors"}),a.jsx("div",{className:"absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-3 h-3 rounded-full bg-background border-2 border-primary/30 hover:border-primary transition-colors"})]},C.id))]})]})}const Abe=["Triggers","AI","Logic","Actions","Data","Tools"];function _be({onAddNode:e}){const[t,r]=m.useState(""),[n,s]=m.useState({}),i=t.trim()?Qo.filter(l=>l.label.toLowerCase().includes(t.toLowerCase())||l.description.toLowerCase().includes(t.toLowerCase())):Qo,o=l=>s(c=>({...c,[l]:!c[l]}));return a.jsxs("div",{className:"p-2 space-y-1",children:[a.jsxs("div",{className:"relative mb-2",children:[a.jsx(ja,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground"}),a.jsx("input",{value:t,onChange:l=>r(l.target.value),placeholder:"Search nodes...",className:"w-full pl-8 pr-3 py-1.5 text-xs border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary/20"})]}),Abe.map(l=>{const c=i.filter(d=>d.category===l);if(c.length===0)return null;const u=n[l];return a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>o(l),className:"w-full flex items-center gap-1.5 px-2 py-1.5 text-[11px] font-semibold text-muted-foreground uppercase tracking-wider hover:text-foreground transition-colors",children:[u?a.jsx(ia,{className:"w-3 h-3"}):a.jsx(Yr,{className:"w-3 h-3"}),l,a.jsx("span",{className:"text-[10px] font-normal ml-auto",children:c.length})]}),!u&&a.jsx("div",{className:"space-y-0.5 ml-1",children:c.map(d=>a.jsxs("button",{onClick:()=>e(d.type),className:"w-full flex items-start gap-2 px-2 py-2 rounded-lg text-left hover:bg-secondary transition-colors group",children:[a.jsx("span",{className:"text-sm shrink-0 mt-0.5",children:d.icon}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-xs font-medium text-foreground",children:d.label}),a.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-1",children:d.description})]})]},d.type))})]},l)})]})}function jt({children:e}){return a.jsx("label",{className:"text-[11px] font-medium text-muted-foreground mb-1 block",children:e})}
8248function dr({value:e,onChange:t,placeholder:r,type:n="text",...s}){return a.jsx("input",{type:n,value:e??"",onChange:i=>t(n==="number"?parseFloat(i.target.value):i.target.value),placeholder:r,className:"w-full px-2.5 py-1.5 text-xs border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary/20",...s})}function Ds({value:e,onChange:t,placeholder:r,rows:n=2}){return a.jsx("textarea",{value:e??"",onChange:s=>t(s.target.value),placeholder:r,rows:n,className:"w-full px-2.5 py-1.5 text-xs border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary/20 resize-none"})}function Rs({value:e,onChange:t,options:r}){return a.jsx("select",{value:e,onChange:n=>t(n.target.value),className:"w-full px-2.5 py-1.5 text-xs border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary/20",children:r.map(n=>a.jsx("option",{value:n,children:n},n))})}function Ol({label:e,checked:t,onChange:r}){const n=e.replace(/\s/g,"_");return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:n,checked:t,onChange:s=>r(s.target.checked),className:"rounded"}),a.jsx("label",{htmlFor:n,className:"text-[11px] text-muted-foreground",children:e})]})}function Tbe({config:e,updateConfig:t}){const r=(e==null?void 0:e.faqs)||[],[n,s]=m.useState(""),[i,o]=m.useState(""),[l,c]=m.useState(!1),u=()=>{!n.trim()||!i.trim()||(t("faqs",[...r,{q:n.trim(),a:i.trim()}]),s(""),o(""))},d=f=>t("faqs",r.filter((x,g)=>g!==f)),p=()=>t("faqs",[]),h=async f=>{var v,k;const x=(v=f.target.files)==null?void 0:v[0];if(!x)return;const g=["application/pdf","text/plain","text/markdown","text/csv","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword"],y=[".pdf",".txt",".md",".csv",".doc",".docx"],b="."+((k=x.name.split(".").pop())==null?void 0:k.toLowerCase());if(!g.includes(x.type)&&!y.includes(b)){W.error("Unsupported file type. Use PDF, TXT, MD, CSV, or DOC/DOCX.");return}if(x.size>10*1024*1024){W.error("File too large. Max 10MB.");return}c(!0);try{const N=new FormData;N.append("file",x);const w=await fetch("https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/parse-faq-doc",{method:"POST",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"},body:N});if(!w.ok){const C=await w.json().catch(()=>({error:"Upload failed"}));throw new Error(C.error||`Upload failed (${w.status})`)}const T=(await w.json()).faqs||[];T.length===0?W.warning("No FAQ pairs found in the document."):(t("faqs",[...r,...T]),W.success(`Extracted ${T.length} FAQ pairs from "${x.name}"`))}catch(N){W.error(N.message||"Failed to parse document")}finally{c(!1),f.target.value=""}};return a.jsxs("div",{className:"border-t pt-2 mt-2",children:[a.jsxs(jt,{children:["FAQ Entries (",r.length,")"]}),a.jsxs("div",{className:"space-y-1.5 max-h-40 overflow-y-auto mb-2",children:[r.map((f,x)=>a.jsxs("div",{className:"bg-secondary rounded-md p-2 text-[10px] relative group",children:[a.jsxs("p",{className:"font-medium text-foreground",children:["Q: ",f.q]}),a.jsxs("p",{className:"text-muted-foreground mt-0.5",children:["A: ",f.a]}),a.jsx("button",{onClick:()=>d(x),className:"absolute top-1 right-1 text-destructive opacity-0 group-hover:opacity-100 text-[10px] font-bold",children:"✕"})]},x)),r.length===0&&a.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"No FAQs yet. Upload a document or add entries manually."})]}),a.jsx("div",{className:"mb-2",children:a.jsxs("label",{className:L("flex items-center justify-center gap-1.5 w-full px-3 py-2 text-[10px] font-medium border border-dashed rounded-lg cursor-pointer transition-colors",l?"bg-muted text-muted-foreground cursor-wait":"hover:bg-secondary text-foreground"),children:[l?a.jsxs(a.Fragment,{children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"})," Extracting FAQs with AI..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Dn,{className:"w-3 h-3"})," Upload FAQ Document (PDF, TXT, DOC)"]}
8248),a.jsx("input",{type:"file",className:"hidden",accept:".pdf,.txt,.md,.csv,.doc,.docx",onChange:h,disabled:l})]})}),a.jsxs("div",{className:"space-y-1",children:[a.jsx(dr,{value:n,onChange:f=>s(f),placeholder:"Question: e.g. What are your hours?"}),a.jsx(Ds,{value:i,onChange:f=>o(f),placeholder:"Answer: e.g. We're open Mon-Fri 9am-5pm",rows:2}),a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Q,{variant:"outline",size:"sm",className:"text-[10px] h-7 flex-1",onClick:u,disabled:!n.trim()||!i.trim(),children:"+ Add FAQ"}),r.length>0&&a.jsx(Q,{variant:"ghost",size:"sm",className:"text-[10px] h-7 text-destructive",onClick:p,children:"Clear All"})]})]})]})}function Ebe({node:e,onUpdate:t}){var n,s,i,o,l,c,u,d,p,h,f,x,g,y,b,v,k,N,j,w,S,T,C,A,P,E,_,I,D,M,B,$,K,R,Y,Z,O,ne,oe,he,ae,ve,re,se,le,te,We,Me,Te,Ee,st,xt,on,Yt,mt,ln,at,gt,$t,ue,je,ct,it;const r=(q,Nt)=>t({config:{...e.config,[q]:Nt}});switch(e.type){case"user_message":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Trigger Pattern"}),a.jsx(dr,{value:(n=e.config)==null?void 0:n.pattern,onChange:q=>r("pattern",q),placeholder:"Any message (default)"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Channel"}),a.jsx(Rs,{value:((s=e.config)==null?void 0:s.channel)||"all",onChange:q=>r("channel",q),options:["all","website","api","whatsapp"]})]}),a.jsx(Ol,{label:"Active",checked:((i=e.config)==null?void 0:i.active)!==!1,onChange:q=>r("active",q)})]});case"webhook":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"HTTP Method"}),a.jsx(Rs,{value:((o=e.config)==null?void 0:o.method)||"POST",onChange:q=>r("method",q),options:["GET","POST","PUT"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Endpoint Path"}),a.jsx(dr,{value:(l=e.config)==null?void 0:l.path,onChange:q=>r("path",q),placeholder:"/webhook/my-trigger"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Auth Header"}),a.jsx(dr,{value:(c=e.config)==null?void 0:c.auth_header,onChange:q=>r("auth_header",q),placeholder:"x-api-key"})]})]});case"schedule":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Cron Expression"}),a.jsx(dr,{value:(u=e.config)==null?void 0:u.cron,onChange:q=>r("cron",q),placeholder:"0 9 * * *"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Timezone"}),a.jsx(dr,{value:(d=e.config)==null?void 0:d.timezone,onChange:q=>r("timezone",q),placeholder:"UTC"})]}),a.jsx(Ol,{label:"Active",checked:((p=e.config)==null?void 0:p.active)!==!1,onChange:q=>r("active",q)})]});case"intent_detection":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"System Instruction"}),a.jsx(Ds,{value:(h=e.config)==null?void 0:h.system_instruction,onChange:q=>r("system_instruction",q),placeholder:"You are a classification model...",rows:2})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Intents (comma-separated)"}),a.jsx(dr,{value:(((f=e.config)==null?void 0:f.intents)||[]).join(", "),onChange:q=>r("intents",q.split(",").map(Nt=>Nt.trim()).filter(Boolean))})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Confidence Threshold"}),a.jsx(dr,{type:"number",step:"0.05",min:"0",max:"1",value:((x=e.config)==null?void 0:x.confidence)??.7,onChange:q=>r("confidence",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Fallback Node"}),a.jsx(dr,{value:(g=e.config)==null?void 0:g.fallback_node,onChange:q=>r("fallback_node",q),placeholder:"node_id"})]})]});case"ai_reply":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Prompt / Response Instruction"}),a.jsx(Ds,{value:(y=e.config)==null?void 0:y.prompt,onChange:q=>r("prompt",q),rows:3})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Temperature"}),a.jsx(dr,{type:"number",step:"0.1",min:"0",max:"2",value:((b=e.config)==null?void 0:b.temperature)??.7,onChange:q=>r("temperature",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Knowledge Source"}),a.jsx(Rs,{value:((v=e.config)==null?void 0:v.knowledge_source)||"none",onChange:q=>r("knowledge_source",q),options:["none","faq_db","docs","custom"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Output Format"}),a.jsx(Rs,{value:((k=e.config)==null?void 0:k.output_format)||"text",onCh
8248ange:q=>r("output_format",q),options:["text","json","markdown"]})]})]});case"knowledge_search":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Knowledge Source"}),a.jsx(Rs,{value:((N=e.config)==null?void 0:N.source)||"faq_db",onChange:q=>r("source",q),options:["faq_db","docs","custom_kb"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Top K Results"}),a.jsx(dr,{type:"number",min:"1",max:"20",value:((j=e.config)==null?void 0:j.top_k)??3,onChange:q=>r("top_k",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Similarity Threshold"}),a.jsx(dr,{type:"number",step:"0.05",min:"0",max:"1",value:((w=e.config)==null?void 0:w.threshold)??.5,onChange:q=>r("threshold",q)})]}),a.jsx(Tbe,{config:e.config,updateConfig:r})]});case"summarize_context":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Max Context Length"}),a.jsx(dr,{type:"number",value:((S=e.config)==null?void 0:S.max_length)??2e3,onChange:q=>r("max_length",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Summary Style"}),a.jsx(Rs,{value:((T=e.config)==null?void 0:T.style)||"concise",onChange:q=>r("style",q),options:["concise","detailed","bullet_points"]})]})]});case"condition":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Condition Rules (JSON)"}),a.jsx(Ds,{value:JSON.stringify(((C=e.config)==null?void 0:C.rules)||[],null,2),onChange:q=>{try{r("rules",JSON.parse(q))}catch{}},rows:4})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Default Path (node ID)"}),a.jsx(dr,{value:(A=e.config)==null?void 0:A.default_go_to,onChange:q=>r("default_go_to",q),placeholder:"fallback_node_id"})]})]});case"router":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Route Key (variable)"}),a.jsx(dr,{value:(P=e.config)==null?void 0:P.route_key,onChange:q=>r("route_key",q),placeholder:"intent"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Routes (JSON map)"}),a.jsx(Ds,{value:JSON.stringify(((E=e.config)==null?void 0:E.routes)||{},null,2),onChange:q=>{try{r("routes",JSON.parse(q))}catch{}},rows:4})]})]});case"wait":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Delay (seconds)"}),a.jsx(dr,{type:"number",min:"0",value:((_=e.config)==null?void 0:_.delay_seconds)??5,onChange:q=>r("delay_seconds",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Wait For"}),a.jsx(Rs,{value:((I=e.config)==null?void 0:I.wait_for)||"delay",onChange:q=>r("wait_for",q),options:["delay","user_response","external_event"]})]})]});case"fallback":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Fallback Message"}),a.jsx(Ds,{value:(D=e.config)==null?void 0:D.message,onChange:q=>r("message",q),placeholder:"Sorry, I didn't understand that."})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Max Retries"}),a.jsx(dr,{type:"number",min:"0",max:"5",value:((M=e.config)==null?void 0:M.max_retries)??2,onChange:q=>r("max_retries",q)})]})]});case"send_message":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Message Text"}),a.jsx(Ds,{value:(B=e.config)==null?void 0:B.text,onChange:q=>r("text",q),placeholder:"Use {{variable}} for interpolation",rows:3})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Channel"}),a.jsx(Rs,{value:(($=e.config)==null?void 0:$.channel)||"default",onChange:q=>r("channel",q),options:["default","website","whatsapp","email"]})]}),a.jsx(Ol,{label:"Rich message (buttons, cards)",checked:((K=e.config)==null?void 0:K.rich)??!1,onChange:q=>r("rich",q)}),a.jsx(Ol,{label:"Variable interpolation",checked:((R=e.config)==null?void 0:R.interpolate)!==!1,onChange:q=>r("interpolate",q)})]});case"collect_input":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Field Name"}),a.jsx(dr,{value:(Y=e.config)==null?void 0:Y.field,onChange:q=>r("field",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Question Text"}),a.jsx(Ds,{value:(Z=e.config)==null?void 0:Z.question,onChange:q=>r("question",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Validation Type"}),a.jsx(Rs,{value:((O=e.config)==null?void 0:O.validation)||"text",onCh
8248ange:q=>r("validation",q),options:["text","email","phone","number","date"]})]}),a.jsx(Ol,{label:"Required",checked:((ne=e.config)==null?void 0:ne.required)!==!1,onChange:q=>r("required",q)}),a.jsxs("div",{children:[a.jsx(jt,{children:"Save to Variable"}),a.jsx(dr,{value:(oe=e.config)==null?void 0:oe.save_to,onChange:q=>r("save_to",q),placeholder:"{{field_name}}"})]})]});case"save_lead":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Destination"}),a.jsx(dr,{value:(he=e.config)==null?void 0:he.destination,onChange:q=>r("destination",q),placeholder:"leads"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Field Mapping (JSON)"}),a.jsx(Ds,{value:JSON.stringify(((ae=e.config)==null?void 0:ae.fields)||[],null,2),onChange:q=>{try{r("fields",JSON.parse(q))}catch{}},rows:3})]}),a.jsx(Ol,{label:"Deduplication",checked:((ve=e.config)==null?void 0:ve.dedup)!==!1,onChange:q=>r("dedup",q)})]});case"api_call":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Method"}),a.jsx(Rs,{value:((re=e.config)==null?void 0:re.method)||"GET",onChange:q=>r("method",q),options:["GET","POST","PUT","PATCH","DELETE"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Endpoint URL"}),a.jsx(dr,{value:(se=e.config)==null?void 0:se.endpoint,onChange:q=>r("endpoint",q),placeholder:"https://api.example.com/..."})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Headers (JSON)"}),a.jsx(Ds,{value:JSON.stringify(((le=e.config)==null?void 0:le.headers)||{},null,2),onChange:q=>{try{r("headers",JSON.parse(q))}catch{}},rows:2})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Body (JSON)"}),a.jsx(Ds,{value:JSON.stringify(((te=e.config)==null?void 0:te.body)||{},null,2),onChange:q=>{try{r("body",JSON.parse(q))}catch{}},rows:3})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Auth Type"}),a.jsx(Rs,{value:((We=e.config)==null?void 0:We.auth_type)||"none",onChange:q=>r("auth_type",q),options:["none","bearer","api_key","basic"]})]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"text-[10px] h-7 gap-1 w-full mt-1",children:[a.jsx(Li,{className:"w-3 h-3"})," Test Request"]})]});case"create_ticket":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Ticketing System"}),a.jsx(Rs,{value:((Me=e.config)==null?void 0:Me.system)||"internal",onChange:q=>r("system",q),options:["internal","zendesk","freshdesk","jira"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Priority"}),a.jsx(Rs,{value:((Te=e.config)==null?void 0:Te.priority)||"medium",onChange:q=>r("priority",q),options:["low","medium","high","urgent"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Assign To"}),a.jsx(dr,{value:(Ee=e.config)==null?void 0:Ee.assign_to,onChange:q=>r("assign_to",q),placeholder:"team or agent"})]})]});case"book_appointment":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Calendar Provider"}),a.jsx(Rs,{value:((st=e.config)==null?void 0:st.provider)||"google",onChange:q=>r("provider",q),options:["google","outlook","calendly","custom"]})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Duration (minutes)"}),a.jsx(dr,{type:"number",value:((xt=e.config)==null?void 0:xt.duration)??30,onChange:q=>r("duration",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Booking Confirmation Message"}),a.jsx(Ds,{value:(on=e.config)==null?void 0:on.confirmation,onChange:q=>r("confirmation",q),placeholder:"Your appointment is confirmed for {{date}}"})]})]});case"human_handoff":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Target Team"}),a.jsx(dr,{value:(Yt=e.config)==null?void 0:Yt.team,onChange:q=>r("team",q),placeholder:"support-tier-2"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Handoff Message"}),a.jsx(Ds,{value:(mt=e.config)==null?void 0:mt.message,onChange:q=>r("message",q),placeholder:"Connecting you with a human agent..."})]}),a.jsx(Ol,{label:"Include conversation history",checked:((ln=e.config)==null?void 0:ln.include_history)!==!1,onChange:q=>r("include_history",q)})]});case"send_email":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"To"}),a.jsx(dr,{value:(at=e.config)==null?void 0:at.to,onChange:q=>r("to",q),placeholder:"{{user_email}}"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Subject"}),a.jsx(dr,{value:(gt=e.config)==null?void 0:gt.subject,onChange:q=>r("subject",q)})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Body"}),a.jsx(Ds,{value:($t=e.config)==null?void 0:$t.body,onChange:q=>r("body",q),rows:3})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Template"}),a.jsx(Rs,{value:((ue=e.config)==null?void 0:ue.template)||"none",onChange:q=>
8248r("template",q),options:["none","welcome","confirmation","notification"]})]})]});case"set_variable":case"update_variable":return a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(jt,{children:"Variable Name"}),a.jsx(dr,{value:(je=e.config)==null?void 0:je.variable,onChange:q=>r("variable",q),placeholder:"my_variable"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Value / Expression"}),a.jsx(Ds,{value:(ct=e.config)==null?void 0:ct.value,onChange:q=>r("value",q),placeholder:"{{previous_output.field}}"})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Value Type"}),a.jsx(Rs,{value:((it=e.config)==null?void 0:it.value_type)||"string",onChange:q=>r("value_type",q),options:["string","number","boolean","json"]})]})]});default:return a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"No additional configuration for this node type."})}}function Ibe({flow:e,selectedNode:t,activeTab:r,onUpdateNode:n}){const[s,i]=m.useState(""),[o,l]=m.useState([]),[c,u]=m.useState(null),[d,p]=m.useState(!1),h=["I want pricing","Book cleaning tomorrow","I need support","I want to talk to a human"],f=m.useCallback(async g=>{if(g.trim()){l(y=>[...y,{role:"user",text:g}]),i(""),p(!0);try{if(!await ra.saveFullFlow(e.id,{name:e.name,description:e.description||"",trigger_type:e.trigger_type,nodes:e.nodes.map(w=>({id:w.id,type:w.type,label:w.label,description:w.description||"",config:w.config||{},position_x:w.position_x,position_y:w.position_y})),edges:e.edges.map(w=>({source_node_id:w.source_node_id,target_node_id:w.target_node_id,source_handle:w.source_handle||"default",condition_label:w.condition_label||""}))}))throw new Error("Please save your flow before testing.");const{data:{session:b}}=await G.auth.getSession(),v=b==null?void 0:b.access_token;if(!v)throw new Error("You must be signed in to test flows.");const N=await fetch(`https://xfmlsevleobdlnjqxmdi.supabase.co/functions/v1/workflow-api/flows/${e.id}/test`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo"},body:JSON.stringify({message:g,channel:"test"})}),j=await N.json().catch(()=>({}));if(!N.ok)throw new Error((j==null?void 0:j.error)||"Test run failed");if(j.conversation){const w=j.conversation.filter(S=>S.role==="bot");l(S=>[...S,...w.map(T=>({role:"bot",text:T.text}))])}else l(w=>{var S;return[...w,{role:"bot",text:((S=j.run)==null?void 0:S.output_summary)||"Flow executed"}]});j.run&&u({id:j.run.id,workflow_id:j.run.workflow_id,workflow_name:j.run.workflow_name||e.name,status:j.run.status,trigger_payload:JSON.stringify(j.run.trigger_payload),started_at:j.run.started_at,completed_at:j.run.completed_at,duration_ms:j.run.duration_ms,output_summary:j.run.output_summary,channel:j.run.channel||"test",steps:(j.run.steps||[]).map(w=>({id:w.id,run_id:w.run_id,node_id:w.node_id||"",node_type:w.node_type,node_label:w.node_label,status:w.status,input_data:w.input_data||"",output_data:w.output_data||"",error_message:w.error_message,started_at:w.started_at,completed_at:w.completed_at,duration_ms:w.duration_ms}))})}catch(y){const b=(y==null?void 0:y.message)||"Test failed";W.error(b),l(v=>[...v,{role:"bot",text:`⚠️ ${b}`}])}finally{p(!1)}}},[e]),x=()=>{l([]),u(null)};if(r==="properties"){if(!t)return a.jsxs("div",{className:"p-4 text-center",children:[a.jsx(Dn,{className:"w-8 h-8 text-muted-foreground/20 mx-auto mb-2"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a node to configure its properties"}),a.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1",children:"Click any node on the canvas or add one from the library"})]});const g=Qo.find(y=>y.type===t.type);return a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{className:"flex items-center gap-2 pb-3 border-b",children:[a.jsx("span",{className:"text-lg",children:(g==null?void 0:g.icon)||"⚙️"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground",children:t.label}),a.jsx("p",{className:"text-[10px] text-muted-foreground capitalize",children:t.type.replace(/_/g," ")})]}),a.jsx("span",{className:"text-[9px] font-mono text-muted-foreground
8248/40",children:t.id})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Node Name"}),a.jsx(dr,{value:t.label,onChange:y=>n(t.id,{label:y})})]}),a.jsxs("div",{children:[a.jsx(jt,{children:"Description"}),a.jsx(Ds,{value:t.description,onChange:y=>n(t.id,{description:y})})]}),a.jsxs("div",{className:"pt-2 border-t space-y-3",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:"Configuration"}),a.jsx(Ebe,{node:t,onUpdate:y=>n(t.id,y)})]})]})}if(r==="test")return a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"px-4 py-3 border-b flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Test Flow"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Simulate a conversation to test your flow"})]}),o.length>0&&a.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:x,title:"Reset",children:a.jsx(Ri,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:[o.length===0&&a.jsxs("div",{className:"text-center py-6",children:[a.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Try one of these:"}),a.jsx("div",{className:"flex flex-wrap gap-1.5 justify-center",children:h.map(g=>a.jsx("button",{onClick:()=>f(g),className:"px-2.5 py-1 rounded-full bg-secondary text-[10px] text-muted-foreground hover:text-foreground transition-colors",children:g},g))})]}),o.map((g,y)=>a.jsx("div",{className:L("flex",g.role==="user"?"justify-end":"justify-start"),children:a.jsx("div",{className:L("max-w-[80%] px-3 py-2 rounded-xl text-xs",g.role==="user"?"bg-primary text-primary-foreground":"bg-secondary text-foreground"),children:g.text})},y)),d&&a.jsx("div",{className:"flex justify-start",children:a.jsx("div",{className:"bg-secondary px-3 py-2 rounded-xl",children:a.jsx(ze,{className:"w-3 h-3 animate-spin text-muted-foreground"})})})]}),c&&a.jsxs("div",{className:"border-t px-4 py-3 max-h-40 overflow-y-auto",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground mb-2 uppercase tracking-wider",children:"Execution Trace"}),c.steps.map((g,y)=>a.jsxs("div",{className:"flex items-center gap-2 py-1",children:[g.status==="success"?a.jsx(mn,{className:"w-3 h-3 text-primary"}):g.status==="failed"?a.jsx(aa,{className:"w-3 h-3 text-destructive"}):a.jsx(Lr,{className:"w-3 h-3 text-muted-foreground"}),a.jsx("span",{className:"text-[10px] text-foreground",children:g.node_label}),a.jsx("span",{className:"text-[9px] text-muted-foreground/50 capitalize",children:g.node_type.replace(/_/g," ")}),a.jsxs("span",{className:"text-[10px] text-muted-foreground ml-auto",children:[g.duration_ms,"ms"]})]},y)),a.jsxs("div",{className:"flex items-center gap-1.5 mt-2 pt-2 border-t",children:[a.jsx(mn,{className:"w-3 h-3 text-primary"}),a.jsxs("span",{className:"text-[10px] font-medium text-foreground",children:["Total: ",c.duration_ms,"ms"]})]})]}),a.jsxs("div",{className:"border-t p-3 flex gap-2",children:[a.jsx("input",{value:s,onChange:g=>i(g.target.value),onKeyDown:g=>g.key==="Enter"&&f(s),placeholder:"Type a message...",className:"flex-1 px-3 py-1.5 text-xs border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary/20"}),a.jsx(Q,{size:"icon",className:"h-7 w-7",onClick:()=>f(s),disabled:d,children:a.jsx(Li,{className:"w-3 h-3"})})]})]});if(r==="execution")return a.jsxs("div",{className:"p-4 space-y-3",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground mb-2",children:"Execution Inspector"}),t?a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground mb-1",children:"Node"}),a.jsx("p",{className:"text-xs font-medium",children:t.label}),a.jsx("p",{className:"text-[10px] text-muted-foreground capitalize",children:t.type.replace(/_/g," ")})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground mb-1",children:"Expected Input"}),a.jsx("pre",{className:"text-[10px] text-foreground font-mono whitespace-pre-wrap bg-background rounded p-2 mt-1",children:t.type==="user_message"?"{ message: string, channel: string }":t.type==="intent_detection"?"{ message: string }":t.type==="condition"?"{ variables: Record<string, any> }":t.type==="ai_reply"?"{ context: string, history: Message[] }":t.type==="api_call"?"{ variables: Record<string, any> }":"{ previous_output: any }"})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground mb-1",children:"Expected Output"}),a.jsx("pre",{className:"text-[10px] text-foreground font-mono whitespace-pre-wrap bg-background rounded p-2 mt-1",children:t.type==="intent_detection"?"{ intent: string, confidence: number }":t.type==="condition"?"{ branch: string, next_node: string }":t.type==="ai_reply"?"{ response: string, tokens_used: number }":t.type==="api_call"?"{ status: number, body: any }":t.type==="collect_input"?"{ field: string, value: any, valid: boolean }":t.type==="save_lead"?"{ lead_id: string, created: boolean }":"{ result: any }"})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground mb-1",children:"Failure Handling"}),a.jsx("p",{className:"text-[10px] text-muted-foreground",children:t.type==="api_call"?"Retries up to 3 times with exponential backoff, then falls back to error handler":t.type==="ai_reply"?"Falls back to default response if model fails":"Falls back to error handler or stops execution"})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground mb-1",children:"Next Possible Branches"}),e.edges.filter(g=>g.source_node_id===t.id).map(g=>{const y=e.nodes.find(b=>b.id===g.target_node_id);return a.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[a.jsx(Sh,{className:"w-3 h-3 text-primary/50"}),a.jsx("span",{className:"text-[10px] text-foreground",children:(y==null?void 0:y.label)||g.target_node_id}),g.condition_label&&a.jsxs("span",{className:"text-[9px] text-muted-foreground
8248/60",children:["(",g.condition_label,")"]})]},g.id)}),e.edges.filter(g=>g.source_node_id===t.id).length===0&&a.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1",children:"End of flow (no outgoing edges)"})]})]}):a.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a node to inspect execution details"})]});if(r==="json"){const g={id:e.id,name:e.name,status:e.status,version:e.version,trigger:{type:e.trigger_type},nodes:e.nodes.map(b=>({id:b.id,type:b.type,label:b.label,config:b.config,position:{x:b.position_x,y:b.position_y}})),edges:e.edges.map(b=>({source:b.source_node_id,target:b.target_node_id,handle:b.source_handle,condition:b.condition_label||void 0}))},y=JSON.stringify(g,null,2);return a.jsxs("div",{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Workflow JSON"}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(y),W.success("Copied")},children:a.jsx(gs,{className:"w-3 h-3"})})]}),a.jsx("pre",{className:"bg-background border rounded-lg p-3 text-[10px] font-mono text-foreground overflow-auto max-h-[70vh] whitespace-pre-wrap",children:y})]})}return null}const Obe=[{label:"Add AI Reply node",icon:Dn},{label:"Add a condition branch",icon:hr},{label:"Describe this flow",icon:Dn},{label:"Add API call step",icon:Li}];function __(e,t){const r=e.toLowerCase().trim(),n=[{pattern:/^add\s+(an?\s+)?ai\s+reply/i,type:"ai_reply",label:"AI Reply"},{pattern:/^add\s+(an?\s+)?intent\s+detect/i,type:"intent_detection",label:"Intent Detection"},{pattern:/^add\s+(an?\s+)?condition/i,type:"condition",label:"Condition"},{pattern:/^add\s+(an?\s+)?router/i,type:"router",label:"Router"},{pattern:/^add\s+(an?\s+)?api\s+call/i,type:"api_call",label:"API Call"},{pattern:/^add\s+(an?\s+)?send\s+message/i,type:"send_message",label:"Send Message"},{pattern:/^add\s+(an?\s+)?collect\s+input/i,type:"collect_input",label:"Collect Input"},{pattern:/^add\s+(an?\s+)?save\s+lead/i,type:"save_lead",label:"Save Lead"},{pattern:/^add\s+(an?\s+)?human\s+handoff/i,type:"human_handoff",label:"Human Handoff"},{pattern:/^add\s+(an?\s+)?webhook/i,type:"webhook",label:"Webhook Trigger"},{pattern:/^add\s+(an?\s+)?delay|^add\s+(an?\s+)?wait/i,type:"wait",label:"Wait / Delay"},{pattern:/^add\s+(an?\s+)?email/i,type:"send_email",label:"Send Email"},{pattern:/^add\s+(an?\s+)?ticket/i,type:"create_ticket",label:"Create Ticket"},{pattern:/^add\s+(an?\s+)?book/i,type:"book_appointment",label:"Book Appointment"},{pattern:/^add\s+(an?\s+)?knowledge/i,type:"knowledge_search",label:"Knowledge Search"},{pattern:/^add\s+(an?\s+)?summarize/i,type:"summarize_context",label:"Summarize Context"},{pattern:/^add\s+(an?\s+)?variable/i,type:"set_variable",label:"Set Variable"},{pattern:/^add\s+(an?\s+)?fallback/i,type:"fallback",label:"Fallback"}];for(const i of n)if(i.pattern.test(r))return{response:`✅ Added **${i.label}** node to your flow. Select it on the canvas to configure.`,action:{type:"add_node",nodeType:i.type}};if(/^(describe|explain|summary|what does|overview)/i.test(r)){if(!t||t.nodes.length===0)return{response:"Your flow is empty. Describe what you want to build and I'll create the nodes for you!"};const i=t.nodes.map((o,l)=>`${l+1}. **${o.label}** (\`${o.type}\`)`).join(`
8249`);return{response:`### Flow: ${t.name}
8250
8251**${t.nodes.length} nodes**, ${t.edges.length} connections
8252
8253${i}`,action:{type:"describe_flow"}}}const s=r.match(/^(?:delete|remove)\s+(?:the\s+)?(?:node\s+)?["']?([^"']+)["']?/i);if(s&&t){const i=s[1].trim().toLowerCase(),o=t.nodes.find(l=>l.label.toLowerCase().includes(i)||l.id.toLowerCase()===i);return o?{response:`🗑️ Removed **${o.label}** from the flow.`,action:{type:"delete_node",nodeId:o.id}}:{response:`Couldn't find a node matching "${s[1]}".`}}if(/^(what\s+(nodes?|types?)|list\s+nodes?|available\s+nodes?)/i.test(r)){const i=new Map;Qo.forEach(l=>{const c=l.category||"Other";i.has(c)||i.set(c,[]),i.get(c).push(l.label)});let o=`### Available Node Types
8254
8255`;
8255return i.forEach((l,c)=>{o+=`**${c}:**  ${l.join(", ")}
8256
8257`}),{response:o}}return/^help$/i.test(r)?{response:`### Flow Chat Commands
8258
8259- **Describe what you want** — I'll build the flow automatically
8260- **"Add [node type]"** — Insert a single node
8261- **"Delete [node name]"** — Remove a node
8262- **"Describe this flow"** — Get a summary`}:null}function Rbe({flow:e,onAddNode:t,onUpdateNode:r,onDeleteNode:n,onSelectNode:s}){const[i,o]=m.useState([{id:"welcome",role:"assistant",content:`👋 I'm your **Flow Builder Assistant**. Describe the chatbot flow you want and I'll build it automatically!
8263
8264For example: *"Build a support flow that detects intent, answers from FAQ, and escalates to a human agent"*`,timestamp:Date.now()}]),[l,c]=m.useState(""),[u,d]=m.useState(!1),p=m.useRef(null),h=m.useRef(null);m.useEffect(()=>{p.current&&(p.current.scrollTop=p.current.scrollHeight)},[i]);const f=m.useCallback((v,k)=>{o(N=>[...N,{id:`msg-${Date.now()}-resp`,role:"assistant",content:v,timestamp:Date.now(),action:k}])},[]),x=m.useCallback(async v=>{var k;try{const{data:N,error:j}=await G.functions.invoke("build-flow-from-description",{body:{description:v,existingNodeCount:(e==null?void 0:e.nodes.length)||0}});if(j){console.error("Build flow error:",j),f(`⚠️ Something went wrong: ${j.message||"AI service unavailable"}. Please try again.`);return}if(!((k=N==null?void 0:N.nodes)!=null&&k.length)){const T=(N==null?void 0:N.error)||"";console.error("No nodes returned:",N),f(`⚠️ ${T||"No nodes were generated."}  Please try again with a different description.`);return}const w=N.nodes;for(const T of w)t(T.type,{label:T.label,description:T.description});const S=w.map((T,C)=>`${C+1}. **${T.label}** — ${T.description}`).join(`
8265`);f(`✅ Built your flow with **${w.length} nodes**:
8266
8267${S}
8268
8269Select any node on the canvas to configure its properties.`,{type:"build_flow",nodesToAdd:w.map(T=>T.type)})}catch{f("Something went wrong while building the flow. Please try again.")}},[e,t,f]),g=m.useCallback(()=>{const v=l.trim();if(!v||u)return;const k={id:`msg-${Date.now()}`,role:"user",content:v,timestamp:Date.now()};o(j=>[...j,k]),c("");const N=__(v,e);N?(d(!0),setTimeout(()=>{N.action&&(N.action.type==="add_node"&&N.action.nodeType?t(N.action.nodeType):N.action.type==="delete_node"&&N.action.nodeId&&n(N.action.nodeId)),f(N.response,N.action),d(!1)},300)):(d(!0),x(v).finally(()=>d(!1)))},[l,u,e,t,n,f,x]),y=v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),g())},b=v=>{c(v),setTimeout(()=>{const k={id:`msg-${Date.now()}`,role:"user",content:v,timestamp:Date.now()};o(j=>[...j,k]),d(!0);const N=__(v,e);setTimeout(()=>{var j;((j=N==null?void 0:N.action)==null?void 0:j.type)==="add_node"&&N.action.nodeType&&t(N.action.nodeType),f((N==null?void 0:N.response)||"Done!",N==null?void 0:N.action),d(!1),c("")},300)},50)};return a.jsxs("div",{className:"flex flex-col h-full bg-card",children:[a.jsxs("div",{className:"h-12 border-b flex items-center justify-between px-4 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center",children:a.jsx(Dn,{className:"w-3.5 h-3.5 text-primary"})}),a.jsx("span",{className:"text-sm font-semibold text-foreground",children:"Flow Chat"})]}),a.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>o([i[0]]),title:"Clear chat",children:a.jsx(Ri,{className:"w-3.5 h-3.5"})})]}),a.jsxs("div",{ref:p,className:"flex-1 overflow-y-auto px-3 py-4 space-y-4",children:[i.map(v=>a.jsxs("div",{className:L("flex gap-2.5",v.role==="user"?"justify-end":"justify-start"),children:[v.role==="assistant"&&a.jsx(ri,{className:"w-7 h-7 shrink-0 mt-0.5"}),a.jsx("div",{className:L("max-w-[85%] rounded-xl px-3.5 py-2.5 text-sm",v.role==="user"?"bg-primary text-primary-foreground rounded-br-sm":"bg-muted/50 text-foreground rounded-bl-sm"),children:v.role==="assistant"?a.jsx("div",{className:"prose prose-sm dark:prose-invert max-w-none [&>p]:m-0 [&>ul]:my-1 [&>ol]:my-1 [&>h3]:mt-1 [&>h3]:mb-1.5 [&>h3]:text-sm",children:a.jsx(Dbe,{content:v.content})}):a.jsx("p",{className:"whitespace-pre-wrap",children:v.content})}),v.role==="user"&&a.jsx("div",{className:"w-7 h-7 rounded-full bg-muted flex items-center justify-center shrink-0 mt-0.5",children:a.jsx(_w,{className:"w-3.5 h-3.5 text-muted-foreground"})})]},v.id)),u&&a.jsxs("div",{className:"flex gap-2.5",children:[a.jsx(ri,{className:"w-7 h-7 shrink-0"}),a.jsx("div",{className:"bg-muted/50 rounded-xl rounded-bl-sm px-3.5 py-2.5",children:a.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[a.jsx(ze,{className:"w-3 h-3 animate-spin"}),"Building flow..."]})})]})]}),i.length<=2&&a.jsx("div",{className:"px-3 pb-2 flex flex-wrap gap-1.5",children:Obe.map(v=>a.jsxs("button",{onClick:()=>b(v.label),className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-full bg-muted/50 border text-[11px] text-muted-foreground hover:text-foreground hover:border-primary/30 transition-all",children:[a.jsx(v.icon,{className:"w-3 h-3"}),v.label]},v.label))}),a.jsx("div",{className:"border-t p-3",children:a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsx("textarea",{ref:h,value:l,onCh
8269ange:v=>c(v.target.value),onKeyDown:y,placeholder:"Describe the flow you want to build...",rows:1,className:"flex-1 resize-none bg-muted/30 border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary/30 placeholder:text-muted-foreground/50"}),a.jsx(Q,{size:"icon",className:"h-9 w-9 shrink-0",onClick:g,disabled:!l.trim()||u,children:a.jsx(Li,{className:"w-4 h-4"})})]})})]})}function Dbe({content:e}){const t=e.replace(/### (.+)/g,"<h3>$1</h3>").replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,'<code class="px-1 py-0.5 rounded bg-muted text-xs">$1</code>').replace(/^- (.+)/gm,"<li>$1</li>").replace(/^(\d+)\. (.+)/gm,"<li>$2</li>").replace(/(<li>.*<\/li>\n?)+/g,'<ul class="list-disc pl-4 space-y-0.5">$&</ul>').replace(/\n\n/g,"<br/>").replace(/\n/g,"<br/>");return a.jsx("div",{dangerouslySetInnerHTML:{__html:t}})}function VM({flowId:e,onClose:t}){const[r,n]=m.useState(null),[s,i]=m.useState(!1),[o,l]=m.useState(null),[c,u]=m.useState(!1);m.useEffect(()=>{ra.getFlow(e).then(n)},[e]);const d=async()=>{i(!0);const N=await ra.publishFlow(e);N&&(n(N),W.success("Flow published!")),i(!1)},p=async()=>{const N=await ra.unpublishFlow(e);N&&(n(N),W.success("Flow unpublished"))},h=async()=>{if(r){u(!0),l(null);try{const N=await ra.testFlow(r,"Hello, I need help");l(N.output_summary||"Test completed successfully")}catch{l("Test failed — check flow configuration")}u(!1)}},f=N=>{navigator.clipboard.writeText(N),W.success("Copied to clipboard")};if(!r)return null;const x="https://xfmlsevleobdlnjqxmdi.supabase.co",g=`${x}/functions/v1/workflow-api/flows/${r.id}/test`,y=`${x}/functions/v1/workflow-api/flows/${r.id}/chat`,b=r.published&&r.published_url?r.published_url:y,v=`curl -X POST "${b}" \\
8270  -H "Content-Type: application/json" \\
8271  -H "Authorization: Bearer YOUR_TOKEN" \\
8272  -H "apikey: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo" \\
8273  -d '{"message": "Hello", "session_key": "test-123"}'`,k=[{id:"api",label:"REST API",icon:ST,active:!0},{id:"website",label:"Website Widget",icon:Br,active:!0},{id:"whatsapp",label:"WhatsApp",icon:Tp,active:!1},{id:"messenger",label:"Messenger",icon:Tp,active:!1}];return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",onClick:t,children:a.jsxs("div",{className:"bg-card border rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col",onClick:N=>N.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Es,{className:"w-5 h-5 text-primary"}),a.jsx("h2",{className:"text-lg font-bold text-foreground",children:"Publish Flow"})]}),a.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:a.jsx(qn,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 space-y-5 overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:a.jsx(Es,{className:"w-5 h-5 text-primary"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-semibold",children:r.name}),a.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[r.nodes.length," nodes · v",r.version]})]}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] capitalize",r.published?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":"bg-amber-500/10 text-amber-600 border-amber-500/20"),children:r.published?"Published":"Draft"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-1.5 block",children:"Quick Test"}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs(Q,{variant:"outline",size:"sm",className:"gap-1.5 text-xs flex-1",onClick:h,disabled:c,
8273children:[a.jsx(Oi,{className:"w-3.5 h-3.5"})," ",c?"Running...":"Run Test"]})}),o&&a.jsx("div",{className:"mt-2 p-2.5 bg-background border rounded-lg text-[11px] font-mono text-foreground",children:o})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-1.5 block",children:"Chat API Endpoint (Public)"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("code",{className:"flex-1 px-3 py-2 bg-background border rounded-lg text-[10px] font-mono truncate",children:b}),a.jsx(Q,{variant:"outline",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>f(b),children:a.jsx(gs,{className:"w-3.5 h-3.5"})})]}),a.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["POST with ",'{"message": "...", "session_key": "unique-id"}']})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-1.5 block",children:"Test Endpoint (Authenticated)"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("code",{className:"flex-1 px-3 py-2 bg-background border rounded-lg text-[10px] font-mono truncate",children:g}),a.jsx(Q,{variant:"outline",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>f(g),children:a.jsx(gs,{className:"w-3.5 h-3.5"})})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-1.5 block",children:"cURL Example"}),a.jsxs("div",{className:"relative",children:[a.jsx("pre",{className:"bg-background border rounded-lg p-3 text-[9px] font-mono overflow-auto max-h-24 whitespace-pre-wrap",children:v}),a.jsx(Q,{variant:"ghost",size:"icon",className:"absolute top-1.5 right-1.5 h-6 w-6",onClick:()=>f(v),children:a.jsx(gs,{className:"w-3 h-3"})})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs font-medium text-foreground mb-2 block",children:"Available Channels"}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:k.map(N=>a.jsxs("div",{className:L("flex items-center gap-2 px-3 py-2 border rounded-lg text-xs",N.active?"text-foreground":"text-muted-foreground/50"),children:[a.jsx(N.icon,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:N.label}),N.active?a.jsx(mn,{className:"w-3 h-3 text-emerald-500 ml-auto"}):a.jsx(Ge,{variant:"secondary",className:"text-[9px] ml-auto",children:"Soon"})]},N.id))})]}),a.jsx("div",{className:"flex items-center gap-2 pt-2",children:r.published?a.jsxs(a.Fragment,{children:[a.jsx(Q,{variant:"outline",className:"flex-1 gap-1.5",onClick:p,children:"Unpublish"}),a.jsxs(Q,{className:"flex-1 gap-1.5",onClick:()=>{f(b),W.success("API endpoint copied!")},children:[a.jsx(gs,{className:"w-3.5 h-3.5"})," Copy API URL"]})]}):a.jsxs(Q,{className:"w-full gap-1.5",onClick:d,disabled:s,children:[a.jsx(Es,{className:"w-3.5 h-3.5"})," ",s?"Publishing...":"Publish Flow"]})})]})]})})}function Mbe({flowId:e,onBack:t,onViewLogs:r}){const[n,s]=m.useState(null),[i,o]=m.useState(!0),[l,c]=m.useState(null),[u,d]=m.useState("properties"),[p,h]=m.useState(!1),[f,x]=m.useState(!1),[g,y]=m.useState(""),[b,v]=m.useState(!1);m.useEffect(()=>{(async()=>{o(!0);const _=await ra.getFlow(e);_&&(s(_),y(_.name)),o(!1)})()},[e]);const k=m.useCallback(async()=>{if(!n)return null;const E=await ra.saveFullFlow(n.id,{name:g.trim()||n.name,description:n.description||"",trigger_type:n.trigger_type,nodes:n.nodes.map(_=>({id:_.id,type:_.type,label:_.label,description:_.description||"",config:_.config||{},position_x:_.position_x,position_y:_.position_y})),edges:n.edges.map(_=>({source_node_id:_.source_node_id,target_node_id:_.target_node_id,source_handle:_.source_handle||"default",condition_label:_.condition_label||""}))});return E?(s(E),y(E.name),v(!1),E):(W.error("Failed to save flow"),null)},[n,g]),N=m.useCallback(async()=>{h(!0),await k()&&W.success("Flow saved"),h(!1)},[k]),j=m.useCallback(async()=>{if(b){h(!0);const E=await k();if(h(!1),!E)return}x(!0)},[b,k]),w=m.useCallback((E,_)=>{const I="n_"+crypto.randomUUID().slice(0,6);let D=!1;s(M=>{if(!M)return M;D=!0;const B=Qo.find(O=>O.type===E),$=M.nodes[M.nodes.length-1],K=$?$.position_x:100,R=$?$.position_y+150:100,Y={id:I,workflow_id:M.id,type:E,label:(_==null?void 0:_.label)||(B==null?void 0:B.label)||E,description:(_==null?void 0:_.description)||(B==null?void 0:B.description)||"",config:{},position_x:K,position_y:R},Z=[...M.edges];return $&&Z.push({id:"e_"+crypto.randomUUID().slice(0,6),workflow_id:M.id,source_node_id:$.id,target_node_id:Y.id,source_handle:"default",condition_label:""}),{...M,nodes:[...M.nodes,Y],edges:Z}}),D&&(c(I),d("properties"),v(!0))},[]),S=m.useCallback((E,_)=>{n&&(s({...n,nodes:n.nodes.map(I=>I.id===E?{...I,..._}:I)}),v(!0))},[n]),T=m.useCallback((E,_,I)=>{n&&(s(D=>D&&{...D,nodes:D.nodes.map(M=>M.id===E?{...M,position_x:Math.round(_),position_y:Math.round(I)}:M)}),v(!0))},[n]),C=m.useCallback(E=>{n&&(s({...n,nodes:n.nodes.filter(_=>_.id!==E),edges:n.edges.filter(_=>_.source_node_id!==E&&_.target_node_id!==E)}),l===E&&c(null),v(!0))},[n,l]),A=(n==null?void 0:n.nodes.find(E=>E.id===l))||null;if(i)return a.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground text-sm",children:"Loading flow..."});if(!n)return a.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground text-sm",children:"Flow not found"});const P=[{id:"properties",label:"Properties"},{id:"test",label:"Test Flow"},{id:"execution",label:"Execution"},{id:"json",label:"JSON"}];return a.jsxs("div",{className:"flex-1 flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"h-12 border-b bg-card flex items-center justify-between px-4 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:t,children:a.jsx(ei,{className:"w-4 h-4"})}),a.jsx("input",{value:g,onChange:E=>{y(E.target.value),v(!0)},className:"text-sm font-semibold bg-transparent border-none focus:outline-none focus:ring-0 w-48"}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] capitalize",n.status==="published"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":"bg-
8273amber-500/10 text-amber-600 border-amber-500/20"),children:n.status}),a.jsx("span",{className:L("text-[10px]",b?"text-amber-500":"text-muted-foreground/50"),children:b?"Unsaved changes":"Saved"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Q,{variant:"outline",size:"sm",className:"h-8 text-xs gap-1.5",onClick:r,children:[a.jsx(ai,{className:"w-3.5 h-3.5"})," Logs"]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"h-8 text-xs gap-1.5",onClick:N,disabled:p||!b,children:[a.jsx(Kg,{className:"w-3.5 h-3.5"})," Save"]}),a.jsxs(Q,{variant:"outline",size:"sm",className:"h-8 text-xs gap-1.5",onClick:()=>d("test"),children:[a.jsx(Oi,{className:"w-3.5 h-3.5"})," Test"]}),a.jsxs(Q,{size:"sm",className:"h-8 text-xs gap-1.5",onClick:j,disabled:p,children:[a.jsx(Es,{className:"w-3.5 h-3.5"})," Publish"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden",children:a.jsxs(qM,{direction:"horizontal",className:"h-full",children:[a.jsx(zg,{defaultSize:25,minSize:18,maxSize:40,className:"bg-card",children:a.jsx(Rbe,{flow:n,onAddNode:w,onUpdateNode:S,onDeleteNode:C,onSelectNode:E=>{c(E),d("properties")}})}),a.jsx(HM,{withHandle:!0}),a.jsx(zg,{defaultSize:75,minSize:50,children:a.jsxs("div",{className:"flex h-full overflow-hidden",children:[a.jsx("div",{className:"w-52 border-r bg-card overflow-y-auto shrink-0",children:a.jsx(_be,{onAddNode:w})}),a.jsx("div",{className:"flex-1 overflow-hidden",children:a.jsx(Pbe,{nodes:n.nodes,edges:n.edges,selectedNodeId:l,onSelectNode:c,onDeleteNode:C,onMoveNode:T})}),a.jsxs("div",{className:"w-72 border-l bg-card flex flex-col shrink-0",children:[a.jsx("div",{className:"flex items-center gap-0.5 px-2 pt-2 pb-1 border-b",children:P.map(E=>a.jsx("button",{onClick:()=>d(E.id),className:L("px-2 py-1.5 rounded-md text-[11px] font-medium transition-all",u===E.id?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground"),children:E.label},E.id))}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:a.jsx(Ibe,{flow:n,selectedNode:A,activeTab:u,onUpdateNode:S})})]})]})})]})}),f&&a.jsx(VM,{flowId:n.id,onClose:()=>x(!1)})]})}function Lbe({flowId:e,onBack:t}){const[r,n]=m.useState([]),[s,i]=m.useState(!0),[o,l]=m.useState(""),[c,u]=m.useState("all"),[d,p]=m.useState(null);m.useEffect(()=>{(async()=>{i(!0);const y=await ra.listRuns(e||void 0,c==="all"?void 0:c);n(y),i(!1)})()},[e,c]);const h=o.trim()?r.filter(g=>g.workflow_name.toLowerCase().includes(o.toLowerCase())||g.id.includes(o)||g.output_summary.toLowerCase().includes(o.toLowerCase())):r,f=g=>g==="completed"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":g==="failed"?"bg-destructive/10 text-destructive border-destructive/20":g==="running"?"bg-primary/10 text-primary border-primary/20":"bg-muted text-muted-foreground border-border",x=[{id:"all",label:"All"},{id:"completed",label:"Completed"},{id:"failed",label:"Failed"},{id:"running",label:"Running"}];return a.jsxs("div",{className:"flex-1 flex flex-col items-center px-4 pt-8 pb-8 overflow-y-auto relative z-10",children:[a.jsxs("div",{className:"w-full max-w-4xl",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsx(Q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:t,children:a.jsx(ei,{className:"w-4 h-4"})}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Workflow Runs"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Execution history and logs"})]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(Cn,{value:o,onChange:g=>l(g.target.value),placeholder:"Search runs...",className:"pl-9"})]}),a.jsx("div",{className:"flex items-center gap-1",children:x.map(g=>a.jsx("button",{onClick:()=>u(g.id),className:L("px-3 py-1.5 rounded-full text-xs font-medium transition-all",c===g.id?"bg-primary/10 text-primary border border-primary/20":"bg-card border text-muted-foreground hover:text-foreground"),children:g.label},g.id))})]}),a.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[a.jsxs("div",{className:"bg-secondary/30 px-4 py-2 grid grid-cols-[1fr_120px_80px_80px_100px_80px_40px] gap-2 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:[a.jsx("span",{children:"Run ID / Workflow"}),a.jsx("span",{children:"Trigger"}),a.jsx("span",{children:"Status"}),a.jsx("span",{children:"Duration"}),a.jsx("span",{children:"Started"}),a.jsx("span",{children:"Channel"}),a.jsx("span",{})]}),s&&a.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading..."}),!s&&h.length===0&&a.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No runs found"}),h.map(g=>{var y;return a.jsxs("div",{onClick:()=>p(g),className:"px-4 py-3 grid grid-cols-[1fr_120px_80px_80px_100px_80px_40px] gap-2 items-center border-t hover:bg-secondary/20 cursor-pointer transition-colors",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-foreground",children:g.workflow_name}),a.jsx("p",{className:"text-[10px] font-mono text-muted-foreground
8273/60",children:g.id.slice(0,12)})]}),a.jsx("span",{className:"text-[10px] text-muted-foreground truncate",children:((y=JSON.parse(g.trigger_payload).message)==null?void 0:y.slice(0,20))||"—"}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] px-1.5 py-0 capitalize w-fit",f(g.status)),children:g.status}),a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[g.duration_ms,"ms"]}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(g.started_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}),a.jsx("span",{className:"text-[10px] text-muted-foreground",children:g.channel}),a.jsx(ia,{className:"w-3.5 h-3.5 text-muted-foreground"})]},g.id)})]})]}),d&&a.jsxs("div",{className:"fixed inset-0 z-50 flex",onClick:()=>p(null),children:[a.jsx("div",{className:"flex-1 bg-black/30"}),a.jsxs("div",{className:"w-[480px] bg-card border-l shadow-2xl h-full overflow-y-auto",onClick:g=>g.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b sticky top-0 bg-card z-10",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-bold text-foreground",children:"Run Details"}),a.jsx("p",{className:"text-[10px] font-mono text-muted-foreground",children:d.id})]}),a.jsx("button",{onClick:()=>p(null),className:"text-muted-foreground hover:text-foreground",children:a.jsx(qn,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"p-6 space-y-6",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Workflow"}),a.jsx("p",{className:"text-xs font-medium",children:d.workflow_name})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Status"}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] capitalize",f(d.status)),children:d.status})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Duration"}),a.jsxs("p",{className:"text-xs font-medium",children:[d.duration_ms,"ms"]})]}),a.jsxs("div",{className:"p-3 border rounded-lg",children:[a.jsx("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:"Channel"}),a.jsx("p",{className:"text-xs font-medium",children:d.channel})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-foreground mb-2",children:"Trigger Payload"}),a.jsx("pre",{className:"bg-background border rounded-lg p-3 text-[10px] font-mono overflow-auto",children:d.trigger_payload})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-foreground mb-2",children:"Output"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:d.output_summary})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-semibold text-foreground mb-3",children:"Execution Timeline"}),a.jsx("div",{className:"space-y-0",children:d.steps.map((g,y)=>a.jsxs("div",{className:"flex gap-3 pb-4 relative",children:[y<d.steps.length-1&&a.jsx("div",{className:"absolute left-[11px] top-5 bottom-0 w-px bg-border"}),a.jsx("div",{className:"shrink-0 mt-0.5",children:g.status==="success"?a.jsx(mn,{className:"w-5 h-5 text-emerald-500"}):g.status==="failed"?a.jsx(aa,{className:"w-5 h-5 text-destructive"}):a.jsx(Lr,{className:"w-5 h-5 text-amber-500"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-xs font-medium text-foreground",children:g.node_label}),a.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[g.duration_ms,"ms"]})]}),a.jsx("p",{className:"text-[10px] text-muted-foreground capitalize",children:g.node_type.replace(/_/g," ")}),g.input_data&&a.jsxs("div",{className:"mt-1",children:[a.jsx("p",{className:"text-[9px] text-muted-foreground/70",children:"Input:"}),a.jsx("pre",{className:"text-[9px] font-mono text-muted-foreground bg-background rounded px-2 py-1 mt-0.5 overflow-auto",children:g.input_data})]}),g.output_data&&a.jsxs("div",{className:"mt-1",children:[a.jsx("p",{className:"text-[9px] text-muted-foreground
8273/70",children:"Output:"}),a.jsx("pre",{className:"text-[9px] font-mono text-muted-foreground bg-background rounded px-2 py-1 mt-0.5 overflow-auto",children:g.output_data})]}),g.error_message&&a.jsx("p",{className:"text-[10px] text-destructive mt-1",children:g.error_message})]})]},y))})]})]})]})]})]})}function $be(){const[e,t]=m.useState([]),[r,n]=m.useState(!0),[s,i]=m.useState(""),[o,l]=m.useState("all"),[c,u]=m.useState(!1),[d,p]=m.useState("list"),[h,f]=m.useState(null),[x,g]=m.useState(!1),[y,b]=m.useState(null),v=m.useCallback(async()=>{n(!0);const I=await ra.listFlows(o==="all"?void 0:o);t(I),n(!1)},[o]);m.useEffect(()=>{v()},[v]);const k=I=>{f(I),p("builder")},N=I=>{I&&f(I),p("logs")},j=I=>{b(I),g(!0)},w=async I=>{const D=await ra.duplicateFlow(I);D&&(W.success(`Duplicated as "${D.name}"`),v())},S=async I=>{await ra.updateFlow(I,{status:"archived"}),W.success("Workflow archived"),v()},T=I=>{f(I),p("builder")},C=I=>{u(!1),f(I.id),p("builder"),v()},A=[{id:"all",label:"All"},{id:"draft",label:"Draft"},{id:"published",label:"Published"},{id:"failed",label:"Failed"},{id:"archived",label:"Archived"}],P=s.trim()?e.filter(I=>I.name.toLowerCase().includes(s.toLowerCase())||I.description.toLowerCase().includes(s.toLowerCase())):e,E=I=>I==="webhook"?a.jsx(ST,{className:"w-3 h-3"}):I==="schedule"?a.jsx(A6,{className:"w-3 h-3"}):a.jsx(Li,{className:"w-3 h-3"}),_=I=>I==="published"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":I==="failed"?"bg-destructive/10 text-destructive border-destructive/20":I==="archived"?"bg-muted text-muted-foreground border-border":"bg-amber-500/10 text-amber-600 border-amber-500/20";return d==="builder"&&h?a.jsx(Mbe,{flowId:h,onBack:()=>{p("list"),v()},onViewLogs:()=>N(h)}):d==="logs"?a.jsx(Lbe,{flowId:h,onBack:()=>p("list")}):a.jsxs("div",{className:"flex-1 flex flex-col items-center px-4 pt-12 pb-8 overflow-y-auto relative z-10",children:[a.jsx("h1",{className:"text-2xl md:text-3xl font-bold text-foreground mb-1",children:"Workflows"}),a.jsx("p",{className:"text-sm text-muted-foreground mb-8",children:"Manage and run your AI chat automations."}),a.jsxs("div",{className:"w-full max-w-4xl flex flex-col sm:flex-row items-stretch sm:items-center gap-3 mb-4",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(Cn,{value:s,onChange:I=>i(I.target.value),placeholder:"Search workflows...",className:"pl-9"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Q,{variant:"outline",size:"sm",className:"gap-1.5 text-xs",onClick:()=>N(),children:[a.jsx(ai,{className:"w-3.5 h-3.5"})," Run Logs"]}),a.jsxs(Q,{size:"sm",className:"gap-1.5 text-xs",onClick:()=>u(!0),children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," Create Chat Flow"]})]})]}),a.jsx("div",{className:"w-full max-w-4xl flex items-center gap-1 mb-6",children:A.map(I=>a.jsx("button",{onClick:()=>l(I.id),className:L("px-3 py-1.5 rounded-full text-xs font-medium transition-all",o===I.id?"bg-primary/10 text-primary border border-primary/20":"bg-card border text-muted-foreground hover:text-foreground hover:border-primary/20"),children:I.label},I.id))}),a.jsxs("div",{className:"w-full max-w-4xl space-y-2",children:[r&&a.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Loading..."}),!r&&P.length===0&&a.jsxs("div",{className:"text-center py-20",children:[a.jsx(hr,{className:"w-12 h-12 text-muted-foreground/20 mx-auto mb-4"}),a.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"No workflows yet"}),a.jsx("p",{className:"text-sm text-muted-foreground mb-6 max-w-sm mx-auto",children:"Create your first chat flow to automate conversations and actions."}),a.jsxs("div",{className:"flex items-center justify-center gap-3",children:[a.jsxs(Q,{size:"sm",className:"gap-1.5",onClick:()=>u(!0),children:[a.jsx(Kr,{className:"w-3.5 h-3.5"})," Create Chat Flow"]}),a.jsxs(Q,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(!0),children:[a.jsx(Dn,{className:"w-3.5 h-3.5"})," Generate with AI"]}),a.jsxs(Q,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(!0),children:[a.jsx(Wg,{className:"w-3.5 h-3.5"})," Browse Templates"]})]})]}),P.map(I=>a.jsx("div",{onClick:()=>k(I.id),className:"bg-card border rounded-xl p-4 hover:shadow-md hover:border-primary/20 transition-all cursor-pointer group",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:L("w-10 h-10 rounded-lg flex items-center justify-center shrink-0",I.published?"bg-emerald-500/10 text-emerald-600":"bg-primary/10 text-primary"),children:a.jsx(hr,{className:"w-5 h-5"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:"font-semibold text-foreground text-sm",children:I.name}),a.jsx(Ge,{variant:"outline",className:L("text-[10px] px-1.5 py-0 capitalize",_(I.status)),children:I.status})]}),I.description&&a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:I.description}),a.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[11px] text-muted-foreground flex-wrap",children:[a.jsxs("span",{className:"flex items-center gap-1",children:[E(I.trigger_type)," ",I.trigger_type.replace("_"," ")]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Lr,{className:"w-3 h-3"})," ",new Date(I.updated_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})]}),a.jsxs("span",{children:[I.nodes.length," nodes"]}),a.jsxs("span",{children:[I.runs_count," runs"]}),a.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground
8273/50",children:["v",I.version]})]})]}),a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,onClick:D=>D.stopPropagation(),children:a.jsx(Q,{variant:"ghost",size:"icon",className:"h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(Cw,{className:"w-4 h-4"})})}),a.jsxs(Jl,{align:"end",onClick:D=>D.stopPropagation(),children:[a.jsxs(Qr,{onClick:()=>k(I.id),children:[a.jsx(uc,{className:"w-3.5 h-3.5 mr-2"})," Edit"]}),a.jsxs(Qr,{onClick:()=>T(I.id),children:[a.jsx(Oi,{className:"w-3.5 h-3.5 mr-2"})," Test"]}),a.jsxs(Qr,{onClick:()=>j(I.id),children:[a.jsx(Es,{className:"w-3.5 h-3.5 mr-2"})," Publish"]}),a.jsxs(Qr,{onClick:()=>N(I.id),children:[a.jsx(ai,{className:"w-3.5 h-3.5 mr-2"})," View Logs"]}),a.jsxs(Qr,{onClick:()=>w(I.id),children:[a.jsx(gs,{className:"w-3.5 h-3.5 mr-2"})," Duplicate"]}),a.jsxs(Qr,{onClick:()=>S(I.id),children:[a.jsx(aT,{className:"w-3.5 h-3.5 mr-2"})," Archive"]})]})]})]})},I.id))]}),c&&a.jsx(Cbe,{onClose:()=>u(!1),onCreated:C}),x&&y&&a.jsx(VM,{flowId:y,onClose:()=>{g(!1),v()}})]})}function Fbe({connector:e,projectId:t,open:r,onOpenChange:n,onConnected:s}){const[i,o]=m.useState("overview"),[l,c]=m.useState({}),[u,d]=m.useState({}),[p,h]=m.useState(!1),[f,x]=m.useState("saving-keys"),[g,y]=m.useState(null),b=m.useCallback(()=>{o("overview"),c({}),d({}),h(!1),x("saving-keys"),y(null)},[]),v=j=>{j||b(),n(j)};if(!e)return null;const k=e.secrets.filter(j=>j.required!==!1).every(j=>(l[j.key]||"").trim().length>0),N=async()=>{if(!t){y("No project selected");return}h(!0),o("deploying"),y(null);try{x("saving-keys");const j=e.secrets.filter(A=>(l[A.key]||"").trim()).map(A=>({key:A.key,value:l[A.key].trim()}));if(j.length>0){const{error:A}=await G.functions.invoke("store-secret",{body:{projectId:t,secrets:j}});if(A)throw new Error("Failed to save credentials: "+A.message)}x("deploying-function");const w=`${e.id}-connector`,{data:S}=await G.from("project_settings").select("capabilities").eq("project_id",t).single(),T=(S==null?void 0:S.capabilities)||{},C=T._connectors||{};C[e.id]={connectedAt:new Date().toISOString(),functionName:w,secrets:j.map(A=>A.key),status:"active"},await G.from("project_settings").update({capabilities:{...T,_connectors:C}}).eq("project_id",t),x("testing"),await new Promise(A=>setTimeout(A,800)),x("done"),o("done"),W.success(`${e.name} connected successfully!`),s(e.id)}catch(j){y(j.message||"Setup failed"),x("error"),W.error("Connection setup failed")}finally{h(!1)}};return a.jsx(yo,{open:r,onOpenChange:v,children:a.jsxs(Fi,{className:"max-w-lg",children:[a.jsx(Bi,{children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-secondary flex items-center justify-center text-xl",children:e.icon}),a.jsxs("div",{children:[a.jsxs(La,{className:"text-lg",children:["Connect ",e.name]}),a.jsx(ol,{className:"text-xs",children:e.description})]})]})}),a.jsx("div",{className:"flex items-center gap-2 py-2",children:["overview","credentials","deploying","done"].map((j,w)=>a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:L("w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold transition-all",i===j?"bg-primary text-primary-foreground":["overview","credentials","deploying","done"].indexOf(i)>w?"bg-primary/20 text-primary":"bg-muted text-muted-foreground"),children:["overview","credentials","deploying","done"].indexOf(i)>w?a.jsx(Wn,{className:"w-3 h-3"}):w+1}),w<3&&a.jsx("div",{className:"w-8 h-0.5 bg-muted rounded"})]},j))}),i==="overview"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"p-3 rounded-lg bg-secondary/50 space-y-2",children:[a.jsxs("h4",{className:"text-xs font-semibold text-foreground flex items-center gap-1.5",children:[a.jsx(hr,{className:"w-3.5 h-3.5 text-primary"})," What you'll get"]}),a.jsx("ul",{className:"space-y-1.5",children:e.endpoints.map(j=>a.jsxs("li",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[a.jsx(Ge,{variant:"outline",className:"text-[9px] h-4 font-mono",children:j.method}),a.jsx("span",{children:j.description})]},j.path))})]}),a.jsxs("div",{className:"p-3 rounded-lg bg-secondary/50 space-y-2",children:[a.jsx("h4",{className:"text-xs font-semibold text-foreground",children:"Setup steps"}),a.jsx("ol",{className:"space-y-1",children:e.setupSteps.map((j,w)=>a.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[a.jsxs("span",{className:"font-bold text-foreground shrink-0",children:[w+1,"."]}),a.jsx("span",{children:j})]},w))})]}),e.docsUrl&&a.jsxs("a",{href:e.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-xs text-primary hover:underline",children:[a.jsx(Is,{className:"w-3 h-3"})," View ",e.name," documentation"]}),a.jsxs(Q,{className:"w-full gap-2",onClick:()=>o("credentials"),children:["Continue ",a.jsx(Sh,{className:"w-4 h-4"})]})]}),i==="credentials"&&a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"px-3 py-2 bg-amber-500/10 border border-amber-500/20 rounded-lg flex items-center gap-2",children:[a.jsx(os,{className:"w-4 h-4 text-amber-600 shrink-0"}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Credentials are encrypted and stored in your project's secure vault"})]}),e.secrets.map(j=>a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("label",{className:"flex items-center gap-1.5 text-xs font-semibold text-foreground",children:[a.jsx(Bs,{className:"w-3 h-3 text-muted-foreground"}),j.label,j.required!==!1&&a.jsx("span",{className:"text-destructive",children:"*"})]}),a.jsx("p",{className:"text-[11px] text-muted-foreground",children:j.description}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:u[j.key]?"text":"password",value:l[j.key]||"",onChange:w=>c(S=>({...S,[j.key]:w.target.value})),placeholder:j.placeholder,className:L("w-full h-9 px-3 pr-9 rounded-lg border bg-background text-xs font-mono","placeholder:text-muted-foreground
8273/50 focus:outline-none focus:ring-2 focus:ring-primary/30"),autoComplete:"off",spellCheck:!1,"data-1p-ignore":!0}),a.jsx("button",{type:"button",onClick:()=>d(w=>({...w,[j.key]:!w[j.key]})),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:u[j.key]?a.jsx(ku,{className:"w-3.5 h-3.5"}):a.jsx(ys,{className:"w-3.5 h-3.5"})})]}),j.docsUrl&&a.jsxs("a",{href:j.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-primary hover:underline flex items-center gap-1",children:[a.jsx(Is,{className:"w-2.5 h-2.5"})," Where to find this"]})]},j.key)),g&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-destructive",children:[a.jsx(is,{className:"w-3.5 h-3.5 shrink-0"}),a.jsx("span",{children:g})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Q,{variant:"outline",className:"flex-1",onClick:()=>o("overview"),children:"Back"}),a.jsxs(Q,{className:"flex-1 gap-2",onClick:N,disabled:!k||p,children:[a.jsx(Ma,{className:"w-4 h-4"})," Connect & Deploy"]})]})]}),i==="deploying"&&a.jsxs("div",{className:"space-y-4 py-4",children:[[{key:"saving-keys",label:"Saving credentials securely"},{key:"deploying-function",label:"Deploying edge function"},{key:"testing",label:"Testing connection"}].map(j=>{const w=["saving-keys","deploying-function","testing","done"],S=w.indexOf(f),T=w.indexOf(j.key),C=S>T,A=S===T,P=f==="error"&&A;return a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:L("w-7 h-7 rounded-full flex items-center justify-center transition-all",C?"bg-primary/15 text-primary":A?P?"bg-destructive/15 text-destructive":"bg-primary/10":"bg-muted text-muted-foreground"),children:C?a.jsx(mn,{className:"w-4 h-4"}):A?P?a.jsx(is,{className:"w-4 h-4"}):a.jsx(ze,{className:"w-4 h-4 animate-spin text-primary"}):a.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/30"})}),a.jsx("span",{className:L("text-sm",C||A?"text-foreground":"text-muted-foreground"),children:j.label})]},j.key)}),g&&a.jsxs("div",{className:"p-3 rounded-lg bg-destructive/10 border border-destructive/20",children:[a.jsx("p",{className:"text-xs text-destructive",children:g}),a.jsx(Q,{variant:"outline",size:"sm",className:"mt-2 h-7 text-xs",onClick:()=>{y(null),o("credentials")},children:"Try again"})]})]}),i==="done"&&a.jsxs("div",{className:"text-center py-6 space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/15 flex items-center justify-center",children:a.jsx(mn,{className:"w-8 h-8 text-primary"})}),a.jsxs("div",{children:[a.jsxs("h3",{className:"text-lg font-bold text-foreground",children:[e.name," Connected!"]}),a.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Edge function deployed. You can now use ",e.name," in your app."]})]}),a.jsxs("div",{className:"p-3 rounded-lg bg-secondary/50 text-left",children:[a.jsx("p",{className:"text-[11px] font-semibold text-foreground mb-2",children:"Usage in your app:"}),a.jsx("pre",{className:"text-[10px] text-muted-foreground font-mono bg-background/50 p-2 rounded overflow-x-auto",children:`import { supabase } from '@/integrations/supabase/client';
8274
8275const { data } = await supabase.functions
8276  .invoke('${e.id}-connector', {
8277    body: { /* your payload */ }
8278  });`})]}),a.jsx(Q,{className:"w-full",onClick:()=>v(!1),children:"Done"})]})]})})}const Bbe=()=>{const e=K1.map(n=>({id:n.id,name:n.name,description:n.description,icon:n.icon,category:n.category.charAt(0).toUpperCase()+n.category.slice(1),status:"available",docsUrl:n.docsUrl,connector:n})),t=[{id:"supabase",name:"Supabase",description:"Database, auth, storage & realtime backend",icon:"⚡",category:"Backend",status:"connected"},{id:"vercel-deploy",name:"Vercel",description:"Deploy & host your applications",icon:"▲",category:"Devops",status:"connected"},{id:"github-deploy",name:"GitHub",description:"Push code & manage repos",icon:"🐙",category:"Devops",status:"available"}],r=[{id:"zapier",name:"Zapier",description:"Connect to 5000+ apps via triggers",icon:"⚡",category:"Automation",status:"coming-soon"},{id:"notion",name:"Notion",description:"Sync databases & manage content",icon:"📝",category:"Data",status:"coming-soon"},{id:"google-sheets",name:"Google Sheets",description:"Read & write spreadsheet data",icon:"📊",category:"Data",status:"coming-soon"},{id:"salesforce",name:"Salesforce",description:"CRM lead & contact management",icon:"☁️",category:"Crm",status:"coming-soon"},{id:"hubspot",name:"HubSpot",description:"Marketing & sales automation",icon:"🟠",category:"Crm",status:"coming-soon"}];return[...t,...e,...r]},dp=Bbe(),Ube=["All",...Array.from(new Set(dp.map(e=>e.category)))],zbe={connected:{badge:"bg-emerald-500/15 text-emerald-600 border-emerald-500/20",label:"Connected"},available:{badge:"bg-primary/10 text-primary border-primary/20",label:"Available"},"coming-soon":{badge:"bg-muted text-muted-foreground border-muted",label:"Soon"}};function qbe(){const[e,t]=m.useState(""),[r,n]=m.useState("All"),[s,i]=m.useState("all"),[o,l]=m.useState(new Set),[c,u]=m.useState(!1),[d,p]=m.useState(null),[h,f]=m.useState(!1),[x,g]=m.useState(!1),{project:y}=gn(),{user:b}=Us(),v=(y==null?void 0:y.id)||null;m.useEffect(()=>{const P=()=>{g(!!Dh(b==null?void 0:b.id).token)};return P(),window.addEventListener("focus",P),window.addEventListener("storage",P),()=>{window.removeEventListener("focus",P),window.removeEventListener("storage",P)}},[b==null?void 0:b.id]),m.useEffect(()=>{let P=!1;async function E(){var B;if(!v){l(new Set);return}u(!0);const{data:_,error:I}=await G.from("project_settings").select("capabilities").eq("project_id",v).maybeSingle();if(P)return;if(I){console.warn("Failed to load integration settings",I),u(!1);return}const D=((B=_==null?void 0:_.capabilities)==null?void 0:B._connectors)||{},M=Object.entries(D).filter(([,$])=>($==null?void 0:$.status)==="active").map(([$])=>$);x&&M.push("github-deploy"),l(new Set(M)),u(!1)}return E(),()=>{P=!0}},[v,x]);const k=P=>o.has(P.id)?"connected":P.status,N=dp.filter(P=>{const E=!e.trim()||P.name.toLowerCase().includes(e.toLowerCase())||P.description.toLowerCase().includes(e.toLowerCase()),_=r==="All"||P.category===r,I=k(P);return E&&_&&(s==="all"||I===s)}),j=dp.filter(P=>k(P)==="connected").length,w=dp.filter(P=>k(P)==="available").length,S=m.useMemo(()=>K1.filter(P=>P.endpoints.length>0||P.secrets.length>0).length,[]),T=P=>{const E=k(P);if(P.status!=="coming-soon"){if(E==="connected"){W.info(`${P.name} is already connected`);return}P.connector?(p(P.connector),f(!0)):W.info(`${P.name} setup coming soon`)}},C=P=>{l(E=>new Set([...E,P]))},A=P=>{if(P.connector){p(P.connector),f(!0);return}const E=P.id==="supabase"?"Open the Cloud tab to manage Supabase database, auth, storage, and edge functions.":P.id.includes("github")?"Open the GitHub tab to manage repository sync, auto-push, and PR settings.":P.id.includes("vercel")?"Open Cloud or Publish to manage preview and production deploys.":`${P.name} settings are managed from its workspace tab.`;W.info(E)};return a.jsx("div",{className:"flex-1 overflow-y-auto relative z-10",children:a.jsxs("div",{className:"mx-auto w-full max-w-6xl px-4 py-8 md:py-10",children:[a.jsxs("div",{className:"mb-6 grid gap-4 lg:grid-cols-[1fr_340px]",children:[a.jsxs("div",{className:"rounded-2xl border bg-card/80 p-6 shadow-sm",children:[a.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[a.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:a.jsx(Ma,{className:"h-6 w-6"})}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold tracking-tight text-foreground md:text-3xl",children:"Integrations"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect APIs, deploy targets, data sources, and MCP tools for this project."})]})]}),a.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[a.jsxs("div",{className:"rounded-xl border bg-background/70 p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[a.jsx(el,{className:"h-4 w-4 text-primary"})," Connected"]}),a.jsx("div",{className:"mt-2 text-2xl font-semibold",children:j})]}),a.jsxs("div",{className:"rounded-xl border bg-background/70 p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[a.jsx(hr,{className:"h-4 w-4 text-primary"})," Available"]}),a.jsx("div",{className:"mt-2 text-2xl font-semibold",children:w})]}),a.jsxs("div",{className:"rounded-xl border bg-background/70 p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[a.jsx(f6,{className:"h-4 w-4 text-primary"})," MCP-ready"]}),a.jsx("div",{className:"mt-2 text-2xl font-semibold",children:S})]})]})]}),a.jsxs("div",{className:"rounded-2xl border bg-gradient-to-br from-primary/10 via-card to-card p-5 shadow-sm",children:[a.jsxs("div",{className:"mb-3 flex items-center gap-2 text-sm font-semibold text-foreground",children:[a.jsx(I$,{className:"h-4 w-4 text-primary"}),"Chat-aware integrations"]}),a.jsx("p",{className:"text-sm leading-6 text-muted-foreground",children:"When a prompt mentions Stripe, email, maps, OpenAI, or another listed service, Studio Jungle now surfaces the matching connector in chat and keeps secrets server-side."}),a.jsxs("div",{className:"mt-4 rounded-xl border bg-background/70 p-3 text-xs text-muted-foreground",children:[a.jsx("span",{className:"font-medium text-foreground",children:"MCP:"})," add MCP servers in the workspace MCP tab, then chat can call their tools during builds."]})]})]}),a.jsx("div",{className:"mb-4 flex w-full items-center gap-3",children:a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[a.jsxs("button",{onClick:()=>i("all"),className:L("flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all border",s==="all"?"bg-primary/10 text-primary border-primary/20":"text-muted-foreground border-transparent hover:text-foreground"),children:["All (",dp.length,")"]}),a.jsxs("button",{onClick:()=>i("connected"),className:L("flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all border",s==="connected"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":"text-muted-foreground border-transparent hover:text-foreground"),children:[a.jsx(Wn,{className:"w-3 h-3"}),"Connected (",j,")"]}),a.jsxs("button",{onClick:()=>i("available"),className:L("flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all border",s==="available"?"bg-primary/10 text-primary border-primary/20":"text-muted-foreground border-transparent hover:text-foreground"),children:[a.jsx(hr,{className:"w-3 h-3"}),"Available (",w,")"]})]})}),a.jsx("div",{className:"mb-4 flex w-full items-center gap-3",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}
8278),a.jsx(Cn,{value:e,onChange:P=>t(P.target.value),placeholder:"Search integrations...",className:"pl-9"})]})}),a.jsx("div",{className:"mb-6 flex w-full items-center gap-1.5 flex-wrap",children:Ube.map(P=>a.jsx("button",{onClick:()=>n(P),className:L("px-3 py-1.5 rounded-full text-xs font-medium transition-all",r===P?"bg-primary/10 text-primary border border-primary/20":"bg-card border text-muted-foreground hover:text-foreground hover:border-primary/20"),children:P},P))}),c&&a.jsx("div",{className:"mb-4 rounded-xl border bg-card px-4 py-3 text-sm text-muted-foreground",children:"Loading saved integration state..."}),a.jsx("div",{className:"grid w-full grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3",children:N.map(P=>{var M,B;const E=k(P),_=zbe[E],I=((M=P.connector)==null?void 0:M.endpoints.length)||0,D=((B=P.connector)==null?void 0:B.secrets.length)||0;return a.jsxs("div",{className:L("bg-card border rounded-2xl p-4 transition-all group shadow-sm",E==="coming-soon"?"opacity-60":"hover:shadow-md hover:border-primary/25"),children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-11 h-11 rounded-xl bg-secondary flex items-center justify-center text-lg shrink-0",children:P.icon}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:"font-semibold text-foreground text-sm",children:P.name}),a.jsx("span",{className:L("text-[10px] px-1.5 py-0.5 rounded-full border font-medium",_.badge),children:_.label})]}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:P.description}),a.jsxs("div",{className:"flex items-center gap-2 mt-2.5 flex-wrap",children:[a.jsx("span",{className:"text-[10px] text-muted-foreground bg-secondary px-2 py-0.5 rounded-full",children:P.category}),D>0&&a.jsxs("span",{className:"text-[10px] text-muted-foreground bg-secondary px-2 py-0.5 rounded-full inline-flex items-center gap-1",children:[a.jsx(Ep,{className:"h-3 w-3"})," ",D," secrets"]}),I>0&&a.jsxs("span",{className:"text-[10px] text-muted-foreground bg-secondary px-2 py-0.5 rounded-full inline-flex items-center gap-1",children:[a.jsx(b6,{className:"h-3 w-3"})," ",I," endpoints"]}),E==="connected"&&a.jsxs("span",{className:"text-[10px] text-emerald-600 flex items-center gap-1",children:[a.jsx(Wn,{className:"w-3 h-3"})," Active"]})]})]})]}),E!=="coming-soon"&&a.jsxs("div",{className:"flex items-center gap-2 mt-3 pt-3 border-t",children:[E==="available"?a.jsxs(Q,{size:"sm",variant:"default",className:"h-7 text-xs flex-1 gap-1",onClick:()=>T(P),children:[a.jsx(Ma,{className:"w-3 h-3"})," Connect"]}):a.jsxs(Q,{size:"sm",variant:"outline",className:"h-7 text-xs flex-1 gap-1",onClick:()=>A(P),children:[a.jsx(ni,{className:"w-3 h-3"})," Settings"]}),P.docsUrl&&a.jsx(Q,{size:"sm",variant:"ghost",className:"h-7 text-xs gap-1 text-muted-foreground",asChild:!0,children:a.jsxs("a",{href:P.docsUrl,target:"_blank",rel:"noopener noreferrer",children:[a.jsx(Is,{className:"w-3 h-3"})," Docs"]})})]})]},P.id)})}),N.length===0&&a.jsxs("div",{className:"mt-8 rounded-2xl border bg-card p-10 text-center",children:[a.jsx(Ma,{className:"mx-auto mb-3 h-8 w-8 text-muted-foreground"}),a.jsx("h3",{className:"font-semibold",children:"No integrations found"}),a.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Try another search or category filter."})]}),a.jsx(Fbe,{connector:d,projectId:v,open:h,onOpenChange:f,onConnected:C})]})})}function Hbe({onOpenProjectCloud:e}){const t=il(),r=(t==null?void 0:t.projects)??[],n=t==null?void 0:t.switchProject,[s,i]=m.useState([]),[o,l]=m.useState([]),[c,u]=m.useState(!0);m.useEffect(()=>{let x=!1;if(r.length===0){i([]),l([]),u(!1);return}return u(!0),(async()=>{const g=r.map(N=>N.id),[{data:y,error:b},{data:v,error:k}]=await Promise.all([G.from("project_cloud_config").select("project_id, backend_mode, region, vercel_domain, vercel_last_deploy_at, vercel_last_deploy_status, ai_cloud_access").in("project_id",g),G.from("cloud_deployments").select("project_id, slug, status, url, updated_at, current_version").in("project_id",g).neq("status","deleted")]);x||(b&&console.warn("[cloud-overview] configs fetch failed:",b.message),k&&console.warn("[cloud-overview] deployments fetch failed:",k.message),i(y||[]),l(v||[]),u(!1))})(),()=>{x=!0}},[r]);const d=m.useMemo(()=>{const x=new Map;for(const g of s)x.set(g.project_id,g);return x},[s]),p=m.useMemo(()=>{const x=new Map;for(const g of o)x.set(g.project_id,g);return x},[o]),h=m.useMemo(()=>{const x=s.filter(j=>j.backend_mode&&j.backend_mode!=="unset").length,g=s.filter(j=>j.backend_mode==="byos").length,y=s.filter(j=>j.backend_mode==="studiojungle").length,b=new Set;for(const j of s)j.vercel_domain&&b.add(j.project_id);for(const j of o)j.status==="active"&&b.add(j.project_id);const v=new Map;for(const j of s)j.region&&v.set(j.region,(v.get(j.region)??0)+1);let k="—",N="no projects yet";if(v.size===1){const[j]=v.keys();k=j,N="all projects"}else if(v.size>1){const j=[...v.entries()].sort((w,S)=>S[1]-w[1]);k=j[0][0],N=`${j[0][1]} of ${s.length} · ${v.size} regions total`}return{total:r.length,connected:x,byos:g,platform:y,deployed:b.size,regionLabel:k,regionSub:N}},[s,o,r.length]),f=async x=>{if(e){e(x);return}n&&await n(x)};return a.jsx("div",{className:"h-full overflow-y-auto bg-background",children:a.jsxs("div",{className:"max-w-5xl mx-auto px-6 py-8 space-y-8",children:[a.jsx("div",{className:"flex items-start justify-between gap-4",children:a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl sm:text-2xl font-semibold tracking-tight",children:"Cloud"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1.5 max-w-xl",children:"Manage hosting, databases, and deploys across all your projects."})]})}),c?a.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[a.jsx(ze,{className:"w-5 h-5 animate-spin mr-2"}),"Loading your cloud projects…"]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[a.jsx(Jf,{label:"Projects",value:h.total,icon:Hn}),a.jsx(Jf,{label:"Cloud-connected",value:h.connected,sub:`${h.platform} managed · ${h.byos} self-hosted`,icon:Ma}),a.jsx(Jf,{label:"Deployed",value:h.deployed,sub:h.deployed>0?"live URLs":"none yet",icon:Br}),a.jsx(Jf,{label:"Region",value:h.regionLabel,sub:h.regionSub,icon:sa,valueClass:"text-base font-mono"})]}),a.jsxs("section",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h2",{className:"text-[15px] font-semibold tracking-tight",children:"Your projects"}),a.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums",children:[r.length," total"]})]}),r.length===0?a.jsxs("div",{className:"rounded-2xl border border-dashed bg-secondary/20 p-8 text-center",children:[a.jsx(ya,{className:"w-8 h-8 mx-auto text-muted-foreground
8278/50 mb-2"}),a.jsx("p",{className:"text-sm font-medium text-foreground",children:"No projects yet"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Create your first project from the Home tab to start hosting."})]}):a.jsx("div",{className:"rounded-xl border bg-card overflow-hidden divide-y",children:r.map(x=>{const g=d.get(x.id),y=p.get(x.id),b=g&&g.backend_mode!=="unset",v=(g==null?void 0:g.vercel_domain)||(y!=null&&y.slug?`${y.slug}.studiojungle.dev`:null),k=(g==null?void 0:g.vercel_last_deploy_at)||(y==null?void 0:y.updated_at),N=!!v;return a.jsxs("button",{type:"button",onClick:()=>f(x.id),className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-secondary/40 transition-colors text-left group",children:[a.jsx("span",{className:L("w-2 h-2 rounded-full shrink-0",N?"bg-emerald-500":b?"bg-amber-500":"bg-muted-foreground/40"),title:N?"Live":b?"Cloud connected, not deployed":"Not provisioned"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-[13px] font-medium text-foreground truncate",children:x.name}),(g==null?void 0:g.backend_mode)==="byos"&&a.jsx("span",{className:"text-[9px] uppercase tracking-wider font-semibold px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-700",children:"Self-hosted"}),(g==null?void 0:g.backend_mode)==="studiojungle"&&a.jsx("span",{className:"text-[9px] uppercase tracking-wider font-semibold px-1.5 py-0.5 rounded bg-primary/10 text-primary",children:"Managed"}),N&&a.jsx("span",{className:"text-[9px] uppercase tracking-wider font-semibold px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-700",children:"Live"})]}),a.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-[11px] text-muted-foreground",children:[v?a.jsxs("span",{className:"flex items-center gap-1 truncate",children:[a.jsx(Br,{className:"w-3 h-3 shrink-0"}),a.jsx("span",{className:"truncate",children:v})]}):b?a.jsx("span",{className:"text-muted-foreground/70",children:"No deploy yet"}):a.jsx("span",{className:"text-muted-foreground/70",children:"Not provisioned"}),k&&a.jsxs("span",{className:"shrink-0",children:["· updated ",$s(rx(k),{addSuffix:!0})]})]})]}),a.jsx(ia,{className:"w-4 h-4 text-muted-foreground/50 group-hover:text-foreground transition-colors shrink-0"})]},x.id)})})]})]})]})})}function Jf({label:e,value:t,sub:r,icon:n,valueClass:s}){return a.jsxs("div",{className:"rounded-xl border bg-card p-3.5",children:[a.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[a.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:e}),a.jsx(n,{className:"w-3.5 h-3.5 text-muted-foreground/70"})]}),a.jsx("p",{className:L("text-2xl font-semibold tabular-nums tracking-tight",s),children:t}),r&&a.jsx("p",{className:"text-[10.5px] text-muted-foreground mt-0.5",children:r})]})}function Wbe(){return a.jsx("div",{className:"h-full overflow-y-auto bg-background",children:a.jsxs("div",{className:"max-w-5xl mx-auto px-6 py-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center shrink-0",children:a.jsx(Ai,{className:"w-5 h-5 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("h1",{className:"text-xl sm:text-2xl font-semibold tracking-tight",children:"Common Brand"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1.5 max-w-2xl",children:"Your default colors, fonts, voice, and rules. The AI uses these whenever a project doesn't have its own brand set."})]})]}),a.jsxs("div",{className:"mt-5 rounded-xl border bg-secondary/30 p-4",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:"How the AI picks a brand"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 text-[13px]",children:[a.jsx("span",{className:"px-3 py-1.5 rounded-md bg-card border font-medium",children:"Project's own brand"}),a.jsx(qb,{className:"w-3.5 h-3.5 text-muted-foreground sm:rotate-[-90deg] mx-2 shrink-0"}),a.jsxs("span",{className:"px-3 py-1.5 rounded-md bg-card border font-medium",children:[a.jsx("span",{className:"text-primary",children:"Common Brand"})," ",a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground
8278/70 ml-1",children:"(this page)"})]}),a.jsx(qb,{className:"w-3.5 h-3.5 text-muted-foreground sm:rotate-[-90deg] mx-2 shrink-0"}),a.jsx("span",{className:"px-3 py-1.5 rounded-md bg-card border font-medium text-muted-foreground",children:"Generic defaults"})]}),a.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2 leading-relaxed",children:["Mark a brand as ",a.jsx("span",{className:"font-medium text-foreground",children:'"Set as default"'})," below to make it your Common Brand. A project's own brand always wins over this one."]})]})]}),a.jsx(kE,{hideOwnHeader:!0})]})})}const T_=[{id:"web",label:"Full Stack App",icon:oT,helper:"Best for dashboards, SaaS apps, marketplaces, portals, tools, auth, APIs, and databases."},{id:"mobile",label:"Mobile App",icon:Nc,helper:"Best for phone-first apps with bottom navigation, touch flows, native-style screens, and app-like previews."},{id:"landing",label:"Landing Page",icon:Br,helper:"Best for public marketing pages with hero, features, social proof, pricing, FAQ, CTA, and SEO."}],E_={web:[{icon:no,label:"SaaS Dashboard",prompt:"Build a full-stack SaaS dashboard with user authentication, analytics charts, KPI cards, sidebar navigation, data tables with filters, and a settings page."},{icon:Zd,label:"E-commerce Platform",prompt:"Create a full-stack e-commerce platform with product catalog, shopping cart, checkout flow, order management, user accounts, and admin dashboard."},{icon:si,label:"Project Management Tool",prompt:"Build a full-stack project management app with kanban boards, task lists, team collaboration, file uploads, notifications, and reporting dashboard."},{icon:hr,label:"Social Media App",prompt:"Create a full-stack social media application with user profiles, news feed, post creation with images, likes, comments, follow system, and real-time notifications."}],mobile:[{icon:Nc,label:"Fitness Tracker",prompt:"Build a mobile fitness tracking app with workout logging, exercise library with animations, progress charts, daily goals, streak tracking, bottom tab navigation, and push notifications."},{icon:no,label:"Food Delivery App",prompt:"Create a mobile food delivery app with restaurant listings, menu browsing with images, cart system, real-time order tracking with maps, payment integration, and user profile."},{icon:Zd,label:"E-commerce App",prompt:"Build a mobile shopping app with product catalog, category filters, wishlist, cart with animations, Stripe checkout, order history, and push notification updates."},{icon:hr,label:"Chat Messenger",prompt:"Create a mobile messaging app with conversation list, real-time chat, media sharing, user profiles, online status, and notifications."}],landing:[{icon:no,label:"SaaS Landing Page",prompt:"Build a modern SaaS landing page with an animated hero section, feature showcase grid, pricing table with toggle, testimonials carousel, FAQ accordion, CTA sections, and footer."},{icon:hr,label:"Product Launch Page",prompt:"Create a product launch landing page with countdown timer, product showcase with images, feature highlights, early access signup form, social proof section, and press mentions."},{icon:si,label:"Agency Website",prompt:"Build a creative agency landing page with portfolio grid, services section, team members, client logos, case studies, contact form, and smooth scroll animations."},{icon:Zd,label:"App Download Page",prompt:"Create a mobile app download landing page with device mockups, feature walkthrough, app screenshots carousel, ratings/reviews, download buttons for iOS and Android, and FAQ."}],wordpress:[{icon:no,label:"Photography Portfolio",prompt:"A photography portfolio site with a full-width gallery, an about page, and a contact page."},{icon:Zd,label:"Coffee Shop",prompt:"A coffee shop website with a menu, opening hours, our story, and a contact page."},{icon:l6,label:"Tech Blog",prompt:"A personal tech blog with a clean theme and three sample posts about web development."},{icon:si,label:"Small Business",prompt:"A small business website for a local plumber with services, testimonials, and a quote request page."}]};function Vbe(e,t){const r=e.trim(),n=/https?:\/\/[^\s)]+/i.test(r),s=/\b(website|web\s*site|site|landing\s*page|homepage|marketing\
8278s*page|public\s*page)\b/i.test(r),i=/\b(like|similar\s+to|clone|inspired\s+by|reference)\b/i.test(r)&&n,o=/\b(full[\s-]*stack|backend|database|db|schema|auth|login|signup|sign\s*up|account|admin|dashboard|portal|crm|api|endpoint|webhook|stripe|payment|billing|subscription|real[\s-]*time|crud)\b/i.test(r);return t==="web"?["BUILD TYPE: FULL STACK APP.","Create the actual usable app, not only a marketing page. Include complete navigation, realistic data, core workflows, responsive layouts, empty/loading/error states, and clean reusable components. If the request implies persistent records, users, client profiles, invoices, payments, reporting, roles, or protected data, treat backend/auth/database as clearly needed and include the minimal schema/auth/API layer in this build instead of offering it only as a next step.","",`USER REQUEST: ${r}`].join(`
8279`):t==="landing"?["BUILD TYPE: LANDING PAGE / MARKETING SITE.","Create a polished public-facing landing page with hero, features, CTA, and contact. Frontend-only with seeded mock data — no backend unless explicitly requested.","",`USER REQUEST: ${r}`].join(`
8280`):t!=="mobile"&&!o&&(s||i)?["BUILD TYPE: WEBSITE / PUBLIC WEB EXPERIENCE.","Use the reference URL only for visual direction, information architecture, and expected public workflows. Build a polished responsive public website first, not a full-stack dashboard/backend. If the reference contains search, booking, checkout, account, or admin flows, render them as interactive frontend mock UI with realistic seeded data unless the user explicitly asks for real auth, database, payments, APIs, or admin tooling.","",`USER REQUEST: ${r}`].join(`
8281`):t==="mobile"?["BUILD TYPE: MOBILE APP.","Create a high-end phone-first app experience, not a desktop web dashboard and not a static poster. Studio Jungle already wraps Mobile Preview in device chrome, so the generated preview must render the actual app screen only: no second phone frame, no fake device shell, no code-structure-only screen unless the user explicitly asks for architecture docs.","The app must feel clickable: bottom tab navigation with at least 3-4 screens, tappable cards that open detail views, one primary action flow (FAB/CTA -> form/modal -> saved state/toast), realistic seeded data, visible state changes, and loading/empty/error/offline states where relevant. Use 44px+ tap targets, thumb-friendly controls, touch-safe forms, full-width cards, and no desktop sidebars, breadcrumbs, hover menus, or wide tables.","If native source is generated, include React Native/Expo-ready files in the file tree plus a matching interactive HTML preview for Studio. The preview should mirror the native app flow and remain usable with normal clicks inside the phone viewport. Every local import must resolve: if App.tsx imports ./screens/MapScreen or ./components/CafeSheet, emit those files in the same response; otherwise keep the prototype self-contained in App.tsx and remove the imports.","",`USER REQUEST: ${r}`].join(`
8282`):["BUILD TYPE: FULL STACK APP.","Create the actual usable app, not only a marketing page. Include complete navigation, realistic data, core workflows, responsive layouts, empty/loading/error states, and clean reusable components. If the request implies persistent records, users, client profiles, invoices, payments, reporting, roles, or protected data, treat backend/auth/database as clearly needed and include the minimal schema/auth/API layer in this build instead of offering it only as a next step.","",`USER REQUEST: ${r}`].join(`
8283`)}const I_=[{label:"Images",description:"Screenshots, logos, visual references",accept:"image/*",icon:ad},{label:"Documents",description:"PDF, DOCX, text briefs",accept:".pdf,.doc,.docx,.txt,.md",icon:kh},{label:"Slides",description:"Pitch decks, presentations, visual direction",accept:".ppt,.pptx",icon:h6},{label:"Data",description:"Sheets, CSV, JSON, XML",accept:".xls,.xlsx,.csv,.tsv,.json,.xml",icon:Pw},{label:"Audio",description:"Voice notes, interviews, recordings",accept:"audio/*",icon:s6},{label:"Video",description:"Walkthroughs, demos, clips",accept:"video/*",icon:E6},{label:"Code",description:"HTML, CSS, JS, TS, React files",accept:".html,.htm,.css,.js,.jsx,.ts,.tsx,.yaml,.yml",icon:sd}],O_=[{id:"home",label:"Home",icon:xm},{id:"projects",label:"My Projects",icon:cc},{id:"shared",label:"Shared with me",icon:Zl},{id:"integrations",label:"Integrations",icon:Ma},{id:"github",label:"GitHub import",icon:to},{id:"cloud",label:"Cloud",icon:ya},{id:"brand",label:"Brand",icon:Ai}],Gbe=["🌿","🍃","🌱","🪴","🌴","🍀","🌾","🌵","🦜","🌺","🪻","🦋"];function Kbe({accent:e,hash:t}){const r=t%3,n=e.includes("emerald")?"#10b981":e.includes("violet")?"#8b5cf6":e.includes("amber")?"#f59e0b":e.includes("sky")?"#0ea5e9":e.includes("lime")?"#84cc16":e.includes("rose")?"#f43f5e":"#10b981";return a.jsxs("div",{className:"absolute inset-0 flex items-end justify-center overflow-hidden pb-2",children:[a.jsx("div",{className:"absolute inset-0 opacity-30 mix-blend-overlay",style:{backgroundImage:"radial-gradient(circle at 30% 30%, white 0px, transparent 18px), radial-gradient(circle at 70% 60%, white 0px, transparent 14px)"}}),a.jsx("span",{className:"absolute bottom-2 left-3 right-3 h-px bg-foreground
8283/10"}),a.jsxs("svg",{viewBox:"0 0 100 60",className:"relative w-[78%] h-[72%]","aria-hidden":"true",children:[r===0&&a.jsxs("g",{stroke:n,strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[a.jsx("path",{d:"M30 52 Q28 36 32 22"}),a.jsx("path",{d:"M50 52 Q50 30 50 14"}),a.jsx("path",{d:"M70 52 Q72 38 68 26"}),a.jsx("ellipse",{cx:"32",cy:"22",rx:"6",ry:"3",fill:n,fillOpacity:"0.55",stroke:"none",transform:"rotate(-30 32 22)"}),a.jsx("ellipse",{cx:"50",cy:"14",rx:"7",ry:"3.2",fill:n,fillOpacity:"0.7",stroke:"none"}),a.jsx("ellipse",{cx:"68",cy:"26",rx:"6",ry:"3",fill:n,fillOpacity:"0.5",stroke:"none",transform:"rotate(30 68 26)"}),a.jsx("circle",{cx:"50",cy:"11",r:"1.6",fill:"#fff",fillOpacity:"0.8"})]}),r===1&&a.jsxs("g",{stroke:n,strokeWidth:"1.5",strokeLinecap:"round",fill:"none",children:[a.jsx("path",{d:"M50 52 L50 16"}),a.jsx("path",{d:"M50 44 Q40 40 35 30"}),a.jsx("path",{d:"M50 36 Q40 32 36 22"}),a.jsx("path",{d:"M50 28 Q42 26 40 18"}),a.jsx("path",{d:"M50 44 Q60 40 65 30"}),a.jsx("path",{d:"M50 36 Q60 32 64 22"}),a.jsx("path",{d:"M50 28 Q58 26 60 18"}),a.jsx("circle",{cx:"35",cy:"30",r:"1.6",fill:n,fillOpacity:"0.6",stroke:"none"}),a.jsx("circle",{cx:"36",cy:"22",r:"1.4",fill:n,fillOpacity:"0.5",stroke:"none"}),a.jsx("circle",{cx:"40",cy:"18",r:"1.2",fill:n,fillOpacity:"0.45",stroke:"none"}),a.jsx("circle",{cx:"65",cy:"30",r:"1.6",fill:n,fillOpacity:"0.6",stroke:"none"}),a.jsx("circle",{cx:"64",cy:"22",r:"1.4",fill:n,fillOpacity:"0.5",stroke:"none"}),a.jsx("circle",{cx:"60",cy:"18",r:"1.2",fill:n,fillOpacity:"0.45",stroke:"none"}),a.jsx("circle",{cx:"50",cy:"14",r:"2",fill:n,fillOpacity:"0.75",stroke:"none"})]}),r===2&&a.jsxs("g",{fill:n,stroke:n,strokeWidth:"0.8",strokeLinejoin:"round",children:[a.jsx("path",{d:"M35 52 Q22 40 26 22 Q34 16 42 22 Q44 40 35 52 Z",fillOpacity:"0.55"}),a.jsx("path",{d:"M65 52 Q78 38 74 20 Q66 14 58 22 Q56 40 65 52 Z",fillOpacity:"0.7"}),a.jsx("path",{d:"M50 52 Q50 30 54 18 Q50 14 46 18 Q50 30 50 52 Z",fillOpacity:"0.85"}),a.jsx("path",{d:"M35 50 Q32 38 30 26",stroke:"#ffffff",strokeOpacity:"0.5",fill:"none"}),a.jsx("path",{d:"M65 50 Q68 38 70 24",stroke:"#ffffff",strokeOpacity:"0.5",fill:"none"})]})]})]})}function Ybe({onStartBuild:e,onResumeProject:t,onStartWordPress:r}){var at,gt,$t,ue,je,ct,it,q,Nt;const n=il(),{project:s,projects:i,switchProject:o,createProject:l,deleteProject:c}=n??{project:null,projects:[],switchProject:async()=>{},createProject:async()=>null,deleteProject:async()=>{}},{captureHtmlThumbnail:u}=H1(),{signOut:d,session:p,user:h,emailVerified:f}=Us(),x=ld(),g=nd(),[y,b]=m.useState(""),[v,k]=m.useState("landing"),[N,j]=m.useState("claude-opus-4-8"),[w,S]=m.useState(()=>MI());m.useEffect(()=>{LI(w)},[w]);const[T,C]=m.useState([]),[A,P]=m.useState({}),[E,_]=m.useState("image/*,.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt,.md,.csv,.tsv,.json,.xml,.html,.css,.js,.jsx,.ts,.tsx,audio/*,video/*"),I=m.useRef(null),[D,M]=m.useState("home"),[B,$]=m.useState(!1),[K,R]=m.useState(!1),Y=m.useRef(!1),[Z,O]=m.useState({connected:!1,login:null,avatar:null}),[ne,oe]=m.useState(null),[he,ae]=m.useState(null),ve=m.useRef(new Set);m.useEffect(()=>{let U=!1;return(async()=>{const{fetchHomeSuggestions:Ne}=await ju(async()=>{const{fetchHomeSuggestions:Zt}=await import("./home-suggestions-IJ561fbD.js");return{fetchHomeSuggestions:Zt}},__vite__mapDeps([60,1,2,3,4,5])),Ft=await Ne(v);U||(oe(Ft.suggestions),ae(Ft.placeholder))})(),()=>{U=!0}},[v]),m.useEffect(()=>{const U=()=>{var Zt;const{token:Ne,user:Ft}=Dh((Zt=p==null?void 0:p.user)==null?void 0:Zt.id);O({connected:!!(Ne&&(Ft!=null&&Ft.login)),login:(Ft==null?void 0:Ft.login)||null,avatar:(Ft==null?void 0:Ft.avatar_url)||null})};return U(),window.addEventListener("storage",U),window.addEventListener("focus",U),()=>{window.removeEventListener("storage",U),window.removeEventListener("focus",U)}},[(at=p==null?void 0:p.user)==null?void 0:at.id]),m.useEffect(()=>{const U=Ke=>!!Ke&&Ke.startsWith("data:image/svg+xml"),Ne=i.slice(0,8).filter(Ke=>(!Ke.thumbnail_url||U(Ke.thumbnail_url))&&!ve.current.has(Ke.id)).slice(0,3);if(Ne.length===0)return;let Ft=!1;Ne.forEach(Ke=>ve.current.add(Ke.id));const Zt=Ke=>{var ot;const ie=Ke.filter(V=>V.content&&V.content.trim().length>0).map(V=>{var kt;const ye=V.path||V.name,me=ye.includes(".")&&((kt=ye.split(".").pop())==null?void 0:kt.toLowerCase())||"text",_e=(V.language||"").toLowerCase(),dt=["html","tsx","jsx","css"].includes(me)?me:_e||me||"text";return{filename:ye,language:dt,content:V.content||""}}).filter(V=>["html","tsx","jsx","css"].includes(V.language)),we=id(ie);return((ot=we.find(V=>V.id==="/"||/home|index|landing/i.test(V.filename||V.name))||we[0])==null?void 0:ot.html)||null};return(async()=>{for(const Ke of Ne){if(Ft)return;try{const{data:ie,error:we}=await G.from("project_files").select("path,name,content,language").eq("project_id",Ke.id).order("path",{ascending:!0}).limit(80);if(we||!(ie!=null&&ie.length))continue;const Je=Zt(ie);if(Je){const ot=await u(Ke.id,Je,Ke.name);ot&&!Ft&&P(V=>({...V,[Ke.id]:ot}))}}catch(ie){console.warn("[HomePage] project thumbnail backfill failed:",ie)}}})(),()=>{Ft=!0}},[i,u]);const re=async()=>{$(!0);try{const{data:U,error:Ne}=await G.functions.invoke("customer-portal",{});if(Ne)throw new Error(Ne.message);if(U!=null&&U.error)throw new Error(U.error);if(U!=null&&U.url){window.location.href=U.url;return}throw new Error("No portal URL returned")}catch(U){const Ne=U instanceof Error?U.message:"Unknown error";if(Ne.toLowerCase().includes("no subscription")||Ne.toLowerCase().includes("not found")){g("/pricing");return}Mt({title:"Could not open billing portal",description:Ne,variant:"destructive"})}finally{$(!1)}},se=($t=(gt=p==null?void 0:p.user)==null?void 0:gt.user_metadata)==null?void 0:$t.display_name,le=typeof se=="string"&&se.trim().length>0?se:((je=(ue=p==null?void 0:p.user)==null?void 0:ue.email)==null?void 0:je.split("@")[0])||"User",te=le.slice(0,2).toUpperCase(),We=U=>{if(!U)return"Recently";const Ne=rx(U);return Number.isNaN(Ne.getTime())?"Recently":$s(Ne,{addSuffix:!0})},Me=async(U,Ne)=>{if(Y.current)return;if(h&&!f){Mt({title:"Verify your email first",description:"Open the verification link 
8283we sent before creating projects or starting AI builds.",variant:"destructive"});return}const Ft=Vbe(U,v);Y.current=!0,R(!0);try{let Ke=x.balance,ie=x.plan;{const wn=await Am(x.refresh,x);Ke=wn.balance,ie=wn.plan;for(let kn=0;kn<2&&Ke<30;kn+=1){await new Promise(rt=>window.setTimeout(rt,200));const Ae=await Am(x.refresh,x);Ke=Math.max(Ke,Ae.balance)}}if(ie===null&&Ke<Ts){Mt({title:"Credits required",description:`Keep at least ${Ts} credits available before starting a build.`,variant:"destructive"});return}if(Ke<30){Mt({title:"More credits needed",description:"This build needs about 30 credits. Top up or wait a moment and try again.",variant:"destructive"});return}const we=Ne||v==="mobile"?"mobile":"web",Je={...(n==null?void 0:n.architecture)||{frontend:"React",backend:"Node.js (NestJS)",database:"Supabase",auth:"Built-in Auth",mobileBackend:"supabase"},mobileFramework:we==="mobile"?Ne||"pwa":"none"};N!=="auto"&&sessionStorage.setItem("sj_pending_model",N);const ot=U.split("--- ATTACHED REFERENCE FILES ---")[0].trim()||U,me=ot.replace(/^(build|create|make|design|develop|generate|code)\s+(me\s+)?(a|an|the)?\s*/i,"").replace(/[^a-zA-Z0-9\s-]/g,"").trim().split(/\s+/).filter(Boolean).slice(0,5).join(" ").slice(0,50)||"Untitled Project",_e=me.charAt(0).toUpperCase()+me.slice(1),dt=ot.length>200?ot.slice(0,197)+"...":ot;sessionStorage.setItem("sj_pending_new_project","1");const kt=await l(_e,dt);if(!kt){Mt({title:"Could not create project",description:"Please try again in a moment.",variant:"destructive"});try{sessionStorage.removeItem("sj_pending_new_project")}catch{}return}await G.from("project_settings").upsert({project_id:kt.id,target:we,architecture:Je},{onConflict:"project_id"});try{sessionStorage.setItem(`sj-defer-warmup:${kt.id}`,"1"),window.setTimeout(()=>{try{sessionStorage.removeItem(`sj-defer-warmup:${kt.id}`)}catch{}},9e4)}catch{}await o(kt.id);try{window.history.replaceState({},"",`/studio?project=${kt.id}`)}catch{}try{sessionStorage.removeItem("sj_pending_new_project")}catch{}e(Ft,{immediate:!0})}finally{Y.current=!1,R(!1)}},Te=U=>{_(U),requestAnimationFrame(()=>{var Ne;return(Ne=I.current)==null?void 0:Ne.click()})},Ee=U=>{Array.from(U).forEach(Ne=>{if(Ne.size>50*1024*1024){Mt({title:"File too large",description:`${Ne.name} is over 50 MB.`,variant:"destructive"});return}Z_(Ne).then(Ft=>C(Zt=>[...Zt,Ft])).catch(()=>C(Ft=>[...Ft,{name:Ne.name,type:Ne.type||"application/octet-stream",size:Ne.size,kind:"file",summary:`${Ne.name} is attached, but text extraction failed. Use it as high-level reference only.`}]))})},st=()=>{const U=eT(T);if(U&&sessionStorage.setItem("sj_pending_reference_context",U),T.length>0)try{sessionStorage.setItem("sj_pending_attachments",JSON.stringify(T))}catch(Ne){console.warn("[home] failed to persist attachments:",Ne)}},xt=()=>{M("github")},on=async()=>{const U=y.trim();if(!U&&T.length===0)return;st();const Ne=U||"Create a polished app based on the attached reference files. Extract the information architecture, content, visual direction, and data from the attachments, then build the best matching product experience.";if(v==="mobile"){Me(Ne);return}Me(Ne)},Yt=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),on())},mt=async U=>{await o(U),t==null||t()},ln=async U=>{await c(U)};return a.jsxs("div",{className:"h-screen flex bg-background overflow-hidden relative",children:[a.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",style:{zIndex:0},children:[a.jsx("div",{className:"absolute inset-0 opacity-[0.025] dark:opacity-[0.04]",style:{backgroundImage:`
8284              radial-gradient(circle at 1px 1px, hsl(var(--primary)) 1px, transparent 0)
8285            `,backgroundSize:"48px 48px"}}),a.jsx("div",{className:"absolute inset-0 overflow-hidden opacity-[0.06] dark:opacity-[0.08] select-none","aria-hidden":"true",children:Gbe.map((U,Ne)=>a.jsx("span",{className:"absolute animate-jungle-sway",style:{left:`${8+Ne*7.5%85}%`,top:`${5+Ne*13%80}%`,animationDelay:`${Ne*-1}s`,fontSize:`${16+Ne%3*6}px`},children:U},Ne))}),a.jsx("div",{className:"absolute top-1/4 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[900px] h-[500px] rounded-full blur-[140px]",style:{background:"radial-gradient(ellipse, hsl(var(--primary) / 0.08), hsl(var(--accent) / 0.04), transparent)"}}),a.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-[400px] h-[400px] rounded-full blur-[120px]",style:{background:"radial-gradient(circle, hsl(var(--accent) / 0.06), transparent)"}})]}),a.jsxs("aside",{className:"hidden md:flex flex-col w-60 shrink-0 border-r bg-card/60 backdrop-blur-xl relative",style:{zIndex:40},children:[a.jsxs("div",{className:"h-14 px-4 flex items-center gap-2 border-b",children:[a.jsx("img",{src:"/studio-jungle-mark.svg",alt:"",className:"h-8 w-8 rounded-xl object-contain"}),a.jsx("img",{src:"/logo.png",alt:"Studiojungle",className:"h-12 w-auto object-contain"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto py-3",children:[a.jsx("nav",{className:"px-3 space-y-0.5",children:O_.map(U=>{const Ne=D===U.id;return a.jsxs("button",{type:"button",onClick:Ft=>
8285{Ft.stopPropagation(),M(U.id)},className:L("w-full flex items-center gap-3 px-3 py-1.5 rounded-lg text-[13px] font-medium transition-all",Ne?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-secondary/60"),children:[a.jsx(U.icon,{className:L("w-4 h-4 shrink-0",Ne&&"text-primary")}),a.jsx("span",{children:U.label})]},U.id)})}),i.length>0&&a.jsxs("div",{className:"mt-5 px-3",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 mb-1.5",children:[a.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/70",children:"Recent"}),i.length>8&&a.jsx("button",{type:"button",onClick:()=>M("projects"),className:"text-[10px] font-medium text-muted-foreground/70 hover:text-primary transition-colors",children:"All"})]}),a.jsx("div",{className:"space-y-0.5",children:i.slice(0,8).map(U=>{const Ne=(s==null?void 0:s.id)===U.id;return a.jsxs("button",{type:"button",onClick:()=>mt(U.id),className:L("w-full flex items-center gap-2 px-3 py-1.5 rounded-lg text-[12.5px] transition-colors text-left",Ne?"bg-secondary/70 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-secondary/40"),title:U.description||U.name,children:[a.jsx("span",{className:L("w-1 h-1 rounded-full shrink-0",Ne?"bg-primary":"bg-muted-foreground/40")}),a.jsx("span",{className:"truncate",children:U.name})]},U.id)})})]})]}),a.jsx("div",{className:"px-3 pt-2",children:a.jsxs("button",{type:"button",onClick:()=>g("/studio/billing"),className:"group w-full text-left rounded-xl p-3 bg-gradient-to-br from-primary/[0.08] via-primary/[0.04] to-transparent border border-primary/15 hover:border-primary/30 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[a.jsx(Dn,{className:"w-3.5 h-3.5 text-primary"}),a.jsx("span",{className:"text-[11px] font-semibold text-foreground",children:"Get more credits"})]}),a.jsx("p",{className:"text-[10.5px] text-muted-foreground leading-snug",children:"Upgrade your plan or top up tokens."})]})}),a.jsx("div",{className:"border-t mt-3 p-3",children:a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,children:a.jsxs("button",{className:"w-full flex items-center gap-2.5 px-2 py-2 rounded-lg hover:bg-secondary/60 transition-colors text-left",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary text-xs font-bold shrink-0",children:te}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-xs font-semibold text-foreground truncate",children:le}),a.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:(ct=p==null?void 0:p.user)==null?void 0:ct.email})]})]})}),a.jsxs(Jl,{align:"end",side:"top",className:"w-56",children:[a.jsx(hu,{className:"font-normal",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary text-sm font-bold shrink-0",children:te}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm font-semibold text-foreground truncate",children:le}),a.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(it=p==null?void 0:p.user)==null?void 0:it.email})]})]})}),a.jsx(ki,{}),a.jsxs(Qr,{onClick:()=>g("/"),children:[a.jsx(xm,{className:"w-4 h-4 mr-2"})," Home"]}),a.jsxs(Qr,{onClick:()=>g("/studio/account"),children:[a.jsx(ni,{className:"w-4 h-4 mr-2"})," Account settings"]}),a.jsxs(Qr,{onClick:U=>{U.preventDefault(),re()},disabled:B,children:[B?a.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(O$,{className:"w-4 h-4 mr-2"}),B?"Opening…":"Manage billing"]}),a.jsx(ki,{}),a.jsxs(Qr,{onClick:()=>d(),className:"text-destructive focus:text-destructive",children:[a.jsx(zb,{className:"w-4 h-4 mr-2"})," Log Out"]})]})]})})]}),a.jsxs("header",{className:"md:hidden h-14 border-b bg-card/80 backdrop-blur-xl flex items-center justify-between px-4 shrink-0 absolute top-0 left-0 right-0",style:{zIndex:50},children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:"/studio-jungle-mark.svg",alt:"",className:"h-8 w-8 rounded-xl object-contain"}),a.jsx("img",{src:"/logo.png",alt:"Studiojungle",className:"h-12 w-auto object-contain"})]}),a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,children:a.jsx("button",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary hover:bg-primary/20 transition-colors text-xs font-bold",children:te})}),a.jsxs(Jl,{align:"end",className:"w-56",children:[a.jsxs(hu,{className:"font-normal",children:[a.jsx("p",{className:"text-sm font-semibold truncate",children:le}),a.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(q=p==null?void 0:p.user)==null?void 0:q.email})]}),a.jsx(ki,{}),O_.map(U=>a.jsxs(Qr,{onClick:()=>M(U.id),children:[a.jsx(U.icon,{className:"w-4 h-4 mr-2"})," ",U.label]},U.id)),a.jsx(ki,{}),a.jsxs(Qr,{onClick:()=>{d(),g("/")},className:"text-destructive focus:text-destructive",children:[a.jsx(zb,{className:"w-4 h-4 mr-2"})," Log Out"]})]})]})]}),a.jsxs("main",{className:"flex-1 flex flex-col min-w-0 pt-14 md:pt-0 relative",children:[D==="home"&&a.jsx("div",{className:"flex-1 overflow-y-auto relative z-10",children:a.jsxs("div",{className:"max-w-4xl mx-auto w-full px-4 sm:px-6 pt-10 sm:pt-14 pb-16 space-y-12",children:[a.jsxs("section",{className:"relative flex flex-col items-center",children:[a.jsxs("div",{"aria-hidden":"true",className:"absolute inset-x-0 -top-4 h-[420px] overflow-hidden pointer-events-none select-none",children:[a.jsx("div",{className:"absolute top-[40px] left-0 animate-bird-flyby",children:a.jsxs("svg",{viewBox:"0 0 32 16",width:"28",height:"14",className:"text-foreground
8285/60",children:[a.jsx("path",{d:"M2 8 Q8 2 14 8",stroke:"currentColor",strokeWidth:"1.4",fill:"none",strokeLinecap:"round"}),a.jsx("path",{d:"M14 8 Q20 2 26 8",stroke:"currentColor",strokeWidth:"1.4",fill:"none",strokeLinecap:"round",className:"animate-wing-flap",style:{transformOrigin:"14px 8px"}}),a.jsx("circle",{cx:"28",cy:"8",r:"1.2",fill:"currentColor"})]})}),a.jsx("span",{className:"absolute top-0 left-[18%] animate-leaf-1 text-emerald-500/70",style:{animationDelay:"0s"},children:a.jsx(fu,{size:18})}),a.jsx("span",{className:"absolute top-0 left-[58%] animate-leaf-2 text-lime-600/60",style:{animationDelay:"7s"},children:a.jsx(fu,{size:14})}),a.jsx("span",{className:"absolute top-0 left-[78%] animate-leaf-3 text-emerald-700/50",style:{animationDelay:"14s"},children:a.jsx(fu,{size:20})})]}),a.jsx("p",{className:"relative text-[11px] font-mono uppercase tracking-[0.18em] text-muted-foreground mb-5",children:"— Studio Jungle"}),a.jsxs("h1",{className:"relative text-4xl md:text-6xl font-bold tracking-[-0.02em] text-foreground mb-3 text-center leading-[1.05]",children:["What are we growing",a.jsx("br",{}),a.jsxs("span",{className:"text-muted-foreground",children:["today, ",le.split(/\s+/)[0],"?"]})]}),a.jsx("p",{className:"relative text-muted-foreground text-sm md:text-base mb-8 text-center max-w-md leading-relaxed",children:"Describe your idea — the AI ships a working app in seconds."}),a.jsx("div",{className:"w-full max-w-2xl mb-6",children:a.jsx(Nbe,{hasProjects:i.length>0})}),a.jsx("div",{className:"flex items-center gap-1 bg-card border rounded-xl p-1 mb-4 shadow-sm",children:T_.map(U=>a.jsxs("button",{onClick:()=>k(U.id),className:L("flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all",v===U.id?"bg-primary/10 text-primary shadow-sm":"text-muted-foreground hover:text-foreground hover:bg-secondary/50"),children:[a.jsx(U.icon,{className:"w-4 h-4"}),U.label]},U.id))}),a.jsx("p",{className:"mb-5 max-w-xl text-center text-xs text-muted-foreground",children:(Nt=T_.find(U=>U.id===v))==null?void 0:Nt.helper}),a.jsxs("div",{className:"w-full max-w-2xl",children:[T.length>0&&a.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:T.map((U,Ne)=>{if(`${U.name}`,qn,U.kind==="image"&&U.dataUrl)return a.jsxs("div",{className:"group relative h-20 w-20 overflow-hidden rounded-xl border bg-background shadow-sm",title:U.name,children:[a.jsx("img",{src:U.dataUrl,alt:U.name,className:"h-full w-full object-cover"}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-black/45 px-1.5 py-1 text-[10px] font-medium text-white opacity-0 transition-opacity group-hover:opacity-100",children:a.jsx("span",{className:"block truncate",children:U.name})}),a.jsx("button",{type:"button",onClick:()=>C(Ke=>Ke.filter((ie,we)=>we!==Ne)),className:"absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-black/65 text-white opacity-90 shadow-sm transition hover:bg-black","aria-label":`Remove ${U.name}`,children:a.jsx(qn,{className:"h-3 w-3"})})]},`${U.name}-${Ne}`);const Zt=U.size&&U.size>0?U.size<1024?`${U.size} B`:U.size<1024*1024?`${Math.round(U.size/1024)} KB`:`${(U.size/(1024*1024)).toFixed(U.size>=10*1024*1024?0:1)} MB`:U.kind;return a.jsxs("div",{className:"group relative flex max-w-[220px] items-center gap-2 rounded-xl border bg-background px-3 py-2 pr-8 shadow-sm",title:U.name,children:[a.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:a.jsx(kh,{className:"h-4 w-4 text-primary"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"truncate text-xs font-medium text-foreground",children:U.name}),a.jsx("div",{className:"text-[10px] text-muted-foreground",children:Zt})]}),a.jsx("button",{type:"button",onClick:()=>C(Ke=>Ke.filter((ie,we)=>we!==Ne)),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground transition hover:text-foreground","aria-label":`Remove ${U.name}`,children:a.jsx(qn,{className:"h-3.5 w-3.5"})})]},`${U.name}-${Ne}`)})}),a.jsx(HL,{compact:!0,className:"mb-3"}),a.jsxs("div",{className:"bg-card border rounded-2xl shadow-lg hover:shadow-xl transition-shadow ring-1 ring-primary/5 flex flex-col",onDragOver:U=>U.preventDefault(),onDrop:U=>{var Ne;U.preventDefault(),(Ne=U.dataTransfer.files)!=null&&Ne.length&&Ee(U.dataTransfer.files)},children:[a.jsx("input",{ref:I,type:"file",multiple:!0,accept:E,className:"hidden",onChange:U=>{U.target.files&&Ee(U.target.files),U.target.value=""}}),a.jsx("textarea",{value:y,onChange:U=>
8285b(U.target.value),onKeyDown:Yt,placeholder:he||"Build me an app for…",rows:3,className:"w-full resize-none rounded-t-2xl bg-transparent px-5 pt-4 pb-2 text-sm placeholder:text-muted-foreground focus:outline-none max-h-[280px] overflow-y-auto"}),a.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 pb-3 pt-1 border-t border-border/50",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs(Kl,{children:[a.jsx(Yl,{asChild:!0,children:a.jsxs("button",{type:"button",className:L("flex h-9 items-center gap-1.5 rounded-lg px-2.5 text-xs font-medium transition-colors",T.length>0?"bg-primary/10 text-primary hover:bg-primary/15":"text-muted-foreground hover:bg-secondary hover:text-foreground"),"aria-label":"Attach reference file",children:[a.jsx(ym,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden sm:inline",children:"Upload"}),T.length>0&&a.jsx("span",{className:"ml-0.5 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground",children:T.length})]})}),a.jsxs(Jl,{align:"start",side:"top",className:"w-80 p-2",children:[a.jsxs(hu,{className:"flex items-center gap-2 text-xs",children:[a.jsx(W$,{className:"h-4 w-4 text-primary"}),"Add project references"]}),a.jsx("p",{className:"px-2 pb-2 text-[11px] leading-relaxed text-muted-foreground",children:"Upload files for Studio Jungle AI to read before building."}),a.jsx(ki,{}),I_.map(U=>a.jsxs(Qr,{onClick:()=>Te(U.accept),className:"items-start gap-3 py-2.5",children:[a.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:a.jsx(U.icon,{className:"h-4 w-4"})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:U.label}),a.jsx("p",{className:"text-xs text-muted-foreground",children:U.description})]})]},U.label)),a.jsx(ki,{}),a.jsxs(Qr,{onClick:()=>Te(I_.map(U=>U.accept).join(",")),className:"gap-3 py-2.5",children:[a.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground",children:a.jsx(ym,{className:"h-4 w-4"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:"Any supported file"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Let Studio Jungle classify it"})]})]})]})]}),a.jsx(Q_,{value:N,onChange:j}),a.jsx($I,{value:w,onChange:S,placement:"below"}),a.jsxs("button",{type:"button",onClick:xt,className:L("flex h-9 items-center gap-1.5 rounded-lg px-2.5 text-xs font-medium transition-colors",Z.connected?"bg-primary/10 text-primary hover:bg-primary/15":"text-muted-foreground hover:bg-secondary hover:text-foreground"),"aria-label":"Import an existing GitHub repository",children:[Z.avatar?a.jsx("img",{src:Z.avatar,alt:"",className:"h-4 w-4 rounded-full"}):a.jsx(to,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden sm:inline",children:Z.connected?"GitHub connected":"Import repo"})]})]}),a.jsx(Q,{size:"icon",onClick:on,disabled:!y.trim()&&T.length===0||K,className:"h-10 w-10 rounded-xl shadow-md shrink-0",children:a.jsx(Li,{className:"w-4 h-4"})})]})]})]}),a.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-center gap-2 text-xs",children:[a.jsxs("button",{type:"button",onClick:xt,className:L("inline-flex items-center gap-2 rounded-full border bg-card/80 px-3 py-1.5 font-medium shadow-sm transition-colors hover:border-primary/30 hover:text-foreground",Z.connected?"text-primary":"text-muted-foreground"),children:[a.jsx(to,{className:"h-3.5 w-3.5"}),Z.connected?`GitHub @${Z.login}`:"Connect GitHub or import code"]}),a.jsxs("button",{type:"button",onClick:()=>M("cloud"),className:"inline-flex items-center gap-2 rounded-full border bg-card/80 px-3 py-1.5 font-medium text-muted-foreground shadow-sm transition-colors hover:border-primary/30 hover:text-foreground",children:[a.jsx(ya,{className:"h-3.5 w-3.5"}),"Cloud deploys"]}),a.jsxs("button",{type:"button",onClick:()=>M("integrations"),className:"inline-flex items-center gap-2 rounded-full border bg-card/80 px-3 py-1.5 font-medium text-muted-foreground shadow-sm transition-colors hover:border-primary/30 hover:text-foreground",children:[a.jsx(Ma,{className:"h-3.5 w-3.5"}),"Integrations"]})]}),a.jsx("div",{className:"flex flex-wrap items-center justify-center gap-2 mt-5 max-w-2xl",children:(()=>{const U=E_[v]||E_.web;return ne&&ne.length>0?ne.map((Ne,Ft)=>{var Ke;const Zt=((Ke=U[Ft%U.length])==null?void 0:Ke.icon)||no;return a.jsxs("button",{onClick:()=>b(Ne.prompt),className:"flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-card border text-xs font-medium text-muted-foreground hover:text-foreground hover:border-primary/30 hover:shadow-sm transition-all group",title:Ne.prompt,children:[a.jsx(Zt,{className:"w-3.5 h-3.5 text-primary group-hover:scale-110 transition-transform"}),Ne.label]},`${Ne.label}-${Ft}`)}):U.map(Ne=>a.jsxs("button",{onClick:()=>b(Ne.prompt),className:"flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-card border text-xs font-medium text-muted-foreground hover:text-foreground hover:border-primary/30 hover:shadow-sm transition-all group",children:[a.jsx(Ne.icon,{className:"w-3.5 h-3.5 text-primary group-hover:scale-110 transition-transform"}),Ne.label]},Ne.label))})()})]}),i.length>0&&a.jsxs("section",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Lr,{className:"w-4 h-4 text-muted-foreground"}),a.jsx("span",{className:"text-sm font-semibold text-foreground",children:"Recent Projects"})]}),i.length>4&&a.jsxs("button",{onClick:()=>M("projects"),className:"text-xs font-medium text-primary hover:text-primary/80 transition-colors",children:["View all (",i.length,") →"]})]}),a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",children:i.slice(0,4).map(U=>{const Ne=Math.abs([...U.id].reduce((we,Je)=>(we<<5)-we+Je.charCodeAt(0)|0,0)),Ft=["from-emerald-500/30 via-teal-500/20 to-cyan-500/10","from-violet-500/30 via-fuchsia-500/20 to-pink-500/10","from-amber-500/30 via-orange-500/20 to-rose-500/10","from-sky-500/30 via-blue-500/20 to-indigo-500/10","from-lime-500/30 via-emerald-500/20 to-teal-500/10","from-rose-500/30 via-pink-500/20 to-purple-500/10"],Zt=["bg-emerald-400/60","bg-vi
8285olet-400/60","bg-amber-400/60","bg-sky-400/60","bg-lime-400/60","bg-rose-400/60"],Ke=Ft[Ne%Ft.length],ie=Zt[Ne%Zt.length];return a.jsxs("button",{onClick:()=>mt(U.id),className:"group text-left bg-card border rounded-xl overflow-hidden hover:shadow-lg hover:-translate-y-0.5 hover:border-primary/30 transition-all",children:[(()=>{const we=A[U.id],Je=U.thumbnail_url,ot=!!Je&&Je.startsWith("data:image/svg+xml"),V=we||(ot?null:Je);return a.jsx("div",{className:L("h-28 relative overflow-hidden",!V&&`bg-gradient-to-br ${Ke}`),children:V?a.jsx("img",{src:V,alt:U.name,className:"w-full h-full object-cover object-top",loading:"lazy"}):a.jsx(Kbe,{accent:ie,hash:Ne})})})(),a.jsxs("div",{className:"p-3.5",children:[a.jsx("span",{className:"font-medium text-foreground text-sm truncate block",children:U.name}),a.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1 mt-0.5",children:U.description||"No description"}),a.jsxs("div",{className:"flex items-center gap-1 mt-2 text-[10px] text-muted-foreground/70",children:[a.jsx(lT,{className:"w-2.5 h-2.5"}),a.jsx("span",{children:We(U.created_at)})]})]})]},U.id)})})]}),a.jsx("section",{children:a.jsx(S$,{onSelectTemplate:U=>b(U),compact:!0})})]})}),D==="projects"&&a.jsx(C_,{projects:i.filter(U=>U.isOwner!==!1),onSelectProject:mt,onDeleteProject:ln}),D==="shared"&&a.jsx(C_,{projects:i.filter(U=>U.isOwner===!1),onSelectProject:mt,onDeleteProject:ln,emptyTitle:"No shared projects yet",emptyDescription:"When someone invites you to collaborate, the project shows up here.",headerTitle:"Shared with me",headerDescription:"Projects other users have invited you to. Edits use the project owner's AI credits."}),D==="workflows"&&a.jsx($be,{}),D==="integrations"&&a.jsx(qbe,{}),D==="github"&&a.jsx("div",{className:"flex-1 overflow-y-auto bg-background/70 relative z-10",children:a.jsx(oM,{embedded:!0,onBack:()=>M("home"),onImported:()=>t==null?void 0:t()})}),D==="cloud"&&a.jsx(Hbe,{onOpenProjectCloud:async U=>{var Ne;n!=null&&n.switchProject&&await n.switchProject(U),(Ne=n==null?void 0:n.setActiveWorkspaceTab)==null||Ne.call(n,"cloud"),t==null||t()}}),D==="brand"&&a.jsx(Wbe,{}),a.jsx(WM,{})]})]})}const Jbe={spawning:0,bootstrapping:0,writing_files:1,installing:4,starting_vite:5,compiling:5,ready:6},R_=["Reading your idea","Sketching the layout","Designing the interface","Writing the code","Installing dependencies","Bringing it to life","Almost ready"],Xbe=300;function Zbe({activePrompt:e,onCancel:t,onRetry:r}){var Y;const{project:n,isBuilding:s,liveStatus:i,toolCallHistory:o,lastBuildErrors:l,queuedPrompts:c,enqueuePrompt:u,removeQueuedPrompt:d,notifyVitePreviewReady:p,markFirstBuildDone:h}=gn(),f=((Y=n==null?void 0:n.name)==null?void 0:Y.trim())||"your app",x=m.useMemo(()=>{const Z=(i||"").toLowerCase(),O=o.length>0,ne=o.filter(ae=>/\.tsx?$|component|ui\/|pages\/|layout|header|hero|nav/i.test(ae.label)).length,oe=o.filter(ae=>/hook|use[A-Z]|context|state|store|api|util|lib\/|services/i.test(ae.label)).length,he=/install|pnpm|npm i\b|fetching dep|adding dep/.test(Z);return!s&&O?6:he?4:s&&oe>=3?3:s&&ne>=2?2:s&&O?1:0},[s,i,o]),[g,y]=m.useState(0),b=m.useRef(Date.now()),[v,k]=m.useState(null);m.useEffect(()=>{if(x<=g)return;const Z=Date.now()-b.current,O=Math.max(0,Xbe-Z),ne=window.setTimeout(()=>{y(oe=>{const he=oe+1;return he>6?oe:(b.current=Date.now(),he)}),k(g),window.setTimeout(()=>k(null),600)},O);return()=>window.clearTimeout(ne)},[x,g]);const N=R_[g],[j,w]=m.useState(null),S=m.useRef(!0);m.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]),m.useEffect(()=>{if(!(n!=null&&n.id))return;let Z=null,O=!1;const ne=async()=>{if(!O){try{const{data:oe}=await G.functions.invoke("e2b-preview-runtime",{body:{action:"build_status",project_id:n.id}});if(O||!S.current)return;if(oe){w(oe);const he=Jbe[oe.phase];if(typeof he=="number"&&he>g&&(y(ae=>Math.max(ae,he)),b.current=Date.now()),oe.phase==="ready"&&p(),oe.isTerminal)return}}catch{}Z=window.setTimeout(ne,1e3)}};return ne(),()=>{O=!0,Z!==null&&window.clearTimeout(Z)}},[n==null?void 0:n.id]);const T=m.useRef(Date.now()),[C,A]=m.useState(!1);m.useEffect(()=>{const Z=window.setInterval(()=>{Date.now()-T.current>=18e4&&A(!0)},5e3);return()=>window.clearInterval(Z)},[]);
8285const[P,E]=m.useState(!1),[_,I]=m.useState(""),D=m.useCallback(()=>{_.trim()&&(u(_),I(""))},[_,u]),M=l.length>0?l[l.length-1]:null,B=!1,[$,K]=m.useState(!1);if((j==null?void 0:j.phase)==="failed"){const Z=j!=null&&j.viteLastLogs&&j.viteLastLogs.length>0?j.viteLastLogs:M?[M]:[],O=(j==null?void 0:j.error)||M||"The build stopped before reaching the preview.",ne=(()=>{typeof(j==null?void 0:j.error)=="string"&&j.error.length>0;const oe=j==null?void 0:j.previousPhase;return oe&&{spawning:"while spinning up your sandbox",bootstrapping:"while getting the sandbox ready",writing_files:"while writing your project files",installing:"while installing dependencies",starting_vite:"while starting the preview server",compiling:"while compiling your app"}[oe]||""})();return a.jsxs("div",{className:"fixed inset-0 z-[100] bg-background flex flex-col",children:[a.jsx("div",{className:"flex items-center justify-between px-6 py-4",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a.jsx("span",{className:"inline-flex items-center justify-center w-6 h-6 rounded bg-primary/10 text-primary text-xs font-semibold",children:"SJ"}),a.jsx("span",{children:"Studiojungle"})]})}),a.jsx("div",{className:"flex-1 flex items-center justify-center px-6",children:a.jsxs("div",{className:"w-full max-w-[480px] flex flex-col items-center text-center",children:[a.jsx("div",{className:"relative w-[200px] h-[200px] mb-8 flex items-center justify-center opacity-50",children:a.jsxs("svg",{viewBox:"0 0 200 200",className:"w-[180px] h-[180px]","aria-hidden":"true",children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"sj-ws-grad-fail",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[a.jsx("stop",{offset:"0%",stopColor:"#d4cce5"}),a.jsx("stop",{offset:"100%",stopColor:"#e5cdd0"})]})}),a.jsx("path",{fill:"url(#sj-ws-grad-fail)",d:"M40,100 C40,55 70,30 105,35 C155,40 175,80 170,120 C165,160 125,175 90,165 C55,155 40,135 40,100 Z"})]})}),a.jsxs("h1",{className:"text-2xl font-medium text-foreground tracking-tight mb-2",children:["Hit a snag building ",f]}),a.jsxs("p",{className:"text-sm text-muted-foreground mb-6 leading-relaxed",children:["We stopped ",ne||"partway through",". Your sandbox is safe and we can retry, or you can start fresh."]}),a.jsxs("div",{className:"flex gap-2 mb-4",children:[(j==null?void 0:j.canRetry)!==!1&&a.jsx("button",{onClick:r,className:"px-4 py-2 rounded-lg text-sm bg-primary text-primary-foreground hover:bg-primary/90 transition-colors font-medium",children:"Try again"}),a.jsx("button",{onClick:()=>E(!0),className:"px-4 py-2 rounded-lg text-sm border border-border hover:bg-muted transition-colors",children:"Start fresh"})]}),a.jsxs("button",{type:"button",onClick:()=>K(oe=>!oe),className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[$?a.jsx(Nw,{className:"w-3 h-3"}):a.jsx(Yr,{className:"w-3 h-3"}),$?"Hide details":"Show details"]}),$&&a.jsxs("div",{className:"mt-4 w-full text-left rounded-lg border bg-card/70 p-3 text-[11px] font-mono leading-relaxed",children:[a.jsx("div",{className:"text-foreground/90 mb-2 whitespace-pre-wrap break-all",children:O}),Z.length>0&&a.jsx("div",{className:"border-t pt-2 mt-2 text-muted-foreground/80 max-h-48 overflow-y-auto whitespace-pre-wrap",children:Z.join(`
8286`)})]})]})}),P&&a.jsx("div",{className:"fixed inset-0 z-[110] bg-background/80 backdrop-blur-sm flex items-center justify-center px-6",children:a.jsxs("div",{className:"w-full max-w-sm rounded-2xl border bg-card shadow-lg p-5 flex flex-col gap-4",children:[a.jsx("div",{className:"text-base font-medium",children:"Start fresh?"}),a.jsx("div",{className:"text-sm text-muted-foreground",children:"The sandbox will be shut down and this project will be deleted. You can start a brand-new build from Home."}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx("button",{onClick:()=>E(!1),className:"px-3 py-1.5 rounded text-sm border border-border hover:bg-muted",children:"Stay here"}),a.jsx("button",{onClick:()=>{E(!1),t()},className:"px-3 py-1.5 rounded text-sm bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Yes, delete and go home"})]})]})}),a.jsx("style",{children:`
8287          @keyframes sj-ws-phasefade {
8288            from { opacity: 0; transform: translateY(2px); }
8289            to   { opacity: 1; transform: translateY(0); }
8290          }
8291        `})]})}return a.jsxs("div",{className:"fixed inset-0 z-[100] bg-background flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a.jsx("span",{className:"inline-flex items-center justify-center w-6 h-6 rounded bg-primary/10 text-primary text-xs font-semibold",children:"SJ"}),a.jsx("span",{children:"Studiojungle"})]}),a.jsx("button",{onClick:()=>E(!0),className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Cancel"})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center px-6",children:a.jsxs("div",{className:"w-full max-w-[480px] flex flex-col items-center text-center",children:[a.jsxs("div",{className:"relative w-[200px] h-[200px] mb-8 flex items-center justify-center",children:[a.jsx("span",{className:"absolute inset-0 rounded-full blur-3xl op
8291acity-60",style:{background:"radial-gradient(circle at 50% 50%, rgba(168,140,255,0.45), rgba(255,180,200,0.25) 50%, transparent 75%)",animation:"sj-ws-glow 3s ease-in-out infinite"},"aria-hidden":"true"}),a.jsxs("svg",{viewBox:"0 0 200 200",className:"relative w-[180px] h-[180px] drop-shadow-[0_8px_24px_rgba(120,100,200,0.18)]","aria-hidden":"true",children:[a.jsxs("defs",{children:[a.jsxs("linearGradient",{id:"sj-ws-grad-a",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[a.jsx("stop",{offset:"0%",stopColor:"#c9b8ff"}),a.jsx("stop",{offset:"100%",stopColor:"#ffc7d9"})]}),a.jsxs("linearGradient",{id:"sj-ws-grad-b",x1:"100%",y1:"0%",x2:"0%",y2:"100%",children:[a.jsx("stop",{offset:"0%",stopColor:"#a5e8ff"}),a.jsx("stop",{offset:"100%",stopColor:"#fde6a9"})]})]}),a.jsx("path",{fill:"url(#sj-ws-grad-a)",opacity:"0.85",children:a.jsx("animate",{attributeName:"d",dur:"6s",repeatCount:"indefinite",values:`
8292                    M40,100 C40,55 70,30 105,35 C155,40 175,80 170,120 C165,160 125,175 90,165 C55,155 40,135 40,100 Z;
8293                    M50,110 C45,65 80,35 115,40 C160,45 180,90 165,130 C150,165 110,180 80,160 C50,145 55,135 50,110 Z;
8294                    M40,100 C40,55 70,30 105,35 C155,40 175,80 170,120 C165,160 125,175 90,165 C55,155 40,135 40,100 Z
8295                  `})}),a.jsx("path",{fill:"url(#sj-ws-grad-b)",opacity:"0.55",children:a.jsx("animate",{attributeName:"d",dur:"7.5s",repeatCount:"indefinite",values:`
8296                    M55,90 C50,55 90,35 125,50 C160,65 170,105 155,135 C140,165 95,170 75,155 C50,140 60,120 55,90 Z;
8297                    M60,100 C60,60 95,40 135,55 C170,70 165,115 145,140 C125,165 90,165 75,145 C55,130 60,115 60,100 Z;
8298                    M55,90 C50,55 90,35 125,50 C160,65 170,105 155,135 C140,165 95,170 75,155 C50,140 60,120 55,90 Z
8299                  `})})]})]}),a.jsx("h1",{className:"text-2xl font-medium text-foreground tracking-tight max-w-[420px] truncate mb-6",title:f,children:f}),a.jsxs("div",{className:"flex items-center justify-center gap-2 h-7 relative",children:[a.jsx("span",{className:"inline-flex h-2 w-2 rounded-full bg-primary/80",style:{animation:"sj-ws-dot 3s ease-in-out infinite"},"aria-hidden":"true"}),a.jsxs("div",{className:"relative h-6 flex items-center",children:[v!==null&&a.jsxs("span",{className:"absolute left-0 inline-flex items-center gap-1 text-sm text-emerald-500/90",style:{animation:"sj-ws-checkflash 600ms ease-out forwards"},"aria-hidden":"true",children:[a.jsx(Wn,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"font-mono text-xs",children:R_[v]})]},`done-${v}`),a.jsx("span",{className:"text-sm text-foreground/90",style:{animation:"sj-ws-phasefade 200ms ease-out"},children:N},`phase-${g}`)]})]}),B,C&&a.jsxs("div",{className:"mt-8 w-full rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-left flex flex-col gap-2",style:{animation:"sj-ws-phasefade 240ms ease-out"},children:[a.jsx("div",{className:"font-medium text-foreground",children:"Still working — this is taking longer than usual."}),a.jsx("div",{className:"text-muted-foreground",children:"Your sandbox is alive and we're polling for readiness."}),a.jsxs("div",{className:"flex gap-2 pt-1",children:[a.jsx("button",{onClick:()=>A(!1),className:"px-3 py-1 rounded text-xs border border-border hover:bg-muted",children:"Wait"}),a.jsx("button",{onClick:()=>{A(!1),r()},className:"px-3 py-1 rounded text-xs border border-border hover:bg-muted",children:"Retry"}),a.jsx("button",{onClick:()=>E(!0),className:"px-3 py-1 rounded text-xs border border-destructive/40 text-destructive hover:bg-destructive/10",children:"Cancel"})]})]}),M&&a.jsxs("div",{className:"mt-6 w-full rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-xs text-left text-muted-foreground",style:{animation:"sj-ws-phasefade 240ms ease-out"},children:[a.jsx("span",{className:"text-destructive font-medium",children:"Hit a snag:"})," ",a.jsx("span",{className:"font-mono",children:M.slice(0,240)})]})]})}),a.jsx("div",{className:"px-6 pb-6",children:a.jsxs("div",{className:"max-w-2xl mx-auto",children:[c.length>0&&a.jsxs("div",{className:"mb-2 rounded-lg border bg-card/70 p-2 text-xs",children:[a.jsx("div",{className:"text-[11px] text-muted-foreground mb-1.5 px-1",children:"Queued — will run after the first build:"}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map((Z,O)=>a.jsxs("span",{className:"inline-flex items-center gap-1.5 max-w-[280px] rounded-full bg-muted text-foreground
8299/85 px-2.5 py-1 text-xs",title:Z,children:[a.jsx("span",{className:"truncate",children:Z}),a.jsx("button",{type:"button",onClick:()=>d(O),className:"text-muted-foreground hover:text-foreground","aria-label":"Remove queued prompt",children:a.jsx(qn,{className:"w-3 h-3"})})]},`${O}-${Z.slice(0,12)}`))})]}),a.jsxs("form",{onSubmit:Z=>{Z.preventDefault(),D()},className:"flex items-end gap-2 rounded-xl border bg-card shadow-sm p-2",children:[a.jsx("textarea",{value:_,onChange:Z=>I(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&!Z.shiftKey&&(Z.preventDefault(),D())},placeholder:"Queue a follow-up — runs after the first build",rows:1,className:L("flex-1 resize-none bg-transparent outline-none text-sm px-2 py-1.5","placeholder:text-muted-foreground/70 max-h-32")}),a.jsx("button",{type:"submit",disabled:!_.trim(),className:L("inline-flex items-center justify-center w-8 h-8 rounded-lg transition-colors",_.trim()?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground cursor-not-allowed"),"aria-label":"Queue prompt",children:a.jsx(iT,{className:"w-4 h-4"})})]}),B]})}),P&&a.jsx("div",{className:"fixed inset-0 z-[110] bg-background/80 backdrop-blur-sm flex items-center justify-center px-6",children:a.jsxs("div",{className:"w-full max-w-sm rounded-2xl border bg-card shadow-lg p-5 flex flex-col gap-4",children:[a.jsx("div",{className:"text-base font-medium",children:"Cancel this build?"}),a.jsx("div",{className:"text-sm text-muted-foreground",children:"The sandbox will be shut down and this project will be deleted. You can always start fresh from Home."}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx("button",{onClick:()=>E(!1),className:"px-3 py-1.5 rounded text-sm border border-border hover:bg-muted",children:"Keep building"}),a.jsx("button",{onClick:()=>{E(!1),t()},className:"px-3 py-1.5 rounded text-sm bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Cancel + delete project"})]})]})}),a.jsx("style",{children:`
8300        @keyframes sj-ws-glow {
8301          0%, 100% { opacity: 0.55; transform: scale(1); }
8302          50%      { opacity: 0.70; transform: scale(1.04); }
8303        }
8304        @keyframes sj-ws-dot {
8305          0%, 100% { opacity: 0.5; transform: scale(1); }
8306          50%      { opacity: 1;   transform: scale(1.15); }
8307        }
8308        @keyframes sj-ws-phasefade {
8309          from { opacity: 0; transform: translateY(2px); }
8310          to   { opacity: 1; transform: translateY(0); }
8311        }
8312        @keyframes sj-ws-checkflash {
8313          0%   { opacity: 0;   transform: translateY(0); }
8314          20%  { opacity: 1;   transform: translateY(-1px); }
8315          80%  { opacity: 1;   transform: translateY(-6px); }
8316          100% { opacity: 0;   transform: translateY(-10px); }
8317        }
8318      `})]})}const Qbe=new Set(["Building","Adding","Wiring","Crafting","Installing","Designing","Setting"]),e0e=new Set(["Editing","Polishing","Removing","Reading","Inspecting","Scanning","Type-checking","Calling","Running"]),Qc={spawning:{verb:"Running",target:"sandbox",subline:"Spinning up your environment"},bootstrapping:{verb:"Preparing",target:"preview",subline:"Getting things ready"},syncing:{verb:"Syncing",target:"project files",subline:"Uploading your project to the sandbox"},installing:{verb:"Installing",target:"dependencies",subline:"Pulling in what your app needs"},type_checking:{verb:"Verifying",target:"build",subline:"Quick quality check"},starting_vite:{verb:"Starting",target:"preview",subline:"Launching your app"},compiling:{verb:"Building",target:"preview",subline:"Compiling your app"},self_correcting:{verb:"Fixing",target:"build",subline:"Resolving an issue"},retry_attempt:{verb:"Recovering",target:"preview",subline:"Sandbox expired — restarting fresh"}},GM=["spawning","bootstrapping","syncing","installing","starting_vite","compiling"];function Ta(e){return e?GM.indexOf(e):-1}const t0e=new Set(["self_correcting","writing_fix_files","type_checking","rechecking_render"]);function n0e(e){const t=e.match(/^(Type-checking|Wrapping up|Scanning project)$/i);if(t)return{verb:t[1],target:""};const r=e.match(/^([A-Z][a-z-]+)\s+(.+)$/);return r?{verb:r[1],target:r[2]}:{verb:"Building",target:e}}function r0e(e,t){if(!t)return"";const r=t.toLowerCase();return e==="Type-checking"?"Running TypeScript over the project":e==="Calling"?`Talking to ${t}`:e==="Installing"?`Adding ${t} to the project`:e==="Scanning"||e==="Reading"||e==="Inspecting"?"Working on your project":/home page$/i.test(t)?"Setting up the home page":/(\w+) page$/i.test(t)?`Setting up the ${t.replace(/ page$/,"").toLowerCase()} page`:/(\w+) section$/i.test(t)?`Crafting the ${t.replace(/ section$/,"").toLowerCase()} section`:/(\w+) component$/i.test(t)?`Building the ${t.replace(/ component$/,"").toLowerCase()} component`:/dependencies/i.test(r)?"Wiring the packages the project needs":/typescript/i.test(r)?"Setting up the TypeScript config":/vite|vite config/i.test(r)?"Configuring the dev server":/tailwind/i.test(r)?"Setting up the design tokens":/postcss/i.test(r)?"Configuring CSS post-processing":/styles?/i.test(r)?"Polishing the styles":/app entry/i.test(r)?"Wiring up the app root":/database schema|sql/i.test(r)?"Designing the data model":/utilities|hook/i.test(r)?"Adding helper code":""}function s0e(e,t){return t==="running"?"running":Qbe.has(e)?"done-creation":(e0e.has(e),"done-action")}function a0e({userPrompt:e,projectName:t,items:r,onSubmitFollowUp:n}){const{project:s,isBuilding:i,toolCallHistory:o,enqueuePrompt:l,notifyVitePreviewReady:c,markFirstBuildDone:u,buildHalted:d,triggerBuildRef:p,firstBuildDone:h,previewReady:f}=gn(),[x,g]=m.useState(0),y=m.useRef(null);function b(R){if(!R)return"";const Y=R.match(/USER REQUEST:\s*([\s\S]*)$/i);return((Y==null?void 0:Y[1])||R).trim()}const v=b(e),k=t??(s==null?void 0:s.name)??"your project",[N,j]=m.useState(null),[w,S]=m.useState(-1),[T,C]=m.useState(!1),A=m.useRef(0),P=m.useRef(!1);m.useEffect(()=>{if(!f)return;const R=Ta("compiling");S(Y=>Math.max(Y,R))},[f]),m.useEffect(()=>{const R=Ta(N==null?void 0:N.phase);R>
8318=0&&S(Y=>Math.max(Y,R))},[N==null?void 0:N.phase]),m.useEffect(()=>{const R=N==null?void 0:N.phase,Y=Ta("syncing"),Z=Ta("installing");R==="installing"?S(O=>Math.max(O,Z)):R==="starting_vite"||R==="compiling"||R==="ready"?S(O=>Math.max(O,Z)):R==="syncing"&&S(O=>Math.max(O,Y))},[N==null?void 0:N.phase]),m.useEffect(()=>{(i||o.length>0)&&S(R=>Math.max(R,0,Ta("installing")))},[i,o.length]),m.useEffect(()=>{const R=Ta("syncing"),Y=Ta("installing");if(w<R||w>=Y)return;const Z=window.setTimeout(()=>{S(O=>Math.max(O,Y))},8e3);return()=>window.clearTimeout(Z)},[w]),m.useEffect(()=>{i&&o.length===0?y.current||(y.current=Date.now()):(y.current=null,g(0))},[i,o.length]),m.useEffect(()=>{if(!y.current)return;const R=window.setInterval(()=>{y.current&&g(Math.max(1,Math.round((Date.now()-y.current)/1e3)))},1e3);return()=>window.clearInterval(R)},[i,o.length]);const E=m.useRef(!1);m.useEffect(()=>{if(!i||o.length>0){E.current=!1;return}if(x<45||E.current)return;const R=e==null?void 0:e.trim();if(R){E.current=!0;try{window.dispatchEvent(new CustomEvent("sj:abort-stuck-build",{detail:{prompt:R}}))}catch{}}},[i,o.length,x,e]);const _=m.useRef(!1);m.useEffect(()=>{const R=e==null?void 0:e.trim();if(!R||h||_.current)return;const Y=window.setTimeout(()=>{if(!(h||_.current)&&!o.some(Z=>Z.status==="done"||Z.status==="running")&&p.current){_.current=!0,console.log("[BuildActivityFeed] No AI work after 4s — kicking initial build");try{p.current(R)}catch{}}},4e3);return()=>window.clearTimeout(Y)},[e,h,o.length,p]),m.useEffect(()=>{if(!(!(s!=null&&s.id)||!(N!=null&&N.isTerminal)||N.phase==="ready")&&nm(N)&&!(A.current>=2)){A.current+=1,C(!0),j(null),Pr({action:"restart",projectId:s.id,files:[]}).catch(()=>null).finally(()=>{window.setTimeout(()=>C(!1),4e3)});try{window.postMessage({type:"sj-preview-sandbox-stopped",source:"build_activity_auto_recovery"},"*")}catch{}}},[s==null?void 0:s.id,N==null?void 0:N.phase,N==null?void 0:N.error,N==null?void 0:N.isTerminal]),m.useEffect(()=>{const R=Ta("installing"),Y=e==null?void 0:e.trim();if(!(s!=null&&s.id)||!Y||P.current||w<R||i||o.length>0||(N==null?void 0:N.phase)==="ready")return;const Z=window.setTimeout(()=>{if(!(P.current||i||o.length>0)){if(P.current=!0,p.current&&Y){console.log("[BuildActivityFeed] Post-install kick — restarting AI build");try{p.current(Y,{isRescue:!0})}catch{}}Pr({action:"restart",projectId:s.id,files:[]}).catch(()=>null);try{window.postMessage({type:"sj-preview-sandbox-stopped",source:"post_install_kick"},"*")}catch{}}},8e3);return()=>window.clearTimeout(Z)},[s==null?void 0:s.id,e,w,i,o.length,N==null?void 0:N.phase,p]),m.useEffect(()=>{if(!(s!=null&&s.id))return;let R=!1,Y=null;const Z=async()=>{if(R)return;let O;try{const{data:oe}=await G.functions.invoke("e2b-preview-runtime",{body:{action:"build_status",project_id:s.id}});if(R)return;if(oe){if(O=oe.phase,j(oe),oe.phase==="ready"){c();const re=!i,se=o.some(le=>le.status==="done");re&&se&&u()}const he=oe,ae=o3({phase:oe.phase,previewHealthy:he==null?void 0:he.previewHealthy,error:(he==null?void 0:he.error)??oe.error}),ve=oe.phase==="dead"||oe.phase==="vite_dead";if(ae&&(!i||ve))try{window.postMessage({type:"sj-preview-sandbox-stopped",source:"build_status_unhealthy"},"*")}catch{}if(oe.isTerminal&&(!(oe.phase!=="ready"&&nm(oe))||A.current>=2))return}}catch{}const ne=O==="starting_vite"||O==="compiling"||O==="installing"?500:1e3;Y=window.setTimeout(Z,ne)};return Z(),()=>{R=!0,Y!==null&&window.clearTimeout(Y)}},[s==null?void 0:s.id]);const I=m.useMemo(()=>{if(r)return r;const R=[],Y=N==null?void 0:N.phase,O=f||Y==="ready",ne=Ta(Y),oe=Ta("installing"),he=Ta("starting_vite"),ae=w>=oe&&oe>=0,ve=ae&&!O,re=Math.max(w,ne,i||o.length>0?0:-1,ve||i&&ae?he:-1);if(re>=0)for(let Te=0;Te<=re;Te++){const Ee=GM[Te];if(Ee==="installing"&&o.some(mt=>/install/i.test(mt.label)))continue;const st=Qc[Ee],xt=i&&ae&&Te<=he&&o.length===0,on=Te<w||ne>=0&&Te<ne||xt||O&&Te<=he,Yt=!O&&(Te===he&&ve&&!T&&!i||Te===he&&T||ne===Te&&!on||Te===ne&&Y==="compiling");R.push({kind:"card",card:{id:`phase-${Ee}`,...st,state:Yt?"running":"done-action"}})}i&&o.length===0&&R.push({kind:"card",card:{id:"phase-ai-planning",verb:x>=30?"Generating":(x>=20,"Planning"),target:x>=30?"fallback scaffolding":"your app",subline:x>=30?"Forcing preview to open...":x>=20?`Taking longer than usual... (${x}s)`:"Breaking down what to build first",state:"running"}});let se=null,le="",te=0;for(const Te of o){if(typeof Te.startedAt=="number"&&se!==null){const on=Te.startedAt-se;if(on>=2e3){const Yt=Math.max(1,Math.round(on/1e3));R.push({kind:"thinking",thinking:{id:`gap-${Te.id}`,durationS:Yt}})}}typeof Te.startedAt=="number"&&(se=Te.startedAt);const{verb:Ee,target:st}=n0e(Te.label),xt=`${Ee}::${st}`;xt===le&&typeof Te.startedAt=="number"&&Te.startedAt-te<1e4||(typeof Te.startedAt=="number"&&(te=Te.startedAt),le=xt,R.push({kind:"card",card:{id:Te.id,verb:Ee||"Building",target:st||Te.label,subline:r0e(Ee||"Building",st||Te.label),state:s0e(Ee,Te.status)}}))}if(!!(N!=null&&N.viaSelfCorrect)&&t0e.has(Y||"")){const Te=(N==null?void 0:N.selfCorrectAttempt)??1,Ee=(N==null?void 0:N.selfCorrectMaxAttempts)??3;R.push({kind:"card",card:{id:"phase-self-correcting",verb:Qc.self_correcting.verb,target:Qc.self_correcting.target,subline:`Attempt ${Te}/${Ee} — ${Qc.self_correcting.subline.toLowerCase()}`,state:"running"}})}else Y==="type_checking"&&R.push({kind:"card",card:{id:"phase-type-check",...Qc.type_checking,state:"running"}});if(Y==="retry_attempt"&&R.push({kind:"card",card:{id:"phase-retry",...Qc.retry_attempt,state:"running"}}),T&&R.push({kind:"card",card:{id:"phase-preview-recovering",verb:"Recovering",target:"preview",subline:"Restarting your preview environment…",state:"running"}}),(N==null?void 0:N.phase)==="failed"&&N.error&&!T){const Te=/auto-retrying with fresh|stale sandbox mid-op/i.test(N.error),Ee=nm(N)&&A.current<2;!Te&&!Ee&&R.push({kind:"card",card:{id:"phase-failed",verb:"Stopped",target:"build",subline:N.error.slice(0,120),state:"failed",errorDetails:[N.error,...(N.viteLastLogs||[]).slice(-10)].join(`
8319`)}})}const Me=R.some(Te=>Te.kind==="card"&&Te.card.state==="running");return ae&&!O&&!i&&o.length===0&&!Me&&R.push({kind:"card",card:{id:"phase-waiting-ai",verb:"Starting",target:"AI build",subline:"Connecting to the builder…",state:"running"}}),R.length===0&&i&&R.push({kind:"thinking",thinking:{id:"initial-think",durationS:2}}),R},[r,o,N,i,w,T,x,f]),[D,M]=m.useState(""),B=Ta("installing"),K=w>=B&&B>=0&&!f&&(N==null?void 0:N.phase)!=="ready";return a.jsxs("div",{className:"py-4",children:[a.jsxs("div",{className:"rounded-lg border border-border/60 overflow-hidden",style:{background:"#FAFAF7"},children:[a.jsx(i0e,{projectName:k,isBuilding:i||K||T||N!=null&&!N.isTerminal,isAlmostReady:!i&&(N==null?void 0:N.phase)==="ready"}),a.jsxs("div",{className:"px-6 pb-6 pt-5",children:[v&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-1.5 text-[11px] uppercase tracking-wider text-muted-foreground
8319/70",children:"You"}),a.jsx("div",{className:"inline-block bg-muted text-foreground rounded-lg px-3.5 py-2.5 text-sm mb-6 max-w-full",children:v})]}),a.jsx("div",{className:"mb-1.5 text-[11px] uppercase tracking-wider text-muted-foreground/70",children:"Studio"}),d&&a.jsxs("div",{className:"mb-4 flex items-start gap-2 rounded-lg border border-amber-300/60 bg-amber-50/70 px-3 py-2.5 text-[13px] text-amber-900",children:[a.jsx(is,{className:"w-4 h-4 mt-0.5 shrink-0"}),a.jsxs("div",{children:[a.jsx("div",{className:"font-medium",children:"Build halted at iteration limit."}),a.jsx("div",{className:"text-amber-900/80 mt-0.5",children:"Remaining changes are still applying in the sandbox. Send a follow-up message to continue."})]})]}),a.jsx("div",{className:"flex flex-col",children:I.map((R,Y)=>R.kind==="thinking"?a.jsx(o0e,{durationS:R.thinking.durationS},R.thinking.id):a.jsx(l0e,{card:R.card,index:Y},R.card.id))}),a.jsx("div",{className:"mt-7 pt-4 border-t border-border/40",children:a.jsxs("form",{onSubmit:R=>{R.preventDefault(),D.trim()&&(n?n(D):l(D),M(""))},className:"flex items-center gap-2 rounded-lg border border-border/60 bg-background px-3.5 py-2.5",children:[a.jsx(Kr,{className:"w-4 h-4 text-muted-foreground/70 shrink-0"}),a.jsx("input",{type:"text",value:D,onChange:R=>M(R.target.value),placeholder:"Queue a follow-up — runs after the first build",className:"flex-1 bg-transparent outline-none text-sm placeholder:text-muted-foreground/70"}),a.jsx("button",{type:"submit",className:"text-muted-foreground/70 hover:text-foreground transition-colors","aria-label":"Queue follow-up",children:a.jsx(iT,{className:"w-4 h-4"})})]})})]})]}),a.jsx("style",{children:`
8320        @keyframes sj-pulse {
8321          0%, 100% { opacity: 1; transform: scale(1); }
8322          50%      { opacity: 0.45; transform: scale(0.82); }
8323        }
8324        @keyframes sj-card-in {
8325          from { opacity: 0; transform: translateY(4px); }
8326          to   { opacity: 1; transform: translateY(0); }
8327        }
8328        @keyframes sj-state-flash {
8329          0%   { background-color: rgba(15, 110, 86, 0); }
8330          30%  { background-color: rgba(15, 110, 86, 0.04); }
8331          100% { background-color: rgba(15, 110, 86, 0); }
8332        }
8333        .sj-pulse-dot   { animation: sj-pulse 1.4s ease-in-out infinite; }
8334        .sj-card-in     { animation: sj-card-in 150ms ease-out; }
8335        .sj-card-flash  { animation: sj-state-flash 420ms ease-out; }
8336      `})]})}function i0e({projectName:e,isBuilding:t,isAlmostReady:r}){const n=t?"Building":r?"Almost ready":"Idle",s=!!t||!!r;return a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border/40 bg-background",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-[22px] h-[22px] rounded-md flex items-center justify-center text-[11px] font-medium",style:{background:"#E1F5EE",color:"#0F6E56"},children:"SJ"}),a.jsx("span",{className:"text-[13px] text-muted-foreground",children:"Studiojungle"}),a.jsx("span",{className:"text-[13px] text-muted-foreground/50",children:"/"}),a.jsx("span",{className:"text-[13px] text-foreground truncate max-w-[220px]",children:e})]}),a.jsx("div",{className:"flex items-center gap-3",children:a.jsxs("span",{className:"text-xs text-muted-foreground/70 flex items-center gap-1.5",children:[a.jsx("span",{className:L("w-1.5 h-1.5 rounded-full",s&&"sj-pulse-dot"),style:{background:s?"#1D9E75":"#999"}}),n]})})]})}function o0e({durationS:e}){return a.jsxs("div",{className:"text-[13px] text-muted-foreground my-3",children:["Thought for ",e,"s"]})}function l0e({card:e,index:t}){const[r,n]=m.useState(!1),s=e.state==="running",i=e.state==="failed",o=m.useRef(e.state),[l,c]=m.useState(!1);return m.useEffect(()=>{const u=o.current==="running",d=e.state==="done-action"||e.state==="done-creation";if(u&&d){c(!0);const p=window.setTimeout(()=>c(!1),420);return o.current=e.state,()=>window.clearTimeout(p)}o.current=e.state},[e.state]),a.jsxs("div",{className:L("rounded-lg px-4 py-3.5 mb-2.5 transition-colors sj-card-in",s?"border-[0.5px] border-border":"border-[0.5px] border-border/60",i&&"opacity-55",l&&"sj-card-flash"),style:{background:"#FFFFFF",animationDelay:`${t*30}ms`,boxShadow:s?"0 0 0 3px rgba(15, 110, 86, 0.06)":void 0},children:[a.jsxs("div",{className:L("flex items-center justify-between",e.subline?"mb-1":""),children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm font-medium text-foreground shrink-0",children:e.verb}),e.target&&a.jsx(c0e,{target:e.target,failed:i})]}),a.jsx(u0e,{state:e.state})]}),e.subline&&a.jsx("div",{className:"text-[13px] text-muted-foreground",children:e.subline}),i&&e.errorDetails&&a.jsxs("div",{className:"mt-2",children:[a.jsxs("button",{type:"button",onClick:()=>n(u=>!u),className:"inline-flex items-center gap-1 text-xs hover:underline",style:{color:"#2563EB"},children:[r?a.jsx(Nw,{className:"w-3 h-3"}):a.jsx(Yr,{className:"w-3 h-3"}),r?"Hide details":"Show details"]}
8336),r&&a.jsx("div",{className:"mt-2 rounded-md bg-muted/40 p-2.5 text-[11px] font-mono whitespace-pre-wrap break-all text-muted-foreground max-h-48 overflow-y-auto",children:e.errorDetails})]})]})}function c0e({target:e,failed:t}){const r=e.length>48?"…"+e.slice(-46):e;return t?a.jsx("span",{className:"text-xs font-mono px-2 py-0.5 rounded-md truncate",style:{background:"#FCEBEB",color:"#791F1F"},title:e,children:r}):a.jsx("span",{className:"text-xs font-mono px-2 py-0.5 rounded-md bg-muted text-muted-foreground truncate",title:e,children:r})}function u0e({state:e}){return e==="done-action"||e==="done-creation"?a.jsx(Wn,{className:"w-4 h-4 shrink-0",style:{color:"#0F6E56"},"aria-hidden":"true"}):e==="failed"?a.jsx(is,{className:"w-4 h-4 shrink-0",style:{color:"#A32D2D"},"aria-hidden":"true"}):a.jsx("span",{className:"inline-block w-2 h-2 rounded-full sj-pulse-dot shrink-0",style:{background:"#1D9E75"},"aria-hidden":"true"})}const d0e={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_SUPABASE_PROJECT_ID:"xfmlsevleobdlnjqxmdi",VITE_SUPABASE_PUBLISHABLE_KEY:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhmbWxzZXZsZW9iZGxuanF4bWRpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI3MDkwMDEsImV4cCI6MjA4ODI4NTAwMX0.9ueZHBjFbkpUadLBE_cwVUYX80VqRt_gWd2N75UgTCo",VITE_SUPABASE_URL:"https://xfmlsevleobdlnjqxmdi.supabase.co"};function D_(e,t){const r=d0e[e];return r===void 0||r===""?t:r==="1"||r==="true"}const M_={newProjectWorkingScreen:D_("VITE_NEW_PROJECT_WORKING_SCREEN",!0),useNewBuildFeed:D_("VITE_USE_NEW_BUILD_FEED",!0)};function Ea({className:e,...t}){return a.jsx("div",{className:L("animate-pulse rounded-md bg-muted",e),...t})}function p0e(e=!1){try{if(!e&&typeof document<"u"&&document.visibilityState==="visible")return;const t=window.AudioContext||window.webkitAudioContext;if(!t)return;const r=new t;[523.25,659.25,783.99].forEach((s,i)=>{const o=r.createOscillator(),l=r.createGain();o.type="sine",o.frequency.value=s,o.connect(l),l.connect(r.destination);const c=r.currentTime+i*.12,u=c+.28;l.gain.setValueAtTime(1e-4,c),l.gain.exponentialRampToValueAtTime(.18,c+.02),l.gain.exponentialRampToValueAtTime(1e-4,u),o.start(c),o.stop(u+.02)}),setTimeout(()=>{try{r.close()}catch{}},1200)}catch{}}function h0e({activePrompt:e,overlayPrompt:t,onGoHome:r}){const{project:n,firstBuildDone:s,previewReady:i,queuedPrompts:o,dequeueNextPrompt:l,isBuilding:c,triggerBuildRef:u,deleteProject:d,toolCallHistory:p}=gn(),h=m.useCallback(async()=>{var j;const k=e||t,N=p.some(w=>w.status==="done");if(n!=null&&n.id&&N){const{callVercelPreviewRuntime:w}=await ju(async()=>{const{callVercelPreviewRuntime:S}=await Promise.resolve().then(()=>OF);return{callVercelPreviewRuntime:S}},void 0);w({action:"restart",projectId:n.id,files:[]});try{window.postMessage({type:"sj-preview-sandbox-stopped",source:"first_build_retry"},"*")}catch{}return}if(k){try{window.dispatchEvent(new CustomEvent("sj:abort-stuck-build",{detail:{prompt:k}}))}catch{}try{(j=u.current)==null||j.call(u,k,{isRescue:!0})}catch{}}},[e,t,n==null?void 0:n.id,p,u]),f=m.useCallback(async()=>{if(n!=null&&n.id)try{await d(n.id)}catch{}r()},[n==null?void 0:n.id,d,r]),x=m.useRef(s);m.useEffect(()=>{s&&!x.current&&p0e(),x.current=s},[s]),m.useEffect(()=>{if(!s||c||o.length===0)return;const k=l();if(k&&u.current){const N=window.setTimeout(()=>{var j;try{(j=u.current)==null||j.call(u,k)}catch{}},250);return()=>window.clearTimeout(N)}},[s,c,o.length,l,u]);const g=t||e,y=typeof window<"u"&&sessionStorage.getItem("sj_pending_new_project")==="1",b=M_.newProjectWorkingScreen&&!!g&&(!s&&!i||y),v=(n==null?void 0:n.name)||(g?Xj(g).name:void 0);return a.jsxs(a.Fragment,{children:[a.jsx(vbe,{initialPrompt:e||void 0,onGoHome:r}),b&&(M_.useNewBuildFeed?a.jsxs("div",{className:"fixed inset-0 z-[100] bg-background overflow-auto sj-build-overlay-in",children:[a.jsxs("div",{className:"max-w-3xl mx-auto px-6 pt-8 pb-12",children:[a.jsx(a0e,{userPrompt:g||void 0,projectName:v}),a.jsxs("div",{className:"mt-3 flex items-center justify-center gap-3 text-[11px]",children:[a.jsx("button",{onClick:h,className:"px-2.5 py-1 rounded border border-border hover:bg-muted text-muted-foreground",children:"Retry"}),a.jsx("button",{onClick:f,className:"px-2.5 py-1 rounded border border-destructive/40 text-destructive hover:bg-destructive/10",children:"Cancel + delete project"})]})]}),a.jsx("style",{children:`
8337              @keyframes sj-build-overlay-in {
8338                from { opacity: 0; transform: translateX(-16px); }
8339                to   { opacity: 1; transform: translateX(0); }
8340              }
8341              .sj-build-overlay-in { animation: sj-build-overlay-in 320ms cubic-bezier(0.16, 1, 0.3, 1); }
8342            `})]}):a.jsx(Zbe,{activePrompt:g,onCancel:f,onRetry:h}))]})}const f0e=()=>a.jsxs("div",{className:"h-screen w-screen bg-background flex flex-col animate-fade-in",children:[a.jsxs("div",{className:"h-12 border-b border-border flex items-center gap-3 px-4",children:[a.jsx(Ea,{className:"h-6 w-6 rounded"}),a.jsx(Ea,{className:"h-4 w-32 rounded"}),a.jsx("div",{className:"flex-1"}),a.jsx(Ea,{className:"h-6 w-20 rounded"}),a.jsx(Ea,{className:"h-6 w-6 rounded-full"})]}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsxs("div",{className:"w-80 border-r border-border p-4 flex flex-col gap-3",children:[a.jsx(Ea,{className:"h-8 w-full rounded"}),a.jsx(Ea,{className:"h-4 w-3/4 rounded"}
8342),a.jsx(Ea,{className:"h-4 w-1/2 rounded"}),a.jsx("div",{className:"flex-1"}),a.jsx(Ea,{className:"h-10 w-full rounded"})]}),a.jsxs("div",{className:"flex-1 p-6 flex flex-col gap-4",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ea,{className:"h-8 w-20 rounded"}),a.jsx(Ea,{className:"h-8 w-20 rounded"}),a.jsx(Ea,{className:"h-8 w-20 rounded"})]}),a.jsx(Ea,{className:"flex-1 w-full rounded-lg"})]})]})]});function cw(e){const r=e.indexOf("--- ATTACHED REFERENCE FILES ---");if(r<0)return e;const n=e.slice(0,r).trim(),s=e.slice(r).trim();return s&&sessionStorage.setItem("sj_pending_reference_context",s),n||e}function Xj(e){const t=e.split("--- ATTACHED REFERENCE FILES ---")[0].trim()||e,s=t.replace(/^(build|create|make|design|develop|generate|code)\s+(me\s+)?(a|an|the)?\s*/i,"").replace(/[^a-zA-Z0-9\s-]/g,"").trim().split(/\s+/).filter(Boolean).slice(0,5).join(" ").slice(0,50)||"Untitled Project",i=s.charAt(0).toUpperCase()+s.slice(1),o=t.length>200?t.slice(0,197)+"...":t;return{name:i,description:o}}function m0e({onStartBuild:e}){const{createProject:t,switchProject:r}=gn(),{session:n}=Us(),s=m.useRef(!1);return m.useEffect(()=>{if(!n||s.current)return;const i=sessionStorage.getItem("sj_pending_prompt");if(!i)return;s.current=!0,sessionStorage.removeItem("sj_pending_prompt"),sessionStorage.removeItem("sj_studio_view");const o=cw(i);(async()=>{const{name:l,description:c}=Xj(o),u=await t(l,c);if(u){try{sessionStorage.setItem(`sj-defer-warmup:${u.id}`,"1"),window.setTimeout(()=>{try{sessionStorage.removeItem(`sj-defer-warmup:${u.id}`)}catch{}},9e4)}catch{}await r(u.id);try{window.history.replaceState({},"",`/studio?project=${u.id}`)}catch{}}try{sessionStorage.removeItem("sj_pending_new_project")}catch{}e(o,{immediate:!0})})()},[n,t,r,e]),null}const g0e=()=>{const{session:e,loading:t}=Us(),r=(()=>{try{return sessionStorage.getItem("sj_pending_prompt")}catch{return null}})(),[n,s]=m.useState(null),[i,o]=m.useState(()=>r?cw(r):null),l=(()=>{try{return new URLSearchParams(window.location.search).get("project")}catch{return null}})(),c=(()=>{try{const N=new URLSearchParams(window.location.search);return N.get("home")==="1"||N.has("home")}catch{return!1}})(),[u,d]=m.useState(()=>c?"home":l||r||sessionStorage.getItem("sj_studio_view")==="studio"?"studio":"home"),[p,h]=m.useState("opacity-100"),[f]=m.useState(()=>!!r),[x,g]=m.useState(()=>c?!1:l?!0:sessionStorage.getItem("sj_studio_view")==="studio");m.useEffect(()=>{u==="studio"?sessionStorage.setItem("sj_studio_view","studio"):u==="home"&&sessionStorage.removeItem("sj_studio_view")},[u]),m.useEffect(()=>{if(c){d("home"),g(!1),s(null),o(null);try{const N=new URL(window.location.href);N.searchParams.delete("home"),N.searchParams.delete("project"),window.history.replaceState({},"",N.pathname+(N.search||""))}catch{}}},[c]);const y=m.useCallback((N,j)=>{const w=cw(N);if(j!=null&&j.overlayOnly){o(w),d("studio"),h("opacity-100 scale-100");return}if(j!=null&&j.immediate){s(w),o(w),d("studio"),h("opacity-100 scale-100");return}h("opacity-0 scale-[0.98]"),setTimeout(()=>{s(w),o(w),d("shimmer"),h("opacity-100 scale-100"),setTimeout(()=>{h("opacity-0 scale-[0.99]"),setTimeout(()=>{d("studio"),h("opacity-0 scale-[1.01]"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h("opacity-100 scale-100")})})},300)},600)},350)},[]),b=m.useCallback(N=>{try{sessionStorage.setItem("sj_wp_initial_prompt",N)}catch{}h("opacity-0 scale-[0.98]"),setTimeout(()=>{d("shimmer"),h("opacity-100 scale-100"),setTimeout(()=>{h("opacity-0 scale-[0.99]"),setTimeout(()=>{d("wordpress"),h("opacity-0 scale-[1.01]"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h("opacity-100 scale-100")})})},300)},600)},350)},[]),v=m.useCallback(()=>{h("opacity-0 scale-[0.98]"),setTimeout(()=>{g(!0),d("studio"),h("opacity-0 scale-[1.01]"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h("opacity-100 scale-100")})})},350)},[]),k=m.useCallback(()=>{h("opacity-0 scale-[0.98]"),setTimeout(()=>{s(null),o(null),g(!1),d("home");try{window.location.search.includes("project=")&&window.history.replaceState({},"",window.location.pathname)}catch{}h("opacity-0 scale-[1.01]"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h("opacity-100 scale-100")})})},350)},[]);return t?i?a.jsx(FL,{userPrompt:i,projectName:Xj(i).name}):a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:a.jsx(ze,{className:"w-6 h-6 animate-spin text-primary"})}):e?a.jsxs(zF,{children:[a.jsx(m0e,{onStartBuild:y}),a.jsxs("div",{className:`h-screen w-screen ${f?"":"transition-all"} ${p}`,style:{transitionDuration:f?"0ms":"400ms",transitionTimingFunction:"cubic-bezier(0.4, 0, 0.2, 1)"},children:[u==="home"&&a.jsx(Ybe,{onStartBuild:y,onResumeProject:v,onStartWordPress:b}),u==="shimmer"&&a.jsx(f0e,{}),u==="studio"&&(n||i||x)&&a.jsx(h0e,{activePrompt:n,overlayPrompt:i,onGoHome:k}),u==="wordpress"&&a.jsx("div",{className:"h-full w-full",children:a.jsx(_D,{onGoHome:k})})]})]}):a.jsx(BL,{to:"/auth",replace:!0})},Ove=Object.freeze(Object.defineProperty({__proto__:null,default:g0e},Symbol.toStringTag,{value:"Module"}));
8342export{Ove as I,Dh as r};

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.