figranium 0.9.6 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/{index-Bkr74C53.js → index-BwaOqbmy.js} +2 -2
- package/dist/index.html +1 -1
- package/headful.js +40 -101
- package/package.json +1 -1
- package/scrape.js +38 -85
- package/server.js +16 -0
- package/user-agent-settings.js +3 -3
|
@@ -11,5 +11,5 @@ Error generating stack: `+n.message+`
|
|
|
11
11
|
Please change the parent <Route path="${j}"> to <Route path="${j==="/"?"*":`${j}/*`}">.`)}let A=mn(),w;if(u){let j=typeof u=="string"?vl(u):u;dt(C==="/"||j.pathname?.startsWith(C),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${C}" but pathname "${j.pathname}" was given in the \`location\` prop.`),w=j}else w=A;let N=w.pathname||"/",p=N;if(C!=="/"){let j=C.replace(/^\//,"").split("/");p="/"+N.replace(/^\//,"").split("/").slice(j.length).join("/")}let b=gp(i,{pathname:p});ba(_||b!=null,`No routes matched location "${w.pathname}${w.search}${w.hash}" `),ba(b==null||b[b.length-1].route.element!==void 0||b[b.length-1].route.Component!==void 0||b[b.length-1].route.lazy!==void 0,`Matched leaf route at location "${w.pathname}${w.search}${w.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let v=lg(b&&b.map(j=>Object.assign({},j,{params:Object.assign({},x,j.params),pathname:qa([C,d.encodeLocation?d.encodeLocation(j.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:j.pathname]),pathnameBase:j.pathnameBase==="/"?C:qa([C,d.encodeLocation?d.encodeLocation(j.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:j.pathnameBase])})),h,r,c,f);return u&&v?R.createElement(ji.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...w},navigationType:"POP"}},v):v}function eg(){let i=cg(),u=Y0(i)?`${i.status} ${i.statusText}`:i instanceof Error?i.message:JSON.stringify(i),r=i instanceof Error?i.stack:null,c="rgba(200,200,200, 0.5)",f={padding:"0.5rem",backgroundColor:c},d={padding:"2px 4px",backgroundColor:c},h=null;return console.error("Error handled by React Router default ErrorBoundary:",i),h=R.createElement(R.Fragment,null,R.createElement("p",null,"💿 Hey developer 👋"),R.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",R.createElement("code",{style:d},"ErrorBoundary")," or"," ",R.createElement("code",{style:d},"errorElement")," prop on your route.")),R.createElement(R.Fragment,null,R.createElement("h2",null,"Unexpected Application Error!"),R.createElement("h3",{style:{fontStyle:"italic"}},u),r?R.createElement("pre",{style:f},r):null,h)}var tg=R.createElement(eg,null),Rp=class extends R.Component{constructor(i){super(i),this.state={location:i.location,revalidation:i.revalidation,error:i.error}}static getDerivedStateFromError(i){return{error:i}}static getDerivedStateFromProps(i,u){return u.location!==i.location||u.revalidation!=="idle"&&i.revalidation==="idle"?{error:i.error,location:i.location,revalidation:i.revalidation}:{error:i.error!==void 0?i.error:u.error,location:u.location,revalidation:i.revalidation||u.revalidation}}componentDidCatch(i,u){this.props.onError?this.props.onError(i,u):console.error("React Router caught the following error during render",i)}render(){let i=this.state.error;if(this.context&&typeof i=="object"&&i&&"digest"in i&&typeof i.digest=="string"){const r=J0(i.digest);r&&(i=r)}let u=i!==void 0?R.createElement(ya.Provider,{value:this.props.routeContext},R.createElement(Yc.Provider,{value:i,children:this.props.component})):this.props.children;return this.context?R.createElement(ag,{error:i},u):u}};Rp.contextType=K0;var jc=new WeakMap;function ag({children:i,error:u}){let{basename:r}=R.useContext(ra);if(typeof u=="object"&&u&&"digest"in u&&typeof u.digest=="string"){let c=Q0(u.digest);if(c){let f=jc.get(u);if(f)throw f;let d=jp(c.location,r);if(Sp&&!jc.get(u))if(d.isExternal||c.reloadDocument)window.location.href=d.absoluteURL||d.to;else{const h=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(d.to,{replace:c.replace}));throw jc.set(u,h),h}return R.createElement("meta",{httpEquiv:"refresh",content:`0;url=${d.absoluteURL||d.to}`})}}return i}function ng({routeContext:i,match:u,children:r}){let c=R.useContext(wl);return c&&c.static&&c.staticContext&&(u.route.errorElement||u.route.ErrorBoundary)&&(c.staticContext._deepestRenderedBoundaryId=u.route.id),R.createElement(ya.Provider,{value:i},r)}function lg(i,u=[],r=null,c=null,f=null){if(i==null){if(!r)return null;if(r.errors)i=r.matches;else if(u.length===0&&!r.initialized&&r.matches.length>0)i=r.matches;else return null}let d=i,h=r?.errors;if(h!=null){let C=d.findIndex(_=>_.route.id&&h?.[_.route.id]!==void 0);dt(C>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(h).join(",")}`),d=d.slice(0,Math.min(d.length,C+1))}let m=!1,x=-1;if(r)for(let C=0;C<d.length;C++){let _=d[C];if((_.route.HydrateFallback||_.route.hydrateFallbackElement)&&(x=C),_.route.id){let{loaderData:A,errors:w}=r,N=_.route.loader&&!A.hasOwnProperty(_.route.id)&&(!w||w[_.route.id]===void 0);if(_.route.lazy||N){m=!0,x>=0?d=d.slice(0,x+1):d=[d[0]];break}}}let g=r&&c?(C,_)=>{c(C,{location:r.location,params:r.matches?.[0]?.params??{},unstable_pattern:V0(r.matches),errorInfo:_})}:void 0;return d.reduceRight((C,_,A)=>{let w,N=!1,p=null,b=null;r&&(w=h&&_.route.id?h[_.route.id]:void 0,p=_.route.errorElement||tg,m&&(x<0&&A===0?(Op("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),N=!0,b=null):x===A&&(N=!0,b=_.route.hydrateFallbackElement||null)));let v=u.concat(d.slice(0,A+1)),j=()=>{let k;return w?k=p:N?k=b:_.route.Component?k=R.createElement(_.route.Component,null):_.route.element?k=_.route.element:k=C,R.createElement(ng,{match:_,routeContext:{outlet:C,matches:v,isDataRoute:r!=null},children:k})};return r&&(_.route.ErrorBoundary||_.route.errorElement||A===0)?R.createElement(Rp,{location:r.location,revalidation:r.revalidation,component:p,error:w,children:j(),routeContext:{outlet:null,matches:v,isDataRoute:!0},onError:g}):j()},null)}function Vc(i){return`${i} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function ig(i){let u=R.useContext(wl);return dt(u,Vc(i)),u}function sg(i){let u=R.useContext(tr);return dt(u,Vc(i)),u}function rg(i){let u=R.useContext(ya);return dt(u,Vc(i)),u}function Gc(i){let u=rg(i),r=u.matches[u.matches.length-1];return dt(r.route.id,`${i} can only be used on routes that contain a unique "id"`),r.route.id}function og(){return Gc("useRouteId")}function cg(){let i=R.useContext(Yc),u=sg("useRouteError"),r=Gc("useRouteError");return i!==void 0?i:u.errors?.[r]}function ug(){let{router:i}=ig("useNavigate"),u=Gc("useNavigate"),r=R.useRef(!1);return kp(()=>{r.current=!0}),R.useCallback(async(f,d={})=>{ba(r.current,Ep),r.current&&(typeof f=="number"?await i.navigate(f):await i.navigate(f,{fromRouteId:u,...d}))},[i,u])}var Fh={};function Op(i,u,r){!u&&!Fh[i]&&(Fh[i]=!0,ba(!1,r))}R.memo(dg);function dg({routes:i,future:u,state:r,onError:c}){return zp(i,void 0,r,c,u)}function ga(i){dt(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function fg({basename:i="/",children:u=null,location:r,navigationType:c="POP",navigator:f,static:d=!1,unstable_useTransitions:h}){dt(!_i(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let m=i.replace(/^\/*/,"/"),x=R.useMemo(()=>({basename:m,navigator:f,static:d,unstable_useTransitions:h,future:{}}),[m,f,d,h]);typeof r=="string"&&(r=vl(r));let{pathname:g="/",search:C="",hash:_="",state:A=null,key:w="default"}=r,N=R.useMemo(()=>{let p=Ya(g,m);return p==null?null:{location:{pathname:p,search:C,hash:_,state:A,key:w},navigationType:c}},[m,g,C,_,A,w,c]);return ba(N!=null,`<Router basename="${m}"> is not able to match the URL "${g}${C}${_}" because it does not start with the basename, so the <Router> won't render anything.`),N==null?null:R.createElement(ra.Provider,{value:x},R.createElement(ji.Provider,{children:u,value:N}))}function hg({children:i,location:u}){return W0(Tc(i),u)}function Tc(i,u=[]){let r=[];return R.Children.forEach(i,(c,f)=>{if(!R.isValidElement(c))return;let d=[...u,f];if(c.type===R.Fragment){r.push.apply(r,Tc(c.props.children,d));return}dt(c.type===ga,`[${typeof c.type=="string"?c.type:c.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),dt(!c.props.index||!c.props.children,"An index route cannot have child routes.");let h={id:c.props.id||d.join("-"),caseSensitive:c.props.caseSensitive,element:c.props.element,Component:c.props.Component,index:c.props.index,path:c.props.path,middleware:c.props.middleware,loader:c.props.loader,action:c.props.action,hydrateFallbackElement:c.props.hydrateFallbackElement,HydrateFallback:c.props.HydrateFallback,errorElement:c.props.errorElement,ErrorBoundary:c.props.ErrorBoundary,hasErrorBoundary:c.props.hasErrorBoundary===!0||c.props.ErrorBoundary!=null||c.props.errorElement!=null,shouldRevalidate:c.props.shouldRevalidate,handle:c.props.handle,lazy:c.props.lazy};c.props.children&&(h.children=Tc(c.props.children,d)),r.push(h)}),r}var Js="get",Fs="application/x-www-form-urlencoded";function ar(i){return typeof HTMLElement<"u"&&i instanceof HTMLElement}function pg(i){return ar(i)&&i.tagName.toLowerCase()==="button"}function mg(i){return ar(i)&&i.tagName.toLowerCase()==="form"}function xg(i){return ar(i)&&i.tagName.toLowerCase()==="input"}function gg(i){return!!(i.metaKey||i.altKey||i.ctrlKey||i.shiftKey)}function bg(i,u){return i.button===0&&(!u||u==="_self")&&!gg(i)}var Ys=null;function yg(){if(Ys===null)try{new FormData(document.createElement("form"),0),Ys=!1}catch{Ys=!0}return Ys}var vg=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function _c(i){return i!=null&&!vg.has(i)?(ba(!1,`"${i}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Fs}"`),null):i}function wg(i,u){let r,c,f,d,h;if(mg(i)){let m=i.getAttribute("action");c=m?Ya(m,u):null,r=i.getAttribute("method")||Js,f=_c(i.getAttribute("enctype"))||Fs,d=new FormData(i)}else if(pg(i)||xg(i)&&(i.type==="submit"||i.type==="image")){let m=i.form;if(m==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let x=i.getAttribute("formaction")||m.getAttribute("action");if(c=x?Ya(x,u):null,r=i.getAttribute("formmethod")||m.getAttribute("method")||Js,f=_c(i.getAttribute("formenctype"))||_c(m.getAttribute("enctype"))||Fs,d=new FormData(m,i),!yg()){let{name:g,type:C,value:_}=i;if(C==="image"){let A=g?`${g}.`:"";d.append(`${A}x`,"0"),d.append(`${A}y`,"0")}else g&&d.append(g,_)}}else{if(ar(i))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r=Js,c=null,f=Fs,h=i}return d&&f==="text/plain"&&(h=d,d=void 0),{action:c,method:r.toLowerCase(),encType:f,formData:d,body:h}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Kc(i,u){if(i===!1||i===null||typeof i>"u")throw new Error(u)}function Sg(i,u,r,c){let f=typeof i=="string"?new URL(i,typeof window>"u"?"server://singlefetch/":window.location.origin):i;return r?f.pathname.endsWith("/")?f.pathname=`${f.pathname}_.${c}`:f.pathname=`${f.pathname}.${c}`:f.pathname==="/"?f.pathname=`_root.${c}`:u&&Ya(f.pathname,u)==="/"?f.pathname=`${u.replace(/\/$/,"")}/_root.${c}`:f.pathname=`${f.pathname.replace(/\/$/,"")}.${c}`,f}async function jg(i,u){if(i.id in u)return u[i.id];try{let r=await import(i.module);return u[i.id]=r,r}catch(r){return console.error(`Error loading route module \`${i.module}\`, reloading page...`),console.error(r),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function _g(i){return i==null?!1:i.href==null?i.rel==="preload"&&typeof i.imageSrcSet=="string"&&typeof i.imageSizes=="string":typeof i.rel=="string"&&typeof i.href=="string"}async function Ng(i,u,r){let c=await Promise.all(i.map(async f=>{let d=u.routes[f.route.id];if(d){let h=await jg(d,r);return h.links?h.links():[]}return[]}));return Ag(c.flat(1).filter(_g).filter(f=>f.rel==="stylesheet"||f.rel==="preload").map(f=>f.rel==="stylesheet"?{...f,rel:"prefetch",as:"style"}:{...f,rel:"prefetch"}))}function Ph(i,u,r,c,f,d){let h=(x,g)=>r[g]?x.route.id!==r[g].route.id:!0,m=(x,g)=>r[g].pathname!==x.pathname||r[g].route.path?.endsWith("*")&&r[g].params["*"]!==x.params["*"];return d==="assets"?u.filter((x,g)=>h(x,g)||m(x,g)):d==="data"?u.filter((x,g)=>{let C=c.routes[x.route.id];if(!C||!C.hasLoader)return!1;if(h(x,g)||m(x,g))return!0;if(x.route.shouldRevalidate){let _=x.route.shouldRevalidate({currentUrl:new URL(f.pathname+f.search+f.hash,window.origin),currentParams:r[0]?.params||{},nextUrl:new URL(i,window.origin),nextParams:x.params,defaultShouldRevalidate:!0});if(typeof _=="boolean")return _}return!0}):[]}function Cg(i,u,{includeHydrateFallback:r}={}){return Eg(i.map(c=>{let f=u.routes[c.route.id];if(!f)return[];let d=[f.module];return f.clientActionModule&&(d=d.concat(f.clientActionModule)),f.clientLoaderModule&&(d=d.concat(f.clientLoaderModule)),r&&f.hydrateFallbackModule&&(d=d.concat(f.hydrateFallbackModule)),f.imports&&(d=d.concat(f.imports)),d}).flat(1))}function Eg(i){return[...new Set(i)]}function kg(i){let u={},r=Object.keys(i).sort();for(let c of r)u[c]=i[c];return u}function Ag(i,u){let r=new Set;return new Set(u),i.reduce((c,f)=>{let d=JSON.stringify(kg(f));return r.has(d)||(r.add(d),c.push({key:d,link:f})),c},[])}function Tp(){let i=R.useContext(wl);return Kc(i,"You must render this element inside a <DataRouterContext.Provider> element"),i}function zg(){let i=R.useContext(tr);return Kc(i,"You must render this element inside a <DataRouterStateContext.Provider> element"),i}var Ic=R.createContext(void 0);Ic.displayName="FrameworkContext";function Dp(){let i=R.useContext(Ic);return Kc(i,"You must render this element inside a <HydratedRouter> element"),i}function Rg(i,u){let r=R.useContext(Ic),[c,f]=R.useState(!1),[d,h]=R.useState(!1),{onFocus:m,onBlur:x,onMouseEnter:g,onMouseLeave:C,onTouchStart:_}=u,A=R.useRef(null);R.useEffect(()=>{if(i==="render"&&h(!0),i==="viewport"){let p=v=>{v.forEach(j=>{h(j.isIntersecting)})},b=new IntersectionObserver(p,{threshold:.5});return A.current&&b.observe(A.current),()=>{b.disconnect()}}},[i]),R.useEffect(()=>{if(c){let p=setTimeout(()=>{h(!0)},100);return()=>{clearTimeout(p)}}},[c]);let w=()=>{f(!0)},N=()=>{f(!1),h(!1)};return r?i!=="intent"?[d,A,{}]:[d,A,{onFocus:yi(m,w),onBlur:yi(x,N),onMouseEnter:yi(g,w),onMouseLeave:yi(C,N),onTouchStart:yi(_,w)}]:[!1,A,{}]}function yi(i,u){return r=>{i&&i(r),r.defaultPrevented||u(r)}}function Og({page:i,...u}){let{router:r}=Tp(),c=R.useMemo(()=>gp(r.routes,i,r.basename),[r.routes,i,r.basename]);return c?R.createElement(Dg,{page:i,matches:c,...u}):null}function Tg(i){let{manifest:u,routeModules:r}=Dp(),[c,f]=R.useState([]);return R.useEffect(()=>{let d=!1;return Ng(i,u,r).then(h=>{d||f(h)}),()=>{d=!0}},[i,u,r]),c}function Dg({page:i,matches:u,...r}){let c=mn(),{future:f,manifest:d,routeModules:h}=Dp(),{basename:m}=Tp(),{loaderData:x,matches:g}=zg(),C=R.useMemo(()=>Ph(i,u,g,d,c,"data"),[i,u,g,d,c]),_=R.useMemo(()=>Ph(i,u,g,d,c,"assets"),[i,u,g,d,c]),A=R.useMemo(()=>{if(i===c.pathname+c.search+c.hash)return[];let p=new Set,b=!1;if(u.forEach(j=>{let k=d.routes[j.route.id];!k||!k.hasLoader||(!C.some(B=>B.route.id===j.route.id)&&j.route.id in x&&h[j.route.id]?.shouldRevalidate||k.hasClientLoader?b=!0:p.add(j.route.id))}),p.size===0)return[];let v=Sg(i,m,f.unstable_trailingSlashAwareDataRequests,"data");return b&&p.size>0&&v.searchParams.set("_routes",u.filter(j=>p.has(j.route.id)).map(j=>j.route.id).join(",")),[v.pathname+v.search]},[m,f.unstable_trailingSlashAwareDataRequests,x,c,d,C,u,i,h]),w=R.useMemo(()=>Cg(_,d),[_,d]),N=Tg(_);return R.createElement(R.Fragment,null,A.map(p=>R.createElement("link",{key:p,rel:"prefetch",as:"fetch",href:p,...r})),w.map(p=>R.createElement("link",{key:p,rel:"modulepreload",href:p,...r})),N.map(({key:p,link:b})=>R.createElement("link",{key:p,nonce:r.nonce,...b,crossOrigin:b.crossOrigin??r.crossOrigin})))}function Mg(...i){return u=>{i.forEach(r=>{typeof r=="function"?r(u):r!=null&&(r.current=u)})}}var Ug=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Ug&&(window.__reactRouterVersion="7.13.0")}catch{}function Bg({basename:i,children:u,unstable_useTransitions:r,window:c}){let f=R.useRef();f.current==null&&(f.current=g0({window:c,v5Compat:!0}));let d=f.current,[h,m]=R.useState({action:d.action,location:d.location}),x=R.useCallback(g=>{r===!1?m(g):R.startTransition(()=>m(g))},[r]);return R.useLayoutEffect(()=>d.listen(x),[d,x]),R.createElement(fg,{basename:i,children:u,location:h.location,navigationType:h.action,navigator:d,unstable_useTransitions:r})}var Mp=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Up=R.forwardRef(function({onClick:u,discover:r="render",prefetch:c="none",relative:f,reloadDocument:d,replace:h,state:m,target:x,to:g,preventScrollReset:C,viewTransition:_,unstable_defaultShouldRevalidate:A,...w},N){let{basename:p,unstable_useTransitions:b}=R.useContext(ra),v=typeof g=="string"&&Mp.test(g),j=jp(g,p);g=j.to;let k=F0(g,{relative:f}),[B,D,M]=Rg(c,w),O=Yg(g,{replace:h,state:m,target:x,preventScrollReset:C,relative:f,viewTransition:_,unstable_defaultShouldRevalidate:A,unstable_useTransitions:b});function X(oe){u&&u(oe),oe.defaultPrevented||O(oe)}let $=R.createElement("a",{...w,...M,href:j.absoluteURL||k,onClick:j.isExternal||d?u:X,ref:Mg(N,D),target:x,"data-discover":!v&&r==="render"?"true":void 0});return B&&!v?R.createElement(R.Fragment,null,$,R.createElement(Og,{page:k})):$});Up.displayName="Link";var Lg=R.forwardRef(function({"aria-current":u="page",caseSensitive:r=!1,className:c="",end:f=!1,style:d,to:h,viewTransition:m,children:x,...g},C){let _=Ni(h,{relative:g.relative}),A=mn(),w=R.useContext(tr),{navigator:N,basename:p}=R.useContext(ra),b=w!=null&&Zg(_)&&m===!0,v=N.encodeLocation?N.encodeLocation(_).pathname:_.pathname,j=A.pathname,k=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;r||(j=j.toLowerCase(),k=k?k.toLowerCase():null,v=v.toLowerCase()),k&&p&&(k=Ya(k,p)||k);const B=v!=="/"&&v.endsWith("/")?v.length-1:v.length;let D=j===v||!f&&j.startsWith(v)&&j.charAt(B)==="/",M=k!=null&&(k===v||!f&&k.startsWith(v)&&k.charAt(v.length)==="/"),O={isActive:D,isPending:M,isTransitioning:b},X=D?u:void 0,$;typeof c=="function"?$=c(O):$=[c,D?"active":null,M?"pending":null,b?"transitioning":null].filter(Boolean).join(" ");let oe=typeof d=="function"?d(O):d;return R.createElement(Up,{...g,"aria-current":X,className:$,ref:C,style:oe,to:h,viewTransition:m},typeof x=="function"?x(O):x)});Lg.displayName="NavLink";var Hg=R.forwardRef(({discover:i="render",fetcherKey:u,navigate:r,reloadDocument:c,replace:f,state:d,method:h=Js,action:m,onSubmit:x,relative:g,preventScrollReset:C,viewTransition:_,unstable_defaultShouldRevalidate:A,...w},N)=>{let{unstable_useTransitions:p}=R.useContext(ra),b=Kg(),v=Ig(m,{relative:g}),j=h.toLowerCase()==="get"?"get":"post",k=typeof m=="string"&&Mp.test(m),B=D=>{if(x&&x(D),D.defaultPrevented)return;D.preventDefault();let M=D.nativeEvent.submitter,O=M?.getAttribute("formmethod")||h,X=()=>b(M||D.currentTarget,{fetcherKey:u,method:O,navigate:r,replace:f,state:d,relative:g,preventScrollReset:C,viewTransition:_,unstable_defaultShouldRevalidate:A});p&&r!==!1?R.startTransition(()=>X()):X()};return R.createElement("form",{ref:N,method:j,action:v,onSubmit:c?x:B,...w,"data-discover":!k&&i==="render"?"true":void 0})});Hg.displayName="Form";function qg(i){return`${i} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Bp(i){let u=R.useContext(wl);return dt(u,qg(i)),u}function Yg(i,{target:u,replace:r,state:c,preventScrollReset:f,relative:d,viewTransition:h,unstable_defaultShouldRevalidate:m,unstable_useTransitions:x}={}){let g=Dn(),C=mn(),_=Ni(i,{relative:d});return R.useCallback(A=>{if(bg(A,u)){A.preventDefault();let w=r!==void 0?r:wi(C)===wi(_),N=()=>g(i,{replace:w,state:c,preventScrollReset:f,relative:d,viewTransition:h,unstable_defaultShouldRevalidate:m});x?R.startTransition(()=>N()):N()}},[C,g,_,r,c,u,i,f,d,h,m,x])}var Vg=0,Gg=()=>`__${String(++Vg)}__`;function Kg(){let{router:i}=Bp("useSubmit"),{basename:u}=R.useContext(ra),r=og(),c=i.fetch,f=i.navigate;return R.useCallback(async(d,h={})=>{let{action:m,method:x,encType:g,formData:C,body:_}=wg(d,u);if(h.navigate===!1){let A=h.fetcherKey||Gg();await c(A,r,h.action||m,{unstable_defaultShouldRevalidate:h.unstable_defaultShouldRevalidate,preventScrollReset:h.preventScrollReset,formData:C,body:_,formMethod:h.method||x,formEncType:h.encType||g,flushSync:h.flushSync})}else await f(h.action||m,{unstable_defaultShouldRevalidate:h.unstable_defaultShouldRevalidate,preventScrollReset:h.preventScrollReset,formData:C,body:_,formMethod:h.method||x,formEncType:h.encType||g,replace:h.replace,state:h.state,fromRouteId:r,flushSync:h.flushSync,viewTransition:h.viewTransition})},[c,f,u,r])}function Ig(i,{relative:u}={}){let{basename:r}=R.useContext(ra),c=R.useContext(ya);dt(c,"useFormAction must be used inside a RouteContext");let[f]=c.matches.slice(-1),d={...Ni(i||".",{relative:u})},h=mn();if(i==null){d.search=h.search;let m=new URLSearchParams(d.search),x=m.getAll("index");if(x.some(C=>C==="")){m.delete("index"),x.filter(_=>_).forEach(_=>m.append("index",_));let C=m.toString();d.search=C?`?${C}`:""}}return(!i||i===".")&&f.route.index&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r!=="/"&&(d.pathname=d.pathname==="/"?r:qa([r,d.pathname])),wi(d)}function Zg(i,{relative:u}={}){let r=R.useContext(Np);dt(r!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:c}=Bp("useViewTransitionState"),f=Ni(i,{relative:u});if(!r.isTransitioning)return!1;let d=Ya(r.currentLocation.pathname,c)||r.currentLocation.pathname,h=Ya(r.nextLocation.pathname,c)||r.nextLocation.pathname;return Ps(f.pathname,h)!=null||Ps(f.pathname,d)!=null}var Xg=xp();const _e=Fe.memo(({name:i,className:u="",fill:r=!1})=>l.jsx("span",{className:`material-symbols-outlined ${u}`,style:{fontVariationSettings:r?"'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24":"'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24"},"aria-hidden":"true",children:i})),$g=({onNavigate:i,onNewTask:u,onLogout:r,currentScreen:c})=>l.jsxs("aside",{className:"w-20 h-full border-r border-white/10 glass flex flex-col items-center py-8 shrink-0 z-50",children:[l.jsx("button",{onClick:()=>i("dashboard"),className:"mb-12 hover:opacity-80 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 rounded-lg","aria-label":"Go to Dashboard",title:"Go to Dashboard",children:l.jsx("img",{src:"/figranium_icon.svg",alt:"Figranium Logo",className:"w-10 h-10",onError:f=>{f.currentTarget.src="/figranium_icon.svg"}})}),l.jsxs("div",{className:"flex-1 flex flex-col gap-6",children:[l.jsx("button",{onClick:u,className:"w-12 h-12 rounded-2xl flex items-center justify-center text-white bg-white/5 hover:bg-white/10 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"New Task","aria-label":"New Task",children:l.jsx(_e,{name:"add",className:"text-2xl"})}),l.jsx("button",{onClick:()=>i("dashboard"),className:`w-12 h-12 rounded-2xl flex items-center justify-center transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${c==="dashboard"?"bg-white/10 text-white":"text-gray-500 hover:bg-white/5 hover:text-white"}`,title:"Dashboard","aria-label":"Dashboard",children:l.jsx(_e,{name:"home",className:"text-2xl"})}),l.jsx("button",{onClick:()=>i("settings"),className:`w-12 h-12 rounded-2xl flex items-center justify-center transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${c==="settings"?"bg-white/10 text-white":"text-gray-500 hover:bg-white/5 hover:text-white"}`,title:"Settings","aria-label":"Settings",children:l.jsx(_e,{name:"settings",className:"text-2xl"})}),l.jsx("button",{onClick:()=>i("executions"),className:`w-12 h-12 rounded-2xl flex items-center justify-center transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${c==="executions"?"bg-white/10 text-white":"text-gray-500 hover:bg-white/5 hover:text-white"}`,title:"Executions","aria-label":"Executions",children:l.jsx(_e,{name:"history",className:"text-2xl"})}),l.jsx("button",{onClick:()=>i("captures"),className:`w-12 h-12 rounded-2xl flex items-center justify-center transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${c==="captures"?"bg-white/10 text-white":"text-gray-500 hover:bg-white/5 hover:text-white"}`,title:"Captures","aria-label":"Captures",children:l.jsx(_e,{name:"photo_camera",className:"text-2xl"})})]}),l.jsx("button",{onClick:r,className:"w-12 h-12 rounded-2xl flex items-center justify-center text-gray-500 hover:bg-red-500/10 hover:text-red-500 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"Logout","aria-label":"Logout",children:l.jsx(_e,{name:"logout",className:"text-2xl"})})]}),Qg=Fe.memo($g),Jg=({status:i,onSubmit:u,error:r,busy:c=!1})=>{const[f,d]=R.useState(""),[h,m]=R.useState(""),[x,g]=R.useState(""),[C,_]=R.useState(""),A=N=>{N.preventDefault(),u(h,x,f,C)},w=i==="setup"?c?"Creating account...":"Create Account":c?"Authenticating...":"Authenticate";return l.jsxs("div",{className:"fixed inset-0 z-[100] bg-[#020202] flex items-center justify-center",children:[l.jsx("div",{className:"absolute inset-0 opacity-[0.03] pointer-events-none",style:{backgroundImage:"radial-gradient(#fff 1px, transparent 1px)",backgroundSize:"40px 40px"}}),l.jsxs("div",{className:"w-[400px] glass-card p-10 rounded-[48px] space-y-8 relative",children:[l.jsxs("div",{className:"text-center space-y-3",children:[l.jsx("img",{src:"/figranium_logo.svg",alt:"Figranium",className:"h-24 mx-auto object-contain"}),l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em] leading-relaxed max-w-[200px] mx-auto",children:"Deterministic Control for an Agentic World"})]}),l.jsxs("form",{onSubmit:A,className:"space-y-8",children:[l.jsxs("div",{className:"space-y-4",children:[i==="setup"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{htmlFor:"auth-name",className:"text-[9px] font-bold text-gray-400 uppercase tracking-[0.2em]",children:"Name"}),l.jsx("input",{id:"auth-name",type:"text",value:f,onChange:N=>d(N.target.value),placeholder:"Full Name",className:"w-full bg-white/[0.05] border border-white/10 rounded-2xl px-5 py-4 text-sm focus:outline-none focus:border-white/30 transition-all placeholder:text-gray-600",autoComplete:"name"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{htmlFor:"auth-email",className:"text-[9px] font-bold text-gray-400 uppercase tracking-[0.2em]",children:"Email"}),l.jsx("input",{id:"auth-email",type:"email",value:h,onChange:N=>m(N.target.value),placeholder:"user@example.com",className:"w-full bg-white/[0.05] border border-white/10 rounded-2xl px-5 py-4 text-sm focus:outline-none focus:border-white/30 transition-all placeholder:text-gray-600",required:!0,autoComplete:"email"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{htmlFor:"auth-pass",className:"text-[9px] font-bold text-gray-400 uppercase tracking-[0.2em]",children:"Password"}),l.jsx("input",{id:"auth-pass",type:"password",value:x,onChange:N=>g(N.target.value),placeholder:"••••••••",className:"w-full bg-white/[0.05] border border-white/10 rounded-2xl px-5 py-4 text-sm focus:outline-none focus:border-white/30 transition-all placeholder:text-gray-600",required:!0,autoComplete:i==="setup"?"new-password":"current-password"})]}),i==="setup"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{htmlFor:"auth-pass-confirm",className:"text-[9px] font-bold text-gray-400 uppercase tracking-[0.2em]",children:"Confirm Password"}),l.jsx("input",{id:"auth-pass-confirm",type:"password",value:C,onChange:N=>_(N.target.value),placeholder:"••••••••",className:"w-full bg-white/[0.05] border border-white/10 rounded-2xl px-5 py-4 text-sm focus:outline-none focus:border-white/30 transition-all placeholder:text-gray-600",required:!0,autoComplete:"new-password"})]})]}),l.jsxs("button",{type:"submit",disabled:c,"aria-busy":c,className:"shine-effect w-full bg-white text-black py-4 rounded-2xl font-bold text-[10px] tracking-[0.3em] uppercase hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-60 disabled:cursor-default flex items-center justify-center gap-3",children:[c&&l.jsx("div",{className:"w-4 h-4 border-2 border-black/10 border-t-black rounded-full animate-spin"}),w]}),r&&l.jsx("div",{role:"alert",className:"text-[9px] font-bold text-red-500 text-center uppercase tracking-widest",children:r})]})]})]})};function Fg(i){return i>=1e6?`${(i/1e6).toFixed(1).replace(/\.0$/,"")}m`:i>=1e3?`${(i/1e3).toFixed(1).replace(/\.0$/,"")}k`:String(i)}const Pg=({className:i})=>l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:i,"aria-hidden":"true",children:l.jsx("path",{d:"M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.166 6.839 9.489.5.092.682-.217.682-.482 0-.237-.008-.866-.013-1.699-2.782.603-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.463-1.11-1.463-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.831.092-.646.35-1.086.636-1.336-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.564 9.564 0 0112 6.844c.85.004 1.705.114 2.504.336 1.909-1.294 2.747-1.025 2.747-1.025.546 1.379.202 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.578.688.48C19.138 20.161 22 16.418 22 12c0-5.523-4.477-10-10-10z"})});function Lp({className:i=""}){const[u,r]=R.useState("—"),c=d=>{const h=d.currentTarget.getBoundingClientRect(),m=Math.min(1,Math.max(0,(d.clientX-h.left)/h.width)),x=Math.min(1,Math.max(0,(d.clientY-h.top)/h.height));d.currentTarget.style.setProperty("--beam-x",`${(m*100).toFixed(2)}%`),d.currentTarget.style.setProperty("--beam-y",`${(x*100).toFixed(2)}%`)},f=d=>{d.currentTarget.style.setProperty("--beam-x","50%"),d.currentTarget.style.setProperty("--beam-y","50%")};return R.useEffect(()=>{let d=!0;return fetch("https://api.github.com/repos/figranium/figranium").then(h=>h.ok?h.json():null).then(h=>{!d||!h?.stargazers_count||r(Fg(Number(h.stargazers_count)))}).catch(()=>{d&&r("—")}),()=>{d=!1}},[]),l.jsxs("a",{href:"https://github.com/figranium/figranium",target:"_blank",rel:"noreferrer",onPointerMove:c,onPointerLeave:f,className:`gh-pill beam-follow inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-2 text-[11px] uppercase tracking-[0.25em] text-white/70 transition hover:border-white/20 hover:bg-white/10 hover:text-white ${i}`,"aria-label":"Star Figranium on GitHub",children:[l.jsx(Pg,{className:"h-4 w-4"}),"GitHub",l.jsx("span",{className:"mx-1 h-3 w-px bg-white/20","aria-hidden":"true"}),l.jsx(_e,{name:"star",className:"text-base",fill:!0}),u]})}const Wg=({tasks:i,onNewTask:u,onEditTask:r,onDeleteTask:c,onExportTasks:f,onImportTasks:d})=>{const h=R.useRef(null),[m,x]=Fe.useState(!1),[g,C]=Fe.useState([]),_=p=>{try{return p?`https://www.google.com/s2/favicons?domain=${new URL(p).hostname}&sz=64`:null}catch{return null}},A=()=>{h.current?.click()},w=p=>{const b=Array.from(p.target.files||[]);b.length>0&&b.forEach(v=>d(v)),p.target.value=""},N=p=>{C(b=>b.includes(p)?b.filter(v=>v!==p):[...b,p])};return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex-1 overflow-hidden animate-in fade-in duration-500 bg-black",children:l.jsxs("div",{className:"h-full flex flex-col px-12 py-12 max-w-7xl mx-auto space-y-12 w-full",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsx("div",{className:"space-y-2",children:l.jsx("h2",{className:"text-4xl font-bold tracking-tighter text-white",children:"Dashboard"})}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(Lp,{}),l.jsxs("button",{onClick:()=>{C([]),x(!0)},className:"px-4 py-3 rounded-2xl border border-white/10 text-white text-[9px] font-bold uppercase tracking-[0.3em] hover:bg-white/5 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx(_e,{name:"download",className:"w-4 h-4 inline-block mr-2 text-[16px] align-sub"}),"Export"]}),l.jsxs("button",{onClick:A,className:"px-4 py-3 rounded-2xl border border-white/10 text-white text-[9px] font-bold uppercase tracking-[0.3em] hover:bg-white/5 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx(_e,{name:"upload",className:"w-4 h-4 inline-block mr-2 text-[16px] align-sub"}),"Import"]}),l.jsx("button",{onClick:u,className:"shine-effect bg-white text-black px-8 py-3 rounded-2xl font-bold text-[10px] tracking-[0.2em] uppercase transition-all hover:scale-105 active:scale-95 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:"+ New Task"}),l.jsx("input",{ref:h,type:"file",accept:"application/json",multiple:!0,className:"hidden",onChange:w})]})]}),l.jsxs("div",{className:"relative flex-1 min-h-0",children:[l.jsx("div",{className:"pointer-events-none absolute top-0 left-0 right-0 h-10 bg-gradient-to-b from-[#050505] via-[#050505]/50 to-transparent z-10"}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 content-start gap-6 overflow-y-auto custom-scrollbar pb-12 pr-4 h-full",children:i.map(p=>{const b=_(p.url);return l.jsxs("div",{className:"bg-[#050505] border border-white/10 p-6 rounded-2xl flex flex-col gap-6 group hover:-translate-y-1 hover:border-white/30 transition-all shadow-xl hover:bg-[#0a0a0a]",children:[l.jsxs("div",{className:"flex justify-between items-start",children:[l.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/5 border border-white/10 flex items-center justify-center overflow-hidden",children:b?l.jsx("img",{src:b,alt:"",className:"w-6 h-6 object-contain grayscale opacity-100 group-hover:grayscale-0 transition-all duration-300",onError:v=>{v.target.style.display="none"}}):l.jsx(_e,{name:"public",className:"text-gray-500 text-xl"})}),l.jsx("div",{className:"px-3 py-1 rounded-lg bg-white/5 text-[7px] font-bold uppercase tracking-widest text-white/60",children:p.mode})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-bold text-white truncate",children:p.name||"Untitled"}),l.jsx("p",{className:"text-[10px] text-gray-600 font-mono truncate mt-1",children:p.url||"Target undefined"})]}),l.jsxs("div",{className:"flex gap-3 pt-4 border-t border-white/5",children:[l.jsx("button",{onClick:()=>r(p),className:"flex-1 py-2 rounded-lg bg-white text-black text-[9px] font-bold uppercase tracking-widest hover:scale-105 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:"Edit Task"}),l.jsx("button",{onClick:()=>c(p.id),className:"w-10 h-10 rounded-lg bg-transparent border border-white/10 flex items-center justify-center hover:bg-red-500/10 hover:text-red-500 hover:border-red-500/30 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Delete task",title:"Delete task",children:l.jsx(_e,{name:"close",className:"text-base"})})]})]},p.id)})})]}),i.length===0&&l.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:l.jsxs("button",{onClick:u,className:"w-full max-w-[400px] bg-[#0a0a0a] border border-dashed border-white/15 rounded-2xl p-8 hover:border-white/30 hover:bg-white/[0.03] transition-all flex flex-col items-center justify-center gap-4 group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/5 group-hover:bg-white/10 transition-all flex items-center justify-center border border-white/5",children:l.jsx(_e,{name:"add",className:"text-3xl text-gray-500 group-hover:text-white transition-colors"})}),l.jsxs("div",{className:"text-center space-y-2",children:[l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.2em] text-white/70 group-hover:text-white transition-colors",children:"Create First Task"}),l.jsx("p",{className:"text-[10px] text-gray-500 max-w-[250px] mx-auto leading-relaxed group-hover:text-gray-400 transition-colors",children:"Get started by creating your first automation task. This will open the visual editor."})]})]})})]})}),m&&l.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 pb-20 sm:pb-6",children:[l.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-sm",onClick:()=>x(!1)}),l.jsxs("div",{className:"relative w-full max-w-lg bg-[#0a0a0a] border border-white/10 rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-full slide-up",children:[l.jsxs("div",{className:"p-6 sm:p-8 shrink-0",children:[l.jsx("h3",{className:"text-xl font-bold text-white tracking-tight",children:"Export Tasks"}),l.jsx("p",{className:"text-[11px] text-white/50 mt-2 font-mono",children:"Select the tasks you want to export."})]}),l.jsxs("div",{className:"px-6 sm:px-8 pb-4 flex items-center gap-3 shrink-0 border-b border-white/5",children:[l.jsx("button",{onClick:()=>C(i.map(p=>p.id)),className:"text-[10px] font-bold uppercase tracking-widest text-blue-400 hover:text-blue-300 transition-colors",children:"Select All"}),l.jsx("span",{className:"text-white/20",children:"|"}),l.jsx("button",{onClick:()=>C([]),className:"text-[10px] font-bold uppercase tracking-widest text-white/40 hover:text-white/80 transition-colors",children:"Deselect All"}),l.jsx("div",{className:"flex-1"}),l.jsxs("span",{className:"text-[10px] font-mono text-white/30",children:[g.length," selected"]})]}),l.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar p-6 sm:p-8 space-y-2",children:i.map(p=>l.jsxs("button",{onClick:()=>N(p.id),className:`w-full text-left p-4 rounded-2xl border transition-all flex items-center gap-4 ${g.includes(p.id)?"bg-blue-500/10 border-blue-500/30":"bg-white/5 border-white/5 hover:border-white/10"}`,children:[l.jsx("div",{className:`w-5 h-5 rounded flex items-center justify-center border transition-colors ${g.includes(p.id)?"bg-blue-500 border-blue-400 text-white":"border-white/20"}`,children:g.includes(p.id)&&l.jsx(_e,{name:"check",className:"text-[14px]"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm font-bold text-white truncate",children:p.name||"Untitled"}),l.jsx("div",{className:"text-[10px] text-white/40 font-mono truncate",children:p.url||"No URL"})]})]},p.id))}),l.jsxs("div",{className:"p-6 sm:p-8 bg-black/40 border-t border-white/5 flex gap-3 shrink-0",children:[l.jsx("button",{onClick:()=>x(!1),className:"flex-1 px-4 py-3 rounded-xl border border-white/10 text-white text-[10px] font-bold uppercase tracking-widest hover:bg-white/5 transition-all",children:"Cancel"}),l.jsxs("button",{onClick:()=>{f(g),x(!1)},disabled:g.length===0,className:`flex-1 px-4 py-3 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all ${g.length>0?"bg-white text-black hover:scale-105":"bg-white/10 text-white/30 cursor-not-allowed"}`,children:["Export (",g.length,")"]})]})]})]})]})},Wh=R.memo(Wg),Dc=[{type:"click",label:"Click",description:"Click an element",icon:"ads_click"},{type:"type",label:"Type",description:"Type text into a field",icon:"text_format"},{type:"hover",label:"Hover",description:"Hover an element",icon:"my_location"},{type:"press",label:"Press",description:"Press a key",icon:"keyboard"},{type:"wait",label:"Wait",description:"Pause for seconds",icon:"schedule"},{type:"wait_selector",label:"Wait for Selector",description:"Wait until element appears",icon:"schedule"},{type:"wait_downloads",label:"Wait for Downloads",description:"Wait until downloads finish",icon:"download"},{type:"scroll",label:"Scroll",description:"Scroll the page or container",icon:"swap_vert"},{type:"javascript",label:"JavaScript",description:"Run custom JS",icon:"code"},{type:"csv",label:"CSV",description:"Parse CSV into rows",icon:"table_chart"},{type:"merge",label:"Merge",description:"Merge inputs into a single output",icon:"layers"},{type:"screenshot",label:"Screenshot",description:"Capture a screenshot",icon:"photo_camera"},{type:"navigate",label:"Navigate To",description:"Navigate to a URL",icon:"navigation"},{type:"if",label:"If",description:"Conditional block start",icon:"call_split"},{type:"else",label:"Else",description:"Conditional alternate path",icon:"call_split"},{type:"end",label:"End Block",description:"Close a block",icon:"subdirectory_arrow_right"},{type:"while",label:"While",description:"Loop while condition true",icon:"repeat"},{type:"repeat",label:"Repeat N",description:"Repeat block N times",icon:"repeat"},{type:"foreach",label:"For Each",description:"Loop through items",icon:"list"},{type:"set",label:"Set Variable",description:"Update variable value",icon:"data_object"},{type:"stop",label:"Stop Task",description:"Stop task with status",icon:"stop"},{type:"on_error",label:"On Error",description:"Run on failure",icon:"warning"},{type:"start",label:"Start Task",description:"Run another task",icon:"play_circle"}],eb=({open:i,query:u,onQueryChange:r,onClose:c,onSelect:f})=>{const d=R.useRef(null),h=R.useMemo(()=>{const m=u.trim().toLowerCase();return m?Dc.filter(x=>x.label.toLowerCase().includes(m)||x.description.toLowerCase().includes(m)):Dc},[u]);return i?l.jsx("div",{className:"fixed inset-0 z-[190] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",onClick:c,children:l.jsxs("div",{className:"glass-card w-full max-w-xl rounded-[28px] border border-white/10 p-6 shadow-2xl",onClick:m=>m.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between mb-4",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-[9px] font-bold uppercase tracking-[0.4em] text-gray-500",children:"Add Block"}),l.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Search actions and control flow blocks."})]}),l.jsx("button",{onClick:c,className:"p-2 rounded-xl border border-white/10 text-white/70 hover:text-white hover:bg-white/5 transition-all","aria-label":"Close",children:l.jsx(_e,{name:"close",className:"text-base"})})]}),l.jsx("input",{ref:m=>{d.current=m,m&&m.focus()},value:u,onChange:m=>r(m.target.value),placeholder:"Type to filter (e.g., if, click, loop)",className:"w-full rounded-xl bg-black/40 border border-white/10 px-4 py-3 text-sm text-white placeholder:text-gray-600 focus:outline-none focus:border-white/30"}),l.jsxs("div",{className:"mt-4 max-h-[400px] overflow-y-auto custom-scrollbar pr-2",children:[l.jsx("div",{className:"grid grid-cols-2 gap-3 pb-2",children:h.map(m=>l.jsxs("button",{onClick:()=>f(m.type),className:"flex flex-col items-start gap-2 text-left p-4 rounded-2xl border border-white/5 bg-white/[0.02] hover:bg-white/[0.08] hover:border-white/20 transition-all hover:scale-[1.02] active:scale-95 group focus:outline-none focus:ring-2 focus:ring-blue-500/50",children:[l.jsx(_e,{name:m.icon||"extension",className:"text-2xl text-white/80 group-hover:text-white transition-colors shrink-0 mb-1"}),l.jsxs("div",{children:[l.jsx("div",{className:"text-[11px] font-bold uppercase tracking-widest text-white/90 group-hover:text-white mb-1",children:m.label}),l.jsx("div",{className:"text-[10px] text-gray-500 line-clamp-2 leading-relaxed",children:m.description})]})]},m.type))}),h.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No matches."})]})]})}):null},xt=i=>i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),tb=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","class","extends","super","import","from","export","default","await","async","typeof","instanceof","in","of","this"]),Hp=(i,u)=>{const r=/\{\$(\w+)\}/g;let c="",f=0,d;const h=x=>!!u&&(x in u||x==="now"),m=x=>{if(x==="now")return!0;const g=u?u[x]:void 0;return g&&g.value!==""&&g.value!==void 0&&g.value!==null};for(;(d=r.exec(i))!==null;){d.index>f&&(c+=xt(i.substring(f,d.index)));const x=d[1],g=h(x),C=m(x);c+=`<span class="${g?C?"var-highlight-default":"var-highlight":"var-highlight-undefined"}">${xt(d[0])}</span>`,f=r.lastIndex}return c+=xt(i.substring(f)),c},ab=i=>{const u=/("(?:\\.|[^"\\])*")|(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|\b(true|false|null)\b/g;let r="",c=0,f;for(;(f=u.exec(i))!==null;){f.index>c&&(r+=xt(i.substring(c,f.index)));const d=f[0];if(f[1]){let h=!1,m=f.index+d.length;for(;m<i.length&&/\s/.test(i[m]);)m+=1;i[m]===":"&&(h=!0),r+=`<span class="${h?"code-token-key":"code-token-string"}">${xt(d)}</span>`}else f[2]?r+=`<span class="code-token-number">${xt(d)}</span>`:r+=`<span class="code-token-boolean">${xt(d)}</span>`;c=u.lastIndex}return r+=xt(i.substring(c)),r},nb=(i,u)=>{const r=/(\{\$\w+\})|(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|(\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|(\btrue\b|\bfalse\b|\bnull\b|\bundefined\b)|(\b[A-Za-z_]\w*\b)/g;let c="",f=0,d;for(;(d=r.exec(i))!==null;){d.index>f&&(c+=xt(i.substring(f,d.index)));const h=d[0];if(d[1])c+=Hp(h,u);else if(d[2])c+=`<span class="code-token-comment">${xt(h)}</span>`;else if(d[3])c+=`<span class="code-token-string">${xt(h)}</span>`;else if(d[4])c+=`<span class="code-token-number">${xt(h)}</span>`;else if(d[5])c+=`<span class="code-token-boolean">${xt(h)}</span>`;else if(d[6]){const m=tb.has(h)?"code-token-keyword":"code-token-identifier";c+=`<span class="${m}">${xt(h)}</span>`}else c+=xt(h);f=r.lastIndex}return c+=xt(i.substring(f)),c},lb=i=>{const u=/<\/?[^>]+>/g;let r="",c=0,f;for(;(f=u.exec(i))!==null;){f.index>c&&(r+=xt(i.substring(c,f.index)));const d=f[0],h=d.match(/^<(\/?[A-Za-z0-9-]+)([\s\S]*?)>$/);if(h){const m=h[1],x=h[2];let g=xt(m);g.startsWith("/")?g=`/<span class="code-token-tag">${g.substring(1)}</span>`:g=`<span class="code-token-tag">${g}</span>`;let C=xt(x);C=C.replace(/(\s)([A-Za-z0-9-:]+)(=)/g,'$1<span class="code-token-attr">$2</span>$3'),C=C.replace(/(".*?"|'.*?')/g,'<span class="code-token-string">$1</span>'),r+=`<span class="code-token-punct"><${g}${C}></span>`}else r+=`<span class="code-token-punct">${xt(d)}</span>`;c=u.lastIndex}return r+=xt(i.substring(c)),r},qp=(i,u,r)=>u==="javascript"?nb(i,r):u==="json"?ab(i):u==="html"?lb(i):Hp(i,r),Si=({value:i,onChange:u,onBlur:r,language:c,placeholder:f,className:d,readOnly:h,variables:m})=>{const x=R.useRef(null),g=R.useRef(null),C=i||f||"",_=!i&&!!f,A=R.useMemo(()=>qp(C,c,m),[C,c,m]);return R.useEffect(()=>{const w=x.current,N=g.current;if(!w||!N)return;const p=()=>{N.scrollTop=w.scrollTop,N.scrollLeft=w.scrollLeft};return w.addEventListener("scroll",p),()=>{w.removeEventListener("scroll",p)}},[]),l.jsxs("div",{className:`code-editor ${d||""}`,onWheel:w=>{const N=x.current;N&&(N.scrollHeight<=N.clientHeight||(N.scrollTop+=w.deltaY,N.scrollLeft+=w.deltaX,N.focus(),w.preventDefault()))},children:[l.jsx("pre",{ref:g,className:`code-editor-pre ${_?"code-editor-placeholder":""}`,"aria-hidden":!0,dangerouslySetInnerHTML:{__html:A}}),l.jsx("textarea",{ref:x,value:i,onChange:w=>u?.(w.target.value),onBlur:w=>r?.(w.target.value),spellCheck:!1,wrap:"off",readOnly:h,className:`code-editor-textarea ${h?"code-editor-textarea-readonly":""}`,"aria-label":"Code editor",tabIndex:h?-1:0})]})},ib=async i=>{try{if(navigator.clipboard&&window.isSecureContext)return await navigator.clipboard.writeText(i),!0;{const u=document.createElement("textarea");u.value=i,u.style.position="fixed",u.style.left="-999999px",u.style.top="-999999px",document.body.appendChild(u),u.focus(),u.select();const r=document.execCommand("copy");return u.remove(),r}}catch(u){return console.error("Copy failed:",u),!1}},Ws=({text:i,label:u,className:r,iconClassName:c,onCopy:f,title:d,disabled:h=!1})=>{const[m,x]=R.useState(!1),g=async N=>{if(N.stopPropagation(),h)return;await ib(i)&&(x(!0),f?.(),setTimeout(()=>x(!1),2e3))},C="flex items-center gap-2 px-3 py-2 rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all text-[9px] font-bold uppercase tracking-widest disabled:opacity-50 disabled:cursor-not-allowed",_="focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",A=r?`${r} ${_}`:`${C} ${_}`,w=m?A.replace("border-white/10","border-green-400 text-green-400"):A;return l.jsxs("button",{onClick:g,disabled:h,className:w,title:d||(m?"Copied":"Copy"),type:"button","aria-label":u||d||"Copy to clipboard",children:[m?l.jsx(_e,{name:"check",className:`${c||"text-sm"} text-green-400`}):l.jsx(_e,{name:"content_copy",className:c||"text-sm"}),u&&l.jsx("span",{children:m?"Copied":u})]})},sb=({currentTask:i,onUpdateTask:u})=>{if(!i.id)return l.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-center space-y-4 animate-in fade-in duration-300",children:[l.jsx("div",{className:"w-12 h-12 rounded-full bg-white/5 flex items-center justify-center",children:l.jsx(_e,{name:"save",className:"text-gray-500"})}),l.jsxs("div",{children:[l.jsx("p",{className:"text-xs text-white font-medium",children:"Save Required"}),l.jsx("p",{className:"text-[10px] text-gray-500 mt-1 max-w-[200px]",children:"You must save this task before you can set an execution schedule."})]})]});const r=i.schedule||{enabled:!1},[c,f]=Fe.useState(!!r.cron&&!r.frequency);Fe.useEffect(()=>{r.cron&&!r.frequency&&f(!0),r.frequency&&!r.cron&&f(!1)},[r.cron,r.frequency]);const[d,h]=Fe.useState(null),[m,x]=Fe.useState(r.nextRun||null),[g,C]=Fe.useState(!1),[_,A]=Fe.useState(null),[w,N]=Fe.useState(!1),p=D=>{const M={...r,...D};M.enabled&&!M.frequency&&!M.cron&&(M.frequency="daily",M.hour=9,M.minute=0),u({schedule:M}),fetch(`/api/schedules/${i.id}/describe`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(M)}).then(O=>O.json()).then(O=>{h(O.description||null),x(O.nextRun||null)}).catch(()=>{})};Fe.useEffect(()=>{(r.enabled||r.frequency||r.cron)&&fetch(`/api/schedules/${i.id}/describe`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(r)}).then(D=>D.json()).then(D=>{h(D.description||null),x(D.nextRun||null)}).catch(()=>{})},[]);const b=D=>{C(!0),A(null),N(!1);const M=D||{...r};fetch(`/api/schedules/${i.id}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(M)}).then(async O=>{const X=await O.json();if(!O.ok)throw new Error(X.message||X.error||"Failed to save");return X}).then(O=>{O.schedule&&(u({schedule:O.schedule}),h(O.description||null),x(O.schedule?.nextRun||null),N(!0),setTimeout(()=>N(!1),2e3))}).catch(O=>{A(O.message)}).finally(()=>{C(!1)})},v=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],j=r.frequency||(c?void 0:"daily"),k=r.daysOfWeek||[],B=D=>{const M=D-Date.now();if(M<0)return"now";const O=Math.floor(M/6e4);if(O<1)return"less than a minute";if(O<60)return`${O}m`;const X=Math.floor(O/60);return X<24?`${X}h ${O%60}m`:`${Math.floor(X/24)}d ${X%24}h`};return l.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Scheduled Execution"}),l.jsxs("button",{onClick:()=>{const D=!r.enabled,M={...r,enabled:D};D&&!M.frequency&&!M.cron&&(M.frequency="daily",M.hour=9,M.minute=0),p(M),b(M)},className:`flex items-center gap-2 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all border ${r.enabled?"bg-emerald-500/20 border-emerald-500/40 text-emerald-400":"bg-white/5 border-white/10 text-gray-500 hover:text-white hover:border-white/20"}`,children:[l.jsx("div",{className:`w-2 h-2 rounded-full ${r.enabled?"bg-emerald-400 animate-pulse":"bg-gray-600"}`}),r.enabled?"Active":"Inactive"]})]}),l.jsxs("div",{className:"flex items-center gap-2 bg-black/40 p-1 rounded-xl border border-white/5",children:[l.jsx("button",{onClick:()=>{f(!1),p({cron:void 0,frequency:r.frequency||"daily"})},className:`flex-1 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${c?"text-gray-500 hover:text-white":"bg-white text-black"}`,children:"Visual"}),l.jsx("button",{onClick:()=>{f(!0),p({frequency:void 0,cron:r.cron||"0 9 * * *"})},className:`flex-1 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${c?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:"Advanced"})]}),c?l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Cron Expression"}),l.jsx("input",{type:"text",value:r.cron||"",onChange:D=>p({cron:D.target.value,frequency:void 0}),placeholder:"*/5 * * * *",className:"w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-sm text-white font-mono placeholder:text-gray-700 focus:outline-none focus:border-white/30 transition-all"}),l.jsx("p",{className:"text-[9px] text-gray-600 font-mono",children:"minute hour day-of-month month day-of-week"})]}):l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Frequency"}),l.jsx("div",{className:"grid grid-cols-3 gap-2",children:["interval","hourly","daily","weekly","monthly"].map(D=>l.jsx("button",{onClick:()=>p({frequency:D,cron:void 0}),className:`px-3 py-2.5 rounded-xl text-[10px] font-bold uppercase tracking-wider border transition-all ${j===D?"bg-white/15 border-white/40 text-white":"bg-white/5 border-white/5 text-gray-500 hover:text-white hover:border-white/15"}`,children:D==="interval"?"Every X min":D},D))})]}),j==="interval"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Run every"}),l.jsx("div",{className:"grid grid-cols-6 gap-2",children:[1,5,10,15,30,60].map(D=>l.jsxs("button",{onClick:()=>p({intervalMinutes:D}),className:`py-2 rounded-xl text-xs font-bold border transition-all ${(r.intervalMinutes||5)===D?"bg-white/15 border-white/40 text-white":"bg-white/5 border-white/5 text-gray-500 hover:text-white hover:border-white/15"}`,children:[D,"m"]},D))})]}),j==="hourly"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"At minute"}),l.jsx("div",{className:"grid grid-cols-4 gap-2",children:[0,15,30,45].map(D=>l.jsxs("button",{onClick:()=>p({minute:D}),className:`py-2 rounded-xl text-xs font-bold border transition-all ${(r.minute??0)===D?"bg-white/15 border-white/40 text-white":"bg-white/5 border-white/5 text-gray-500 hover:text-white hover:border-white/15"}`,children:[":",String(D).padStart(2,"0")]},D))})]}),(j==="daily"||j==="weekly"||j==="monthly")&&l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Time"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("select",{value:r.hour??9,onChange:D=>p({hour:parseInt(D.target.value)}),className:"flex-1 bg-black/40 border border-white/10 rounded-xl px-3 py-2.5 text-xs text-white",children:Array.from({length:24},(D,M)=>l.jsx("option",{value:M,children:M===0?"12 AM":M<12?`${M} AM`:M===12?"12 PM":`${M-12} PM`},M))}),l.jsx("select",{value:r.minute??0,onChange:D=>p({minute:parseInt(D.target.value)}),className:"flex-1 bg-black/40 border border-white/10 rounded-xl px-3 py-2.5 text-xs text-white",children:Array.from({length:60},(D,M)=>l.jsxs("option",{value:M,children:[":",String(M).padStart(2,"0")]},M))})]})]}),j==="weekly"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Days"}),l.jsx("div",{className:"grid grid-cols-7 gap-1.5",children:v.map((D,M)=>l.jsx("button",{onClick:()=>{const O=k.includes(M)?k.filter(X=>X!==M):[...k,M].sort();p({daysOfWeek:O})},className:`py-2 rounded-xl text-[10px] font-bold uppercase border transition-all ${k.includes(M)?"bg-white/20 border-white/40 text-white":"bg-white/5 border-white/5 text-gray-600 hover:text-white hover:border-white/15"}`,children:D},M))})]}),j==="monthly"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Day of Month"}),l.jsx("select",{value:r.dayOfMonth??1,onChange:D=>p({dayOfMonth:parseInt(D.target.value)}),className:"w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2.5 text-xs text-white",children:Array.from({length:31},(D,M)=>l.jsx("option",{value:M+1,children:M+1},M+1))})]})]}),d&&l.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-2xl p-4",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[l.jsx(_e,{name:"event_repeat",className:"text-sm text-white/40"}),l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Schedule"})]}),l.jsx("p",{className:"text-sm text-white font-medium",children:d})]}),m&&l.jsxs("div",{className:"flex items-center justify-between bg-white/5 border border-white/10 rounded-2xl p-4",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Next Run"}),l.jsx("p",{className:"text-xs text-white mt-1",children:new Date(m).toLocaleString()})]}),l.jsxs("span",{className:"text-xs text-gray-400",children:["in ",B(m)]})]}),r.lastRun&&l.jsxs("div",{className:"flex items-center justify-between bg-white/5 border border-white/10 rounded-2xl p-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:`w-2 h-2 rounded-full ${r.lastRunStatus==="success"?"bg-emerald-400":"bg-red-400"}`}),l.jsxs("div",{children:[l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Last Run"}),l.jsx("p",{className:"text-xs text-white mt-0.5",children:new Date(r.lastRun).toLocaleString()})]})]}),r.lastRunDurationMs!=null&&l.jsxs("span",{className:"text-[10px] text-gray-500",children:[(r.lastRunDurationMs/1e3).toFixed(1),"s"]})]}),_&&l.jsx("div",{className:"p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-[10px] font-bold uppercase tracking-widest text-center",children:_}),l.jsxs("button",{onClick:()=>b(),disabled:g,className:`w-full py-3 rounded-2xl text-[10px] font-bold uppercase tracking-[0.2em] transition-all flex items-center justify-center gap-3 ${w?"bg-emerald-500 text-white shadow-lg shadow-emerald-500/20":"bg-white text-black hover:bg-gray-200 shadow-xl shadow-white/5"} disabled:opacity-50`,children:[g?l.jsx("div",{className:"w-3 h-3 border-2 border-black/20 border-t-black rounded-full animate-spin"}):w?l.jsx(_e,{name:"check",className:"text-sm"}):null,w?"Schedule Saved":g?"Saving...":"Save Schedule"]})]})},rb=({isOpen:i,onClose:u,currentTask:r,onUpdateTask:c,proxyListLoaded:f,proxyList:d,initialTab:h="mode",versions:m,versionsLoading:x,onRollback:g,onPreview:C})=>{const[_,A]=Fe.useState(h),[w,N]=Fe.useState([]),[p,b]=Fe.useState({name:"",baseUrl:"https://api.baserow.io",token:""}),[v,j]=Fe.useState(!1),[k,B]=Fe.useState(!1),[D,M]=Fe.useState([]),[O,X]=Fe.useState([]),[$,oe]=Fe.useState(!1),[ce,q]=Fe.useState(!1),[P,E]=Fe.useState(!0);Fe.useEffect(()=>{i&&A(h)},[i,h]),Fe.useEffect(()=>{i&&_==="output"&&fetch("/api/credentials").then(Y=>Y.json()).then(N).catch(()=>{})},[i,_]);const ne=Fe.useCallback(async Y=>{if(!Y){M([]),X([]),E(!0);return}oe(!0),E(!0);try{const me=await fetch(`/api/credentials/${Y}/proxy/baserow/databases`);if(me.ok){const Ne=await me.json();M(Ne),E(!0)}else M([]),E(!1)}catch{M([]),E(!1)}finally{oe(!1)}},[]),Q=Fe.useCallback(async(Y,me)=>{if(!Y||!me){X([]);return}q(!0);try{const Ne=await fetch(`/api/credentials/${Y}/proxy/baserow/databases/${me}/tables`);Ne.ok?X(await Ne.json()):X([])}catch{X([])}finally{q(!1)}},[]);Fe.useEffect(()=>{r.output?.credentialId?ne(r.output.credentialId):(M([]),X([]))},[r.output?.credentialId,ne]),Fe.useEffect(()=>{r.output?.credentialId&&r.output?.databaseId?Q(r.output.credentialId,r.output.databaseId):X([])},[r.output?.databaseId,r.output?.credentialId,Q]);const Z=async()=>{if(!(!p.name||!p.token)){B(!0);try{const Y=await fetch("/api/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:p.name,provider:"baserow",config:{baseUrl:p.baseUrl,token:p.token}})});if(Y.ok){const me=await Y.json();N(Ne=>[...Ne,me]),b({name:"",baseUrl:"https://api.baserow.io",token:""}),j(!1),r.output?.credentialId||c({output:{...r.output,credentialId:me.id,provider:"baserow",tableId:r.output?.tableId||"",onError:r.output?.onError||"ignore"}})}}finally{B(!1)}}},we=async Y=>{await fetch(`/api/credentials/${Y}`,{method:"DELETE"}),N(me=>me.filter(Ne=>Ne.id!==Y)),r.output?.credentialId===Y&&c({output:{...r.output,credentialId:""}})};if(!i)return null;const F=f&&d.length===1&&d[0]?.id==="host",he=(Y,me,Ne,ke)=>{const Ae={...r.variables};Y!==me&&delete Ae[Y],Ae[me]={type:Ne,value:ke},c({variables:Ae})},z=Y=>{const me={...r.variables};delete me[Y],c({variables:me})},U=()=>{const Y=`var_${Object.keys(r.variables||{}).length+1}`;he(Y,Y,"string","")},te=Y=>{c({stealth:{...r.stealth,[Y]:!r.stealth[Y]}})},ae=(Y,me,Ne)=>l.jsxs("button",{onClick:()=>A(Y),className:`flex items-center gap-2 px-4 py-2 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all ${_===Y?"bg-white text-black shadow-lg shadow-white/10":"text-gray-500 hover:text-white hover:bg-white/5"}`,children:[l.jsx(_e,{name:Ne,className:"text-sm"}),me]});return l.jsxs("div",{className:"fixed inset-y-0 right-0 w-[450px] z-[100] flex",children:[l.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-[2px]",onClick:u}),l.jsxs("div",{className:"relative h-full w-full bg-[#080808]/90 border-l border-white/10 backdrop-blur-2xl shadow-[-20px_0_50px_rgba(0,0,0,0.5)] flex flex-col animate-in slide-in-from-right duration-300 ease-out p-8",children:[l.jsxs("div",{className:"flex items-center justify-between mb-8",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-xl font-bold text-white tracking-tight",children:"Task Settings"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-[0.2em] mt-1",children:r.name||"Untitled Task"})]}),l.jsx("button",{onClick:u,className:"w-10 h-10 rounded-full flex items-center justify-center hover:bg-white/5 text-gray-400 hover:text-white transition-colors","aria-label":"Close settings",title:"Close settings",children:l.jsx(_e,{name:"close"})})]}),l.jsxs("div",{className:"flex flex-wrap gap-2 mb-8 bg-black/40 p-1 rounded-2xl border border-white/5",children:[ae("mode","Mode","settings_input_component"),ae("variables","Vars","data_object"),ae("behavior","Behavior","psychology"),ae("extraction","Extract","terminal"),ae("api","API","api"),ae("output","Output","table"),ae("schedule","Schedule","event_repeat"),ae("history","History","history")]}),l.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar pr-2 -mr-2",children:[_==="mode"&&l.jsx("div",{className:"space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300",children:l.jsxs("div",{className:"space-y-4",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Execution Mode"}),l.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[l.jsxs("button",{onClick:()=>c({mode:"agent"}),className:`p-4 rounded-2xl border transition-all text-left space-y-2 ${r.mode==="agent"?"bg-white/10 border-white/30 ring-1 ring-white/20":"bg-white/5 border-white/5 opacity-50 hover:opacity-100 hover:border-white/10"}`,children:[l.jsx("div",{className:"w-8 h-8 rounded-full bg-white/10 flex items-center justify-center",children:l.jsx(_e,{name:"smart_toy",className:"text-white/60"})}),l.jsxs("div",{children:[l.jsx("div",{className:"text-xs font-bold text-white",children:"Agent Mode"}),l.jsx("div",{className:"text-[9px] text-gray-500",children:"Autonomous decision making"})]})]}),l.jsxs("button",{onClick:()=>c({mode:"scrape"}),className:`p-4 rounded-2xl border transition-all text-left space-y-2 ${r.mode==="scrape"?"bg-white/10 border-white/30 ring-1 ring-white/20":"bg-white/5 border-white/5 opacity-50 hover:opacity-100 hover:border-white/10"}`,children:[l.jsx("div",{className:"w-8 h-8 rounded-full bg-white/10 flex items-center justify-center",children:l.jsx(_e,{name:"api",className:"text-white/60"})}),l.jsxs("div",{children:[l.jsx("div",{className:"text-xs font-bold text-white",children:"Scrape Mode"}),l.jsx("div",{className:"text-[9px] text-gray-500",children:"Fixed data extraction flow"})]})]})]})]})}),_==="variables"&&l.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Task Variables"}),l.jsx("button",{onClick:U,className:"px-3 py-1 rounded-lg bg-white/10 text-white text-[10px] font-bold uppercase tracking-wider hover:bg-white/20 transition-all border border-white/10",children:"+ Add Var"})]}),l.jsxs("div",{className:"space-y-3",children:[Object.entries(r.variables||{}).map(([Y,me])=>l.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-2xl p-4 space-y-3",children:[l.jsxs("div",{className:"flex gap-2",children:[l.jsx("input",{type:"text",defaultValue:Y,onBlur:Ne=>{Ne.target.value!==Y&&he(Y,Ne.target.value,me.type,me.value)},placeholder:"Name",className:"flex-1 bg-black/40 border border-white/5 rounded-xl px-3 py-2 text-xs text-white placeholder:text-gray-700"}),l.jsxs("select",{value:me.type,onChange:Ne=>he(Y,Y,Ne.target.value,me.value),className:"bg-black/40 border border-white/5 rounded-xl px-2 py-2 text-[10px] font-bold uppercase text-gray-500",children:[l.jsx("option",{value:"string",children:"String"}),l.jsx("option",{value:"number",children:"Number"}),l.jsx("option",{value:"boolean",children:"Bool"})]}),l.jsx("button",{onClick:()=>z(Y),className:"text-red-500/50 hover:text-red-500 p-2","aria-label":"Remove variable",title:"Remove variable",children:l.jsx(_e,{name:"delete",className:"text-sm"})})]}),l.jsx("div",{className:"pl-1",children:me.type==="boolean"?l.jsxs("select",{value:String(me.value),onChange:Ne=>he(Y,Y,me.type,Ne.target.value==="true"),className:"w-full bg-black/40 border border-white/5 rounded-xl px-3 py-2 text-xs text-white",children:[l.jsx("option",{value:"true",children:"True"}),l.jsx("option",{value:"false",children:"False"})]}):l.jsx("input",{type:me.type==="number"?"number":"text",value:me.value,onChange:Ne=>he(Y,Y,me.type,me.type==="number"?parseFloat(Ne.target.value):Ne.target.value),placeholder:"Default Value",className:"w-full bg-black/40 border border-white/5 rounded-xl px-3 py-2 text-xs text-white"})})]},Y)),Object.keys(r.variables||{}).length===0&&l.jsx("div",{className:"text-center py-12 border border-dashed border-white/10 rounded-3xl",children:l.jsx("p",{className:"text-[10px] text-gray-600 uppercase tracking-widest",children:"No variables defined"})})]})]}),_==="behavior"&&l.jsxs("div",{className:"space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Runtime Flags"}),l.jsx("div",{className:"grid grid-cols-1 gap-2",children:[{label:"Stateless Execution",key:"statelessExecution",icon:"auto_delete"},{label:"Disable Recording",key:"disableRecording",icon:"videocam_off"},{label:"Rotate Proxies",key:"rotateProxies",icon:"vpn_lock",disabled:F},{label:"Rotate User Agents",key:"rotateUserAgents",icon:"person_search"},{label:"Rotate Viewport",key:"rotateViewport",icon:"screenshot_monitor"},{label:"Include Shadow DOM",key:"includeShadowDom",icon:"layers"}].map(Y=>l.jsxs("button",{disabled:Y.disabled,role:"switch","aria-checked":!!r[Y.key],onClick:()=>c({[Y.key]:!r[Y.key]}),className:`flex items-center justify-between p-4 rounded-2xl border transition-all ${r[Y.key]?"bg-white/10 border-white/30 text-white":"bg-white/5 border-white/5 text-gray-400 opacity-60 hover:opacity-100"} ${Y.disabled?"opacity-20 cursor-not-allowed":""}`,children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(_e,{name:Y.icon,className:"text-sm opacity-70"}),l.jsx("span",{className:"text-xs font-medium",children:Y.label})]}),l.jsx("div",{className:`w-8 h-4 rounded-full relative transition-colors ${r[Y.key]?"bg-white":"bg-white/10"}`,children:l.jsx("div",{className:`absolute top-1 w-2 h-2 rounded-full transition-all ${r[Y.key]?"right-1 bg-black":"left-1 bg-white/20"}`})})]},Y.key))})]}),l.jsxs("div",{className:"space-y-4",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Stealth & Behavior"}),l.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{label:"Human Typing",key:"naturalTyping",icon:"keyboard"},{label:"Cursor Glide",key:"cursorGlide",icon:"near_me"},{label:"Idle Moves",key:"idleMovements",icon:"mouse"},{label:"Dead Clicks",key:"deadClicks",icon:"ads_click"},{label:"Fatigue Sim",key:"fatigue",icon:"hourglass_empty"},{label:"Allow Typos",key:"allowTypos",icon:"spellcheck"},{label:"Random Clicks",key:"randomizeClicks",icon:"shuffle"},{label:"Overscroll",key:"overscroll",icon:"unfold_more"}].map(Y=>l.jsxs("button",{role:"switch","aria-checked":!!r.stealth[Y.key],onClick:()=>te(Y.key),className:`flex flex-col gap-2 p-4 rounded-2xl border transition-all text-left ${r.stealth[Y.key]?"bg-white/15 border-white/40 text-white":"bg-white/5 border-white/5 text-gray-500 opacity-60 hover:opacity-100"}`,children:[l.jsx(_e,{name:Y.icon,className:"text-sm opacity-70"}),l.jsx("span",{className:"text-[10px] font-bold uppercase tracking-tight",children:Y.label})]},Y.key))})]})]}),_==="extraction"&&l.jsx("div",{className:"space-y-6 h-full flex flex-col animate-in fade-in slide-in-from-bottom-2 duration-300",children:l.jsxs("div",{className:"space-y-4 flex-1 flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Post-Execution Script"}),l.jsxs("select",{value:r.extractionFormat||"json",onChange:Y=>c({extractionFormat:Y.target.value}),className:"bg-black/40 border border-white/5 rounded-lg px-2 py-1 text-[8px] font-bold uppercase text-gray-500",children:[l.jsx("option",{value:"json",children:"JSON"}),l.jsx("option",{value:"csv",children:"CSV"})]})]}),l.jsx("div",{className:"flex-1 bg-black/40 border border-white/5 rounded-2xl overflow-hidden min-h-[300px]",children:l.jsx(Si,{language:"javascript",value:r.extractionScript||"",onChange:Y=>c({extractionScript:Y}),placeholder:"// Example: return { title: document.title };",className:"h-full text-[11px]"})})]})}),_==="api"&&l.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Trigger via API"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-[10px] text-gray-500",children:"Run this task from external tools using the endpoint below:"}),l.jsxs("div",{className:"relative group",children:[l.jsxs("div",{className:"bg-black/40 border border-white/10 rounded-xl p-4 pr-12 font-mono text-[10px] text-white/80 break-all border-dashed",children:["POST /api/tasks/",r.id,"/api"]}),l.jsx(Ws,{text:`POST /api/tasks/${r.id}/api`,className:"absolute right-2 top-2 p-2 rounded-lg bg-white/5 border border-white/10 text-white opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-all",iconClassName:"text-xs",title:"Copy Endpoint"})]})]})]}),l.jsxs("div",{className:"space-y-4",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Response Options"}),l.jsxs("button",{onClick:()=>c({includeHtml:!r.includeHtml}),className:"w-full flex items-center justify-between p-3 rounded-xl bg-black/20 border border-white/5 hover:bg-white/5 transition-colors",children:[l.jsxs("div",{className:"text-left",children:[l.jsx("span",{className:"text-xs font-medium",children:"Include HTML in response"}),l.jsx("p",{className:"text-[9px] text-gray-500 mt-0.5",children:"When an extraction script is set, also return the raw HTML"})]}),l.jsx("div",{className:`w-8 h-4 rounded-full relative transition-colors flex-shrink-0 ${r.includeHtml?"bg-white":"bg-white/10"}`,children:l.jsx("div",{className:`absolute top-1 w-2 h-2 rounded-full transition-all ${r.includeHtml?"right-1 bg-black":"left-1 bg-white/20"}`})})]})]}),l.jsxs("div",{className:"space-y-4",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Passing Variables"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-[10px] text-gray-500",children:"You can override task variables in the request body:"}),l.jsxs("div",{className:"relative group",children:[l.jsx("div",{className:"bg-black/40 border border-white/5 rounded-xl p-4 pr-12 font-mono text-[10px] text-white/60",children:l.jsx("pre",{children:JSON.stringify({variables:Object.fromEntries(Object.entries(r.variables||{}).slice(0,2).map(([Y,me])=>[Y,me.value]))},null,2)})}),l.jsx(Ws,{text:JSON.stringify({variables:Object.fromEntries(Object.entries(r.variables||{}).slice(0,2).map(([Y,me])=>[Y,me.value]))},null,2),className:"absolute right-2 top-2 p-2 rounded-lg bg-white/5 border border-white/10 text-white opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-all",iconClassName:"text-xs",title:"Copy Payload"})]})]})]})]}),_==="output"&&l.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[l.jsxs("button",{onClick:()=>c({output:r.output?void 0:{provider:"baserow",credentialId:"",tableId:"",onError:"ignore"}}),className:"w-full flex items-center justify-between p-3 rounded-xl bg-black/20 border border-white/5 hover:bg-white/5 transition-colors",children:[l.jsxs("div",{className:"text-left",children:[l.jsx("span",{className:"text-xs font-medium",children:"Push results to destination"}),l.jsx("p",{className:"text-[9px] text-gray-500 mt-0.5",children:"Send extracted data to an external table after each run"})]}),l.jsx("div",{className:`w-8 h-4 rounded-full relative transition-colors flex-shrink-0 ${r.output?"bg-white":"bg-white/10"}`,children:l.jsx("div",{className:`absolute top-1 w-2 h-2 rounded-full transition-all ${r.output?"right-1 bg-black":"left-1 bg-white/20"}`})})]}),r.output&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Provider"}),l.jsx("select",{value:r.output.provider,onChange:Y=>c({output:{...r.output,provider:Y.target.value,credentialId:"",tableId:""}}),className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white focus:outline-none focus:border-white/20",children:l.jsx("option",{value:"baserow",children:"Baserow"})})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Credential"}),l.jsxs("button",{onClick:()=>j(Y=>!Y),className:"text-[9px] font-bold text-gray-400 hover:text-white transition-colors flex items-center gap-1",children:[l.jsx(_e,{name:"add",className:"text-xs"}),"New"]})]}),v&&l.jsxs("div",{className:"space-y-2 p-3 rounded-xl bg-black/40 border border-white/5",children:[l.jsx("input",{className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-white/20",placeholder:"Name (e.g. My Baserow)",value:p.name,onChange:Y=>b(me=>({...me,name:Y.target.value}))}),l.jsx("input",{className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-white/20",placeholder:"Base URL",value:p.baseUrl,onChange:Y=>b(me=>({...me,baseUrl:Y.target.value}))}),l.jsx("input",{className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-white/20",placeholder:"API Token",type:"password",value:p.token,onChange:Y=>b(me=>({...me,token:Y.target.value}))}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:Z,disabled:k||!p.name||!p.token,className:"flex-1 py-1.5 rounded-lg bg-white text-black text-[10px] font-bold disabled:opacity-40 transition-opacity",children:k?"Saving…":"Save"}),l.jsx("button",{onClick:()=>j(!1),className:"px-3 py-1.5 rounded-lg bg-white/5 text-gray-400 text-[10px] font-bold hover:text-white transition-colors",children:"Cancel"})]})]}),(()=>{const Y=w.filter(me=>me.provider===r.output?.provider);return Y.length===0&&!v?l.jsxs("p",{className:"text-[10px] text-gray-600",children:["No credentials yet. Click ",l.jsx("span",{className:"text-gray-400",children:"+ New"})," to add one."]}):l.jsxs("select",{value:r.output.credentialId,onChange:me=>c({output:{...r.output,credentialId:me.target.value}}),className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white focus:outline-none focus:border-white/20",children:[l.jsx("option",{value:"",children:"Select credential…"}),Y.map(me=>l.jsx("option",{value:me.id,children:me.name},me.id))]})})(),w.filter(Y=>Y.provider===r.output?.provider).length>0&&l.jsx("div",{className:"space-y-1",children:w.filter(Y=>Y.provider===r.output?.provider).map(Y=>l.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 rounded-lg bg-black/20 border border-white/5",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-[10px] text-white",children:Y.name}),l.jsx("span",{className:"text-[9px] text-gray-600 ml-2",children:Y.config.baseUrl})]}),l.jsx("button",{onClick:()=>we(Y.id),className:"text-gray-600 hover:text-red-400 transition-colors",children:l.jsx(_e,{name:"delete",className:"text-sm"})})]},Y.id))})]}),r.output.credentialId&&P&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Database"}),$&&l.jsx("div",{className:"w-3 h-3 border-2 border-white/20 border-t-white rounded-full animate-spin"})]}),l.jsxs("select",{value:r.output.databaseId||"",onChange:Y=>c({output:{...r.output,databaseId:Y.target.value,tableId:""}}),className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white focus:outline-none focus:border-white/20",disabled:$,children:[l.jsx("option",{value:"",children:"Select database…"}),D.map(Y=>l.jsx("option",{value:Y.id,children:Y.name},Y.id))]})]}),r.output.databaseId&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Table"}),ce&&l.jsx("div",{className:"w-3 h-3 border-2 border-white/20 border-t-white rounded-full animate-spin"})]}),l.jsxs("select",{value:r.output.tableId,onChange:Y=>c({output:{...r.output,tableId:Y.target.value}}),className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white focus:outline-none focus:border-white/20",disabled:ce,children:[l.jsx("option",{value:"",children:"Select table…"}),O.map(Y=>l.jsx("option",{value:Y.id,children:Y.name},Y.id))]})]})]}),r.output.credentialId&&!P&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Table ID"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/5 rounded-lg px-3 py-2 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-white/20",placeholder:"e.g. 1234",value:r.output.tableId,onChange:Y=>c({output:{...r.output,tableId:Y.target.value}})}),l.jsxs("p",{className:"text-[9px] text-gray-600",children:["Your token doesn't support browsing. Use a ",l.jsx("span",{className:"text-gray-400",children:"Personal API Token"})," for dropdowns, or enter the Table ID from the Baserow URL."]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"On Push Error"}),l.jsx("div",{className:"flex gap-2",children:["ignore","fail"].map(Y=>l.jsx("button",{onClick:()=>c({output:{...r.output,onError:Y}}),className:`flex-1 py-2 rounded-lg text-[10px] font-bold uppercase tracking-widest transition-all ${r.output?.onError===Y?"bg-white text-black":"bg-white/5 text-gray-500 hover:text-white"}`,children:Y==="ignore"?"Ignore":"Log Error"},Y))}),l.jsx("p",{className:"text-[9px] text-gray-600",children:r.output.onError==="fail"?"Push errors will be logged prominently in the server console.":"Push errors will be silently suppressed."})]})]})]}),_==="schedule"&&l.jsx(sb,{currentTask:r,onUpdateTask:c}),_==="history"&&l.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Version History"}),x&&l.jsx("div",{className:"w-3 h-3 border-2 border-white/20 border-t-white rounded-full animate-spin"})]}),l.jsxs("div",{className:"space-y-2",children:[m.map(Y=>l.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-2xl p-4 flex items-center justify-between group hover:border-white/20 transition-all",children:[l.jsxs("div",{className:"flex flex-col gap-1",children:[l.jsx("div",{className:"text-xs font-bold text-white mb-0.5",children:new Date(Y.timestamp).toLocaleString()}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-white/10 text-gray-400 font-bold uppercase tracking-widest",children:Y.mode}),l.jsx("span",{className:"text-[9px] text-gray-600 truncate max-w-[150px]",children:Y.name||"Untitled"})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:()=>C(Y.id),className:"w-8 h-8 rounded-lg flex items-center justify-center text-white/30 hover:text-white hover:bg-white/10 transition-all",title:"Preview version","aria-label":"Preview version",children:l.jsx(_e,{name:"visibility",className:"text-sm"})}),l.jsx("button",{onClick:()=>g(Y.id),className:"w-8 h-8 rounded-lg flex items-center justify-center text-white/30 hover:text-white hover:bg-white/10 transition-all",title:"Rollback to this version","aria-label":"Rollback to this version",children:l.jsx(_e,{name:"restore",className:"text-sm"})})]})]},Y.id)),m.length===0&&!x&&l.jsx("div",{className:"text-center py-12 border border-dashed border-white/10 rounded-3xl",children:l.jsx("p",{className:"text-[10px] text-gray-600 uppercase tracking-widest",children:"No previous versions found"})})]})]})]})]})]})},ob=()=>{const[i,u]=R.useState({x:0,y:0}),[r,c]=R.useState(1),f=R.useRef(!1),d=R.useRef({x:0,y:0,offsetX:0,offsetY:0}),h=R.useRef(!1),m=R.useRef(null),x=R.useRef(!1),g=R.useRef(r);R.useEffect(()=>{g.current=r},[r]),R.useEffect(()=>{if(x.current)return;x.current=!0;const w=m.current;if(!w)return;const N=w.clientWidth;u({x:(N-400)/2,y:20})},[]),R.useEffect(()=>{const w=m.current;if(!w)return;const N=p=>{if(p.ctrlKey||p.metaKey){p.preventDefault();const b=w.getBoundingClientRect(),v=p.clientX-b.left,j=p.clientY-b.top,k=g.current,B=p.deltaY<0?1.1:.9,D=Math.min(2,Math.max(.25,k*B)),M=D/k;u(O=>({x:v-M*(v-O.x),y:j-M*(j-O.y)})),c(D)}else u(b=>({x:b.x-p.deltaX,y:b.y-p.deltaY}))};return w.addEventListener("wheel",N,{passive:!1}),()=>w.removeEventListener("wheel",N)},[]);const C=R.useCallback(w=>{f.current=!0,d.current={x:w.clientX,y:w.clientY,offsetX:i.x,offsetY:i.y},w.target.setPointerCapture?.(w.pointerId)},[i]),_=R.useCallback(w=>{if(!f.current)return;const N=w.clientX-d.current.x,p=w.clientY-d.current.y;u({x:d.current.offsetX+N,y:d.current.offsetY+p})},[]),A=R.useCallback(()=>{f.current=!1},[]);return{canvasOffset:i,setCanvasOffset:u,canvasScale:r,setCanvasScale:c,canvasViewportRef:m,spaceHeldRef:h,isPanning:f,startPanning:C,handlePanning:_,stopPanning:A}},cb=(i,u,r)=>{const c=R.useRef([]),f=R.useRef(-1),d=R.useRef(!1),h=R.useRef("");R.useEffect(()=>{if(d.current){d.current=!1;return}const g=JSON.stringify(i);if(g===h.current)return;const C=setTimeout(()=>{h.current=g,f.current<c.current.length-1&&(c.current=c.current.slice(0,f.current+1)),c.current.push(JSON.parse(g)),f.current=c.current.length-1,c.current.length>50&&(c.current.shift(),f.current-=1)},300);return()=>clearTimeout(C)},[i]);const m=R.useCallback(()=>{if(f.current>0){f.current-=1;const g=c.current[f.current];d.current=!0,h.current=JSON.stringify(g),u(g),r(g,!1)}},[u,r]),x=R.useCallback(()=>{if(f.current<c.current.length-1){f.current+=1;const g=c.current[f.current];d.current=!0,h.current=JSON.stringify(g),u(g),r(g,!1)}},[u,r]);return R.useEffect(()=>{const g=C=>{if((C.metaKey||C.ctrlKey)&&C.key.toLowerCase()==="z"){const _=document.activeElement;if(_){const A=_.tagName.toLowerCase(),w=_.getAttribute("contenteditable")==="true";if(A==="input"||A==="textarea"||w)return}C.preventDefault(),C.shiftKey?x():m()}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[m,x]),{undo:m,redo:x}},ub=(i,u,r)=>{const[c,f]=R.useState(new Set),[d,h]=R.useState(null),[m,x]=R.useState(null),g=R.useRef(null),C=R.useCallback((b,v,j=!1)=>{u(j?k=>{if(!k)return null;const B={...k,actions:k.actions.map(D=>D.id===b?{...D,...v}:D)};return r(B,!1),B}:k=>k?{...k,actions:k.actions.map(B=>B.id===b?{...B,...v}:B)}:null)},[u,r]),_=R.useCallback((b,v)=>{b!==v&&u(j=>{if(!j)return null;const k=[...j.actions],B=k.findIndex(X=>X.id===b),D=k.findIndex(X=>X.id===v);if(B===-1||D===-1)return j;const[M]=k.splice(B,1);k.splice(D,0,M);const O={...j,actions:k};return r(O,!1),O})},[u,r]),A=R.useCallback(b=>{u(v=>{if(!v)return null;const j={...v,actions:v.actions.filter(k=>k.id!==b)};return r(j,!1),j})},[u,r]),w=R.useCallback((b,v,j,k)=>{if(j!==void 0&&k!==void 0&&Math.abs(b-k)<14)return j;const B=i.actions;let D=B.length-1;for(let M=0;M<B.length;M++){if(B[M].id===v)continue;const O=document.getElementById(`action-${B[M].id}`);if(!O)continue;const X=O.getBoundingClientRect(),$=X.top+X.height*.4;if(b<$){D=M;break}}return D},[i.actions]),N=R.useCallback(()=>{if(d){if(m!==null&&m!==d.index){const b=i.actions[m]?.id;b&&_(d.id,b)}h(null),x(null),g.current=null}},[d,m,i.actions,_]),p=R.useCallback((b,v,j)=>{if(b.shiftKey||b.ctrlKey||b.metaKey){f(D=>{const M=new Set(D);return M.has(v)?M.delete(v):M.add(v),M});return}f(new Set([v]));const k=document.getElementById(`action-${v}`);if(!k)return;const B=k.getBoundingClientRect();g.current=b.pointerId,h({id:v,startY:b.clientY,currentY:b.clientY,height:B.height,index:j,originTop:B.top,pointerOffset:b.clientY-B.top}),x(j)},[]);return R.useEffect(()=>{if(!d)return;const b=j=>{if(g.current!==null&&j.pointerId!==g.current)return;const k=d.originTop+d.height/2,B=w(j.clientY,d.id,d.index,k);h(D=>D&&{...D,currentY:j.clientY}),x(B)},v=j=>{g.current!==null&&j.pointerId!==g.current||N()};return window.addEventListener("pointermove",b),window.addEventListener("pointerup",v),window.addEventListener("pointercancel",v),()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v)}},[d,w,N]),{selectedActionIds:c,setSelectedActionIds:f,dragState:d,dragOverIndex:m,updateAction:C,moveAction:_,removeAction:A,handleActionPointerDown:p}},db=(i,u,r,c)=>{const[f,d]=R.useState([]),[h,m]=R.useState(!1),[x,g]=R.useState(null),C=R.useCallback(async()=>{if(i.id){m(!0);try{const w=await fetch(`/api/tasks/${i.id}/versions`);if(!w.ok)throw new Error("Failed to load versions");const N=await w.json();d(Array.isArray(N.versions)?N.versions:[])}catch{d([])}finally{m(!1)}}},[i.id]),_=R.useCallback(async w=>{if(!(!i.id||!await r("Rollback to this version? Current changes will be saved as a new version.")))try{const p=await fetch(`/api/tasks/${i.id}/rollback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionId:w})});if(!p.ok)throw new Error("Rollback failed");const b=await p.json();c(b),u("Rolled back to selected version.","success"),C()}catch{u("Rollback failed.","error")}},[i.id,r,u,c,C]),A=R.useCallback(async w=>{if(i.id)try{const N=await fetch(`/api/tasks/${i.id}/versions/${w}`);if(!N.ok)throw new Error("Failed to load version");const p=await N.json();if(!p?.snapshot)throw new Error("Missing snapshot");g({id:p.metadata?.id||w,timestamp:p.metadata?.timestamp||Date.now(),snapshot:p.snapshot})}catch{u("Failed to load version snapshot.","error")}},[i.id,u]);return{versions:f,versionsLoading:h,versionPreview:x,setVersionPreview:g,loadVersions:C,rollbackToVersion:_,openVersionPreview:A}},fb=(i,u,r,c,f)=>{const[d,h]=R.useState(!0),[m,x]=R.useState(!1),[g,C]=R.useState(null),[_,A]=R.useState({}),w=R.useRef(null);R.useEffect(()=>{w.current=g},[g]);const N=R.useRef(f);R.useEffect(()=>{N.current=f},[f]),R.useEffect(()=>{u||(h(!1),x(!1))},[u]),R.useEffect(()=>{let b=null;return u&&(h(!0),b=new EventSource("/api/headful/selector_stream"),b.onmessage=v=>{try{const j=JSON.parse(v.data),k=w.current;if(j.selector&&k){try{const B=JSON.parse(j.selector);Array.isArray(B)&&B.length>0?(A(D=>({...D,[k]:B})),r(k,{selector:B[0]},!0)):r(k,{selector:j.selector},!0)}catch{r(k,{selector:j.selector},!0)}C(null),N.current?.()}}catch{}}),()=>{b&&b.close()}},[u,r]);const p=R.useCallback(async()=>{const b=!d;x(!0);try{if(!(await fetch("/api/headful/inspect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:b})})).ok)throw new Error("Failed to toggle inspect mode");h(b),c(`Inspect mode ${b?"enabled":"disabled"}`,"success")}catch{c("Failed to toggle inspect mode","error")}finally{x(!1)}},[d,c]);return{isInspectMode:d,isInspectLoading:m,activeInspectActionId:g,setActiveInspectActionId:C,selectorOptionsById:_,handleToggleInspect:p}},hb=()=>{const[i,u]=R.useState([]),[r,c]=R.useState(!1);return R.useEffect(()=>{let f=!1;return(async()=>{try{const h=await fetch("/api/settings/proxies",{credentials:"include"});if(!h.ok)throw new Error("Failed to load proxies");const m=await h.json();if(f)return;u(Array.isArray(m.proxies)?m.proxies:[])}catch{f||u([])}finally{f||c(!0)}})(),()=>{f=!0}},[]),{proxyList:i,proxyListLoaded:r}},pb=({currentTask:i,onUpdateTaskName:u,onAutoSave:r,onOpenHistory:c})=>l.jsx("div",{className:"fixed top-0 left-0 right-0 z-40 w-full pointer-events-none",children:l.jsxs("div",{className:"glass-card flex items-center justify-between p-1 px-6 border-b border-white/10 backdrop-blur-xl pointer-events-auto",children:[l.jsx("div",{className:"flex-1 overflow-hidden flex justify-center",children:l.jsx("input",{type:"text",value:i.name||"",onChange:f=>u(f.target.value),onBlur:()=>r(),placeholder:"Task name",className:"bg-transparent border-none text-[11px] font-bold text-white uppercase tracking-[0.25em] focus:outline-none w-full max-w-[400px] text-center placeholder:text-white/20 py-1"})}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsx("button",{onClick:c,className:"w-8 h-8 rounded-lg flex items-center justify-center text-white/30 hover:text-white hover:bg-white/5 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"Version History","aria-label":"Version History",children:l.jsx(_e,{name:"history",className:"text-base"})})})]})}),mb=({isExecuting:i,isHeadfulOpen:u,onRun:r,onStop:c,onOpenHeadful:f,onStopHeadful:d})=>l.jsxs("div",{className:"fixed bottom-8 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 bg-[#111] border border-white/10 p-2 rounded-3xl shadow-2xl backdrop-blur-xl",children:[l.jsxs("button",{onClick:r,disabled:i||u,className:"shine-effect bg-white text-black px-8 py-4 rounded-2xl font-bold text-[10px] tracking-[0.3em] uppercase transition-all shadow-xl shadow-white/5 flex items-center justify-center gap-3 disabled:opacity-50 disabled:cursor-not-allowed min-w-[200px]",children:[i?l.jsx("div",{className:"w-3 h-3 border-2 border-black/20 border-t-black rounded-full animate-spin"}):l.jsx(_e,{name:"play_arrow",className:"text-sm text-black"}),l.jsx("span",{children:i?"Running...":"Run Task"})]}),i&&l.jsx("button",{onClick:()=>c?.(),className:"w-12 h-12 rounded-2xl border border-white/10 text-white/80 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center",title:"Stop task","aria-label":"Stop task",children:l.jsx(_e,{name:"stop",className:"text-base"})}),l.jsxs("button",{onClick:()=>{u?d?.():f()},disabled:i,className:`px-4 h-12 rounded-2xl border text-[9px] font-bold uppercase tracking-widest transition-all flex items-center gap-2 disabled:opacity-30 disabled:cursor-not-allowed ${u?"border-blue-500/30 bg-blue-500/20 text-blue-400 hover:bg-blue-500/30":"border-white/10 text-white/80 hover:text-white hover:bg-white/10"}`,title:u?"Stop headful browser":"Open browser to log in",children:[l.jsx(_e,{name:u?"stop":"open_in_browser",className:"text-base"}),u?"Close Browser":"Open Browser"]})]});function Mc(){return Mc=Object.assign?Object.assign.bind():function(i){for(var u=1;u<arguments.length;u++){var r=arguments[u];for(var c in r)({}).hasOwnProperty.call(r,c)&&(i[c]=r[c])}return i},Mc.apply(null,arguments)}function ep(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}function Uc(i,u){return Uc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,c){return r.__proto__=c,r},Uc(i,u)}function xb(i,u){i.prototype=Object.create(u.prototype),i.prototype.constructor=i,Uc(i,u)}var tp=Number.isNaN||function(u){return typeof u=="number"&&u!==u};function gb(i,u){return!!(i===u||tp(i)&&tp(u))}function bb(i,u){if(i.length!==u.length)return!1;for(var r=0;r<i.length;r++)if(!gb(i[r],u[r]))return!1;return!0}function Nc(i,u){u===void 0&&(u=bb);var r,c=[],f,d=!1;function h(){for(var m=[],x=0;x<arguments.length;x++)m[x]=arguments[x];return d&&r===this&&u(m,c)||(f=i.apply(this,m),d=!0,r=this,c=m),f}return h}var yb=typeof performance=="object"&&typeof performance.now=="function",ap=yb?function(){return performance.now()}:function(){return Date.now()};function np(i){cancelAnimationFrame(i.id)}function vb(i,u){var r=ap();function c(){ap()-r>=u?i.call(null):f.id=requestAnimationFrame(c)}var f={id:requestAnimationFrame(c)};return f}var Cc=-1;function lp(i){if(i===void 0&&(i=!1),Cc===-1||i){var u=document.createElement("div"),r=u.style;r.width="50px",r.height="50px",r.overflow="scroll",document.body.appendChild(u),Cc=u.offsetWidth-u.clientWidth,document.body.removeChild(u)}return Cc}var yl=null;function ip(i){if(i===void 0&&(i=!1),yl===null||i){var u=document.createElement("div"),r=u.style;r.width="50px",r.height="50px",r.overflow="scroll",r.direction="rtl";var c=document.createElement("div"),f=c.style;return f.width="100px",f.height="100px",u.appendChild(c),document.body.appendChild(u),u.scrollLeft>0?yl="positive-descending":(u.scrollLeft=1,u.scrollLeft===0?yl="negative":yl="positive-ascending"),document.body.removeChild(u),yl}return yl}var wb=150,Sb=function(u,r){return u};function jb(i){var u,r=i.getItemOffset,c=i.getEstimatedTotalSize,f=i.getItemSize,d=i.getOffsetForIndexAndAlignment,h=i.getStartIndexForOffset,m=i.getStopIndexForStartIndex,x=i.initInstanceProps,g=i.shouldResetStyleCacheOnItemSizeChange,C=i.validateProps;return u=(function(_){xb(A,_);function A(N){var p;return p=_.call(this,N)||this,p._instanceProps=x(p.props,ep(p)),p._outerRef=void 0,p._resetIsScrollingTimeoutId=null,p.state={instance:ep(p),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof p.props.initialScrollOffset=="number"?p.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},p._callOnItemsRendered=void 0,p._callOnItemsRendered=Nc(function(b,v,j,k){return p.props.onItemsRendered({overscanStartIndex:b,overscanStopIndex:v,visibleStartIndex:j,visibleStopIndex:k})}),p._callOnScroll=void 0,p._callOnScroll=Nc(function(b,v,j){return p.props.onScroll({scrollDirection:b,scrollOffset:v,scrollUpdateWasRequested:j})}),p._getItemStyle=void 0,p._getItemStyle=function(b){var v=p.props,j=v.direction,k=v.itemSize,B=v.layout,D=p._getItemStyleCache(g&&k,g&&B,g&&j),M;if(D.hasOwnProperty(b))M=D[b];else{var O=r(p.props,b,p._instanceProps),X=f(p.props,b,p._instanceProps),$=j==="horizontal"||B==="horizontal",oe=j==="rtl",ce=$?O:0;D[b]=M={position:"absolute",left:oe?void 0:ce,right:oe?ce:void 0,top:$?0:O,height:$?"100%":X,width:$?X:"100%"}}return M},p._getItemStyleCache=void 0,p._getItemStyleCache=Nc(function(b,v,j){return{}}),p._onScrollHorizontal=function(b){var v=b.currentTarget,j=v.clientWidth,k=v.scrollLeft,B=v.scrollWidth;p.setState(function(D){if(D.scrollOffset===k)return null;var M=p.props.direction,O=k;if(M==="rtl")switch(ip()){case"negative":O=-k;break;case"positive-descending":O=B-j-k;break}return O=Math.max(0,Math.min(O,B-j)),{isScrolling:!0,scrollDirection:D.scrollOffset<O?"forward":"backward",scrollOffset:O,scrollUpdateWasRequested:!1}},p._resetIsScrollingDebounced)},p._onScrollVertical=function(b){var v=b.currentTarget,j=v.clientHeight,k=v.scrollHeight,B=v.scrollTop;p.setState(function(D){if(D.scrollOffset===B)return null;var M=Math.max(0,Math.min(B,k-j));return{isScrolling:!0,scrollDirection:D.scrollOffset<M?"forward":"backward",scrollOffset:M,scrollUpdateWasRequested:!1}},p._resetIsScrollingDebounced)},p._outerRefSetter=function(b){var v=p.props.outerRef;p._outerRef=b,typeof v=="function"?v(b):v!=null&&typeof v=="object"&&v.hasOwnProperty("current")&&(v.current=b)},p._resetIsScrollingDebounced=function(){p._resetIsScrollingTimeoutId!==null&&np(p._resetIsScrollingTimeoutId),p._resetIsScrollingTimeoutId=vb(p._resetIsScrolling,wb)},p._resetIsScrolling=function(){p._resetIsScrollingTimeoutId=null,p.setState({isScrolling:!1},function(){p._getItemStyleCache(-1,null)})},p}A.getDerivedStateFromProps=function(p,b){return _b(p,b),C(p),null};var w=A.prototype;return w.scrollTo=function(p){p=Math.max(0,p),this.setState(function(b){return b.scrollOffset===p?null:{scrollDirection:b.scrollOffset<p?"forward":"backward",scrollOffset:p,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},w.scrollToItem=function(p,b){b===void 0&&(b="auto");var v=this.props,j=v.itemCount,k=v.layout,B=this.state.scrollOffset;p=Math.max(0,Math.min(p,j-1));var D=0;if(this._outerRef){var M=this._outerRef;k==="vertical"?D=M.scrollWidth>M.clientWidth?lp():0:D=M.scrollHeight>M.clientHeight?lp():0}this.scrollTo(d(this.props,p,b,B,this._instanceProps,D))},w.componentDidMount=function(){var p=this.props,b=p.direction,v=p.initialScrollOffset,j=p.layout;if(typeof v=="number"&&this._outerRef!=null){var k=this._outerRef;b==="horizontal"||j==="horizontal"?k.scrollLeft=v:k.scrollTop=v}this._callPropsCallbacks()},w.componentDidUpdate=function(){var p=this.props,b=p.direction,v=p.layout,j=this.state,k=j.scrollOffset,B=j.scrollUpdateWasRequested;if(B&&this._outerRef!=null){var D=this._outerRef;if(b==="horizontal"||v==="horizontal")if(b==="rtl")switch(ip()){case"negative":D.scrollLeft=-k;break;case"positive-ascending":D.scrollLeft=k;break;default:var M=D.clientWidth,O=D.scrollWidth;D.scrollLeft=O-M-k;break}else D.scrollLeft=k;else D.scrollTop=k}this._callPropsCallbacks()},w.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&np(this._resetIsScrollingTimeoutId)},w.render=function(){var p=this.props,b=p.children,v=p.className,j=p.direction,k=p.height,B=p.innerRef,D=p.innerElementType,M=p.innerTagName,O=p.itemCount,X=p.itemData,$=p.itemKey,oe=$===void 0?Sb:$,ce=p.layout,q=p.outerElementType,P=p.outerTagName,E=p.style,ne=p.useIsScrolling,Q=p.width,Z=this.state.isScrolling,we=j==="horizontal"||ce==="horizontal",F=we?this._onScrollHorizontal:this._onScrollVertical,he=this._getRangeToRender(),z=he[0],U=he[1],te=[];if(O>0)for(var ae=z;ae<=U;ae++)te.push(R.createElement(b,{data:X,key:oe(ae,X),index:ae,isScrolling:ne?Z:void 0,style:this._getItemStyle(ae)}));var Y=c(this.props,this._instanceProps);return R.createElement(q||P||"div",{className:v,onScroll:F,ref:this._outerRefSetter,style:Mc({position:"relative",height:k,width:Q,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:j},E)},R.createElement(D||M||"div",{children:te,ref:B,style:{height:we?"100%":Y,pointerEvents:Z?"none":void 0,width:we?Y:"100%"}}))},w._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var p=this.props.itemCount;if(p>0){var b=this._getRangeToRender(),v=b[0],j=b[1],k=b[2],B=b[3];this._callOnItemsRendered(v,j,k,B)}}if(typeof this.props.onScroll=="function"){var D=this.state,M=D.scrollDirection,O=D.scrollOffset,X=D.scrollUpdateWasRequested;this._callOnScroll(M,O,X)}},w._getRangeToRender=function(){var p=this.props,b=p.itemCount,v=p.overscanCount,j=this.state,k=j.isScrolling,B=j.scrollDirection,D=j.scrollOffset;if(b===0)return[0,0,0,0];var M=h(this.props,D,this._instanceProps),O=m(this.props,M,D,this._instanceProps),X=!k||B==="backward"?Math.max(1,v):1,$=!k||B==="forward"?Math.max(1,v):1;return[Math.max(0,M-X),Math.max(0,Math.min(b-1,O+$)),M,O]},A})(R.PureComponent),u.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},u}var _b=function(u,r){u.children,u.direction,u.height,u.layout,u.innerTagName,u.outerTagName,u.width,r.instance},nr=jb({getItemOffset:function(u,r){var c=u.itemSize;return r*c},getItemSize:function(u,r){var c=u.itemSize;return c},getEstimatedTotalSize:function(u){var r=u.itemCount,c=u.itemSize;return c*r},getOffsetForIndexAndAlignment:function(u,r,c,f,d,h){var m=u.direction,x=u.height,g=u.itemCount,C=u.itemSize,_=u.layout,A=u.width,w=m==="horizontal"||_==="horizontal",N=w?A:x,p=Math.max(0,g*C-N),b=Math.min(p,r*C),v=Math.max(0,r*C-N+C+h);switch(c==="smart"&&(f>=v-N&&f<=b+N?c="auto":c="center"),c){case"start":return b;case"end":return v;case"center":{var j=Math.round(v+(b-v)/2);return j<Math.ceil(N/2)?0:j>p+Math.floor(N/2)?p:j}default:return f>=v&&f<=b?f:f<v?v:b}},getStartIndexForOffset:function(u,r){var c=u.itemCount,f=u.itemSize;return Math.max(0,Math.min(c-1,Math.floor(r/f)))},getStopIndexForStartIndex:function(u,r,c){var f=u.direction,d=u.height,h=u.itemCount,m=u.itemSize,x=u.layout,g=u.width,C=f==="horizontal"||x==="horizontal",_=r*m,A=C?g:d,w=Math.ceil((A+c-_)/m);return Math.max(0,Math.min(h-1,r+w-1))},initInstanceProps:function(u){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(u){u.itemSize}});const Nb=(i,u=2)=>{if(i===0)return"0 B";const r=1024,c=u<0?0:u,f=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],d=Math.floor(Math.log(i)/Math.log(r));return parseFloat((i/Math.pow(r,d)).toFixed(c))+" "+f[d]},Cb=({capture:i,onDelete:u})=>{const r=new URL(i.url,window.location.origin).toString();return l.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.02] overflow-hidden",children:[l.jsxs("div",{className:"p-3 border-b border-white/10 flex items-center justify-between",children:[l.jsx("div",{className:"text-[9px] font-bold text-white uppercase tracking-widest",children:i.type==="recording"?"Recording":"Screenshot"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ws,{text:r,title:"Copy URL",className:"p-1.5 rounded-lg text-white/50 hover:text-white hover:bg-white/10 transition-all",iconClassName:"text-sm"}),l.jsx("a",{href:i.url,target:"_blank",rel:"noreferrer",className:"text-[9px] font-bold uppercase tracking-widest text-blue-300 hover:text-blue-200 rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:"Open"}),u&&l.jsx("button",{onClick:()=>u(i.name),className:"text-[9px] font-bold uppercase tracking-widest text-red-300 hover:text-red-200 rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:"Delete"})]})]}),l.jsx("div",{className:"bg-black relative group",children:i.type==="recording"?l.jsx("video",{src:i.url,controls:!0,className:"w-full h-64 object-contain bg-black"}):l.jsx("img",{src:i.url,className:"w-full h-64 object-contain bg-black",alt:`Screenshot of ${i.name}`})}),l.jsxs("div",{className:"p-3 border-t border-white/5 bg-white/[0.01]",children:[l.jsx("div",{className:"text-[9px] text-white font-bold uppercase tracking-widest truncate",title:i.name,children:i.name}),l.jsxs("div",{className:"flex items-center justify-between mt-1 text-[8px] text-gray-500 uppercase tracking-widest",children:[l.jsx("span",{children:Nb(i.size)}),l.jsx("span",{children:new Date(i.modified).toLocaleDateString()})]})]})]})},Yp=Fe.memo(Cb);function Vs(i){throw new Error('Could not dynamically require "'+i+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ec={exports:{}};var sp;function Eb(){return sp||(sp=1,(function(i,u){(function(r){i.exports=r()})(function(){return(function r(c,f,d){function h(g,C){if(!f[g]){if(!c[g]){var _=typeof Vs=="function"&&Vs;if(!C&&_)return _(g,!0);if(m)return m(g,!0);var A=new Error("Cannot find module '"+g+"'");throw A.code="MODULE_NOT_FOUND",A}var w=f[g]={exports:{}};c[g][0].call(w.exports,function(N){var p=c[g][1][N];return h(p||N)},w,w.exports,r,c,f,d)}return f[g].exports}for(var m=typeof Vs=="function"&&Vs,x=0;x<d.length;x++)h(d[x]);return h})({1:[function(r,c,f){var d=r("./utils"),h=r("./support"),m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";f.encode=function(x){for(var g,C,_,A,w,N,p,b=[],v=0,j=x.length,k=j,B=d.getTypeOf(x)!=="string";v<x.length;)k=j-v,_=B?(g=x[v++],C=v<j?x[v++]:0,v<j?x[v++]:0):(g=x.charCodeAt(v++),C=v<j?x.charCodeAt(v++):0,v<j?x.charCodeAt(v++):0),A=g>>2,w=(3&g)<<4|C>>4,N=1<k?(15&C)<<2|_>>6:64,p=2<k?63&_:64,b.push(m.charAt(A)+m.charAt(w)+m.charAt(N)+m.charAt(p));return b.join("")},f.decode=function(x){var g,C,_,A,w,N,p=0,b=0,v="data:";if(x.substr(0,v.length)===v)throw new Error("Invalid base64 input, it looks like a data url.");var j,k=3*(x=x.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(x.charAt(x.length-1)===m.charAt(64)&&k--,x.charAt(x.length-2)===m.charAt(64)&&k--,k%1!=0)throw new Error("Invalid base64 input, bad content length.");for(j=h.uint8array?new Uint8Array(0|k):new Array(0|k);p<x.length;)g=m.indexOf(x.charAt(p++))<<2|(A=m.indexOf(x.charAt(p++)))>>4,C=(15&A)<<4|(w=m.indexOf(x.charAt(p++)))>>2,_=(3&w)<<6|(N=m.indexOf(x.charAt(p++))),j[b++]=g,w!==64&&(j[b++]=C),N!==64&&(j[b++]=_);return j}},{"./support":30,"./utils":32}],2:[function(r,c,f){var d=r("./external"),h=r("./stream/DataWorker"),m=r("./stream/Crc32Probe"),x=r("./stream/DataLengthProbe");function g(C,_,A,w,N){this.compressedSize=C,this.uncompressedSize=_,this.crc32=A,this.compression=w,this.compressedContent=N}g.prototype={getContentWorker:function(){var C=new h(d.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new x("data_length")),_=this;return C.on("end",function(){if(this.streamInfo.data_length!==_.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),C},getCompressedWorker:function(){return new h(d.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},g.createWorkerFrom=function(C,_,A){return C.pipe(new m).pipe(new x("uncompressedSize")).pipe(_.compressWorker(A)).pipe(new x("compressedSize")).withStreamInfo("compression",_)},c.exports=g},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,c,f){var d=r("./stream/GenericWorker");f.STORE={magic:"\0\0",compressWorker:function(){return new d("STORE compression")},uncompressWorker:function(){return new d("STORE decompression")}},f.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,c,f){var d=r("./utils"),h=(function(){for(var m,x=[],g=0;g<256;g++){m=g;for(var C=0;C<8;C++)m=1&m?3988292384^m>>>1:m>>>1;x[g]=m}return x})();c.exports=function(m,x){return m!==void 0&&m.length?d.getTypeOf(m)!=="string"?(function(g,C,_,A){var w=h,N=A+_;g^=-1;for(var p=A;p<N;p++)g=g>>>8^w[255&(g^C[p])];return-1^g})(0|x,m,m.length,0):(function(g,C,_,A){var w=h,N=A+_;g^=-1;for(var p=A;p<N;p++)g=g>>>8^w[255&(g^C.charCodeAt(p))];return-1^g})(0|x,m,m.length,0):0}},{"./utils":32}],5:[function(r,c,f){f.base64=!1,f.binary=!1,f.dir=!1,f.createFolders=!0,f.date=null,f.compression=null,f.compressionOptions=null,f.comment=null,f.unixPermissions=null,f.dosPermissions=null},{}],6:[function(r,c,f){var d=null;d=typeof Promise<"u"?Promise:r("lie"),c.exports={Promise:d}},{lie:37}],7:[function(r,c,f){var d=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",h=r("pako"),m=r("./utils"),x=r("./stream/GenericWorker"),g=d?"uint8array":"array";function C(_,A){x.call(this,"FlateWorker/"+_),this._pako=null,this._pakoAction=_,this._pakoOptions=A,this.meta={}}f.magic="\b\0",m.inherits(C,x),C.prototype.processChunk=function(_){this.meta=_.meta,this._pako===null&&this._createPako(),this._pako.push(m.transformTo(g,_.data),!1)},C.prototype.flush=function(){x.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},C.prototype.cleanUp=function(){x.prototype.cleanUp.call(this),this._pako=null},C.prototype._createPako=function(){this._pako=new h[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var _=this;this._pako.onData=function(A){_.push({data:A,meta:_.meta})}},f.compressWorker=function(_){return new C("Deflate",_)},f.uncompressWorker=function(){return new C("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,c,f){function d(w,N){var p,b="";for(p=0;p<N;p++)b+=String.fromCharCode(255&w),w>>>=8;return b}function h(w,N,p,b,v,j){var k,B,D=w.file,M=w.compression,O=j!==g.utf8encode,X=m.transformTo("string",j(D.name)),$=m.transformTo("string",g.utf8encode(D.name)),oe=D.comment,ce=m.transformTo("string",j(oe)),q=m.transformTo("string",g.utf8encode(oe)),P=$.length!==D.name.length,E=q.length!==oe.length,ne="",Q="",Z="",we=D.dir,F=D.date,he={crc32:0,compressedSize:0,uncompressedSize:0};N&&!p||(he.crc32=w.crc32,he.compressedSize=w.compressedSize,he.uncompressedSize=w.uncompressedSize);var z=0;N&&(z|=8),O||!P&&!E||(z|=2048);var U=0,te=0;we&&(U|=16),v==="UNIX"?(te=798,U|=(function(Y,me){var Ne=Y;return Y||(Ne=me?16893:33204),(65535&Ne)<<16})(D.unixPermissions,we)):(te=20,U|=(function(Y){return 63&(Y||0)})(D.dosPermissions)),k=F.getUTCHours(),k<<=6,k|=F.getUTCMinutes(),k<<=5,k|=F.getUTCSeconds()/2,B=F.getUTCFullYear()-1980,B<<=4,B|=F.getUTCMonth()+1,B<<=5,B|=F.getUTCDate(),P&&(Q=d(1,1)+d(C(X),4)+$,ne+="up"+d(Q.length,2)+Q),E&&(Z=d(1,1)+d(C(ce),4)+q,ne+="uc"+d(Z.length,2)+Z);var ae="";return ae+=`
|
|
12
12
|
\0`,ae+=d(z,2),ae+=M.magic,ae+=d(k,2),ae+=d(B,2),ae+=d(he.crc32,4),ae+=d(he.compressedSize,4),ae+=d(he.uncompressedSize,4),ae+=d(X.length,2),ae+=d(ne.length,2),{fileRecord:_.LOCAL_FILE_HEADER+ae+X+ne,dirRecord:_.CENTRAL_FILE_HEADER+d(te,2)+ae+d(ce.length,2)+"\0\0\0\0"+d(U,4)+d(b,4)+X+ne+ce}}var m=r("../utils"),x=r("../stream/GenericWorker"),g=r("../utf8"),C=r("../crc32"),_=r("../signature");function A(w,N,p,b){x.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=N,this.zipPlatform=p,this.encodeFileName=b,this.streamFiles=w,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}m.inherits(A,x),A.prototype.push=function(w){var N=w.meta.percent||0,p=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(w):(this.bytesWritten+=w.data.length,x.prototype.push.call(this,{data:w.data,meta:{currentFile:this.currentFile,percent:p?(N+100*(p-b-1))/p:100}}))},A.prototype.openedSource=function(w){this.currentSourceOffset=this.bytesWritten,this.currentFile=w.file.name;var N=this.streamFiles&&!w.file.dir;if(N){var p=h(w,N,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},A.prototype.closedSource=function(w){this.accumulate=!1;var N=this.streamFiles&&!w.file.dir,p=h(w,N,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),N)this.push({data:(function(b){return _.DATA_DESCRIPTOR+d(b.crc32,4)+d(b.compressedSize,4)+d(b.uncompressedSize,4)})(w),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},A.prototype.flush=function(){for(var w=this.bytesWritten,N=0;N<this.dirRecords.length;N++)this.push({data:this.dirRecords[N],meta:{percent:100}});var p=this.bytesWritten-w,b=(function(v,j,k,B,D){var M=m.transformTo("string",D(B));return _.CENTRAL_DIRECTORY_END+"\0\0\0\0"+d(v,2)+d(v,2)+d(j,4)+d(k,4)+d(M.length,2)+M})(this.dirRecords.length,p,w,this.zipComment,this.encodeFileName);this.push({data:b,meta:{percent:100}})},A.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},A.prototype.registerPrevious=function(w){this._sources.push(w);var N=this;return w.on("data",function(p){N.processChunk(p)}),w.on("end",function(){N.closedSource(N.previous.streamInfo),N._sources.length?N.prepareNextSource():N.end()}),w.on("error",function(p){N.error(p)}),this},A.prototype.resume=function(){return!!x.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},A.prototype.error=function(w){var N=this._sources;if(!x.prototype.error.call(this,w))return!1;for(var p=0;p<N.length;p++)try{N[p].error(w)}catch{}return!0},A.prototype.lock=function(){x.prototype.lock.call(this);for(var w=this._sources,N=0;N<w.length;N++)w[N].lock()},c.exports=A},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(r,c,f){var d=r("../compressions"),h=r("./ZipFileWorker");f.generateWorker=function(m,x,g){var C=new h(x.streamFiles,g,x.platform,x.encodeFileName),_=0;try{m.forEach(function(A,w){_++;var N=(function(j,k){var B=j||k,D=d[B];if(!D)throw new Error(B+" is not a valid compression method !");return D})(w.options.compression,x.compression),p=w.options.compressionOptions||x.compressionOptions||{},b=w.dir,v=w.date;w._compressWorker(N,p).withStreamInfo("file",{name:A,dir:b,date:v,comment:w.comment||"",unixPermissions:w.unixPermissions,dosPermissions:w.dosPermissions}).pipe(C)}),C.entriesCount=_}catch(A){C.error(A)}return C}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(r,c,f){function d(){if(!(this instanceof d))return new d;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var h=new d;for(var m in this)typeof this[m]!="function"&&(h[m]=this[m]);return h}}(d.prototype=r("./object")).loadAsync=r("./load"),d.support=r("./support"),d.defaults=r("./defaults"),d.version="3.10.1",d.loadAsync=function(h,m){return new d().loadAsync(h,m)},d.external=r("./external"),c.exports=d},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(r,c,f){var d=r("./utils"),h=r("./external"),m=r("./utf8"),x=r("./zipEntries"),g=r("./stream/Crc32Probe"),C=r("./nodejsUtils");function _(A){return new h.Promise(function(w,N){var p=A.decompressed.getContentWorker().pipe(new g);p.on("error",function(b){N(b)}).on("end",function(){p.streamInfo.crc32!==A.decompressed.crc32?N(new Error("Corrupted zip : CRC32 mismatch")):w()}).resume()})}c.exports=function(A,w){var N=this;return w=d.extend(w||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:m.utf8decode}),C.isNode&&C.isStream(A)?h.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):d.prepareContent("the loaded zip file",A,!0,w.optimizedBinaryString,w.base64).then(function(p){var b=new x(w);return b.load(p),b}).then(function(p){var b=[h.Promise.resolve(p)],v=p.files;if(w.checkCRC32)for(var j=0;j<v.length;j++)b.push(_(v[j]));return h.Promise.all(b)}).then(function(p){for(var b=p.shift(),v=b.files,j=0;j<v.length;j++){var k=v[j],B=k.fileNameStr,D=d.resolve(k.fileNameStr);N.file(D,k.decompressed,{binary:!0,optimizedBinaryString:!0,date:k.date,dir:k.dir,comment:k.fileCommentStr.length?k.fileCommentStr:null,unixPermissions:k.unixPermissions,dosPermissions:k.dosPermissions,createFolders:w.createFolders}),k.dir||(N.file(D).unsafeOriginalName=B)}return b.zipComment.length&&(N.comment=b.zipComment),N})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(r,c,f){var d=r("../utils"),h=r("../stream/GenericWorker");function m(x,g){h.call(this,"Nodejs stream input adapter for "+x),this._upstreamEnded=!1,this._bindStream(g)}d.inherits(m,h),m.prototype._bindStream=function(x){var g=this;(this._stream=x).pause(),x.on("data",function(C){g.push({data:C,meta:{percent:0}})}).on("error",function(C){g.isPaused?this.generatedError=C:g.error(C)}).on("end",function(){g.isPaused?g._upstreamEnded=!0:g.end()})},m.prototype.pause=function(){return!!h.prototype.pause.call(this)&&(this._stream.pause(),!0)},m.prototype.resume=function(){return!!h.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},c.exports=m},{"../stream/GenericWorker":28,"../utils":32}],13:[function(r,c,f){var d=r("readable-stream").Readable;function h(m,x,g){d.call(this,x),this._helper=m;var C=this;m.on("data",function(_,A){C.push(_)||C._helper.pause(),g&&g(A)}).on("error",function(_){C.emit("error",_)}).on("end",function(){C.push(null)})}r("../utils").inherits(h,d),h.prototype._read=function(){this._helper.resume()},c.exports=h},{"../utils":32,"readable-stream":16}],14:[function(r,c,f){c.exports={isNode:typeof Buffer<"u",newBufferFrom:function(d,h){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(d,h);if(typeof d=="number")throw new Error('The "data" argument must not be a number');return new Buffer(d,h)},allocBuffer:function(d){if(Buffer.alloc)return Buffer.alloc(d);var h=new Buffer(d);return h.fill(0),h},isBuffer:function(d){return Buffer.isBuffer(d)},isStream:function(d){return d&&typeof d.on=="function"&&typeof d.pause=="function"&&typeof d.resume=="function"}}},{}],15:[function(r,c,f){function d(D,M,O){var X,$=m.getTypeOf(M),oe=m.extend(O||{},C);oe.date=oe.date||new Date,oe.compression!==null&&(oe.compression=oe.compression.toUpperCase()),typeof oe.unixPermissions=="string"&&(oe.unixPermissions=parseInt(oe.unixPermissions,8)),oe.unixPermissions&&16384&oe.unixPermissions&&(oe.dir=!0),oe.dosPermissions&&16&oe.dosPermissions&&(oe.dir=!0),oe.dir&&(D=v(D)),oe.createFolders&&(X=b(D))&&j.call(this,X,!0);var ce=$==="string"&&oe.binary===!1&&oe.base64===!1;O&&O.binary!==void 0||(oe.binary=!ce),(M instanceof _&&M.uncompressedSize===0||oe.dir||!M||M.length===0)&&(oe.base64=!1,oe.binary=!0,M="",oe.compression="STORE",$="string");var q=null;q=M instanceof _||M instanceof x?M:N.isNode&&N.isStream(M)?new p(D,M):m.prepareContent(D,M,oe.binary,oe.optimizedBinaryString,oe.base64);var P=new A(D,q,oe);this.files[D]=P}var h=r("./utf8"),m=r("./utils"),x=r("./stream/GenericWorker"),g=r("./stream/StreamHelper"),C=r("./defaults"),_=r("./compressedObject"),A=r("./zipObject"),w=r("./generate"),N=r("./nodejsUtils"),p=r("./nodejs/NodejsStreamInputAdapter"),b=function(D){D.slice(-1)==="/"&&(D=D.substring(0,D.length-1));var M=D.lastIndexOf("/");return 0<M?D.substring(0,M):""},v=function(D){return D.slice(-1)!=="/"&&(D+="/"),D},j=function(D,M){return M=M!==void 0?M:C.createFolders,D=v(D),this.files[D]||d.call(this,D,null,{dir:!0,createFolders:M}),this.files[D]};function k(D){return Object.prototype.toString.call(D)==="[object RegExp]"}var B={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(D){var M,O,X;for(M in this.files)X=this.files[M],(O=M.slice(this.root.length,M.length))&&M.slice(0,this.root.length)===this.root&&D(O,X)},filter:function(D){var M=[];return this.forEach(function(O,X){D(O,X)&&M.push(X)}),M},file:function(D,M,O){if(arguments.length!==1)return D=this.root+D,d.call(this,D,M,O),this;if(k(D)){var X=D;return this.filter(function(oe,ce){return!ce.dir&&X.test(oe)})}var $=this.files[this.root+D];return $&&!$.dir?$:null},folder:function(D){if(!D)return this;if(k(D))return this.filter(function($,oe){return oe.dir&&D.test($)});var M=this.root+D,O=j.call(this,M),X=this.clone();return X.root=O.name,X},remove:function(D){D=this.root+D;var M=this.files[D];if(M||(D.slice(-1)!=="/"&&(D+="/"),M=this.files[D]),M&&!M.dir)delete this.files[D];else for(var O=this.filter(function($,oe){return oe.name.slice(0,D.length)===D}),X=0;X<O.length;X++)delete this.files[O[X].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(D){var M,O={};try{if((O=m.extend(D||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:h.utf8encode})).type=O.type.toLowerCase(),O.compression=O.compression.toUpperCase(),O.type==="binarystring"&&(O.type="string"),!O.type)throw new Error("No output type specified.");m.checkSupport(O.type),O.platform!=="darwin"&&O.platform!=="freebsd"&&O.platform!=="linux"&&O.platform!=="sunos"||(O.platform="UNIX"),O.platform==="win32"&&(O.platform="DOS");var X=O.comment||this.comment||"";M=w.generateWorker(this,O,X)}catch($){(M=new x("error")).error($)}return new g(M,O.type||"string",O.mimeType)},generateAsync:function(D,M){return this.generateInternalStream(D).accumulate(M)},generateNodeStream:function(D,M){return(D=D||{}).type||(D.type="nodebuffer"),this.generateInternalStream(D).toNodejsStream(M)}};c.exports=B},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(r,c,f){c.exports=r("stream")},{stream:void 0}],17:[function(r,c,f){var d=r("./DataReader");function h(m){d.call(this,m);for(var x=0;x<this.data.length;x++)m[x]=255&m[x]}r("../utils").inherits(h,d),h.prototype.byteAt=function(m){return this.data[this.zero+m]},h.prototype.lastIndexOfSignature=function(m){for(var x=m.charCodeAt(0),g=m.charCodeAt(1),C=m.charCodeAt(2),_=m.charCodeAt(3),A=this.length-4;0<=A;--A)if(this.data[A]===x&&this.data[A+1]===g&&this.data[A+2]===C&&this.data[A+3]===_)return A-this.zero;return-1},h.prototype.readAndCheckSignature=function(m){var x=m.charCodeAt(0),g=m.charCodeAt(1),C=m.charCodeAt(2),_=m.charCodeAt(3),A=this.readData(4);return x===A[0]&&g===A[1]&&C===A[2]&&_===A[3]},h.prototype.readData=function(m){if(this.checkOffset(m),m===0)return[];var x=this.data.slice(this.zero+this.index,this.zero+this.index+m);return this.index+=m,x},c.exports=h},{"../utils":32,"./DataReader":18}],18:[function(r,c,f){var d=r("../utils");function h(m){this.data=m,this.length=m.length,this.index=0,this.zero=0}h.prototype={checkOffset:function(m){this.checkIndex(this.index+m)},checkIndex:function(m){if(this.length<this.zero+m||m<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+m+"). Corrupted zip ?")},setIndex:function(m){this.checkIndex(m),this.index=m},skip:function(m){this.setIndex(this.index+m)},byteAt:function(){},readInt:function(m){var x,g=0;for(this.checkOffset(m),x=this.index+m-1;x>=this.index;x--)g=(g<<8)+this.byteAt(x);return this.index+=m,g},readString:function(m){return d.transformTo("string",this.readData(m))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var m=this.readInt(4);return new Date(Date.UTC(1980+(m>>25&127),(m>>21&15)-1,m>>16&31,m>>11&31,m>>5&63,(31&m)<<1))}},c.exports=h},{"../utils":32}],19:[function(r,c,f){var d=r("./Uint8ArrayReader");function h(m){d.call(this,m)}r("../utils").inherits(h,d),h.prototype.readData=function(m){this.checkOffset(m);var x=this.data.slice(this.zero+this.index,this.zero+this.index+m);return this.index+=m,x},c.exports=h},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,c,f){var d=r("./DataReader");function h(m){d.call(this,m)}r("../utils").inherits(h,d),h.prototype.byteAt=function(m){return this.data.charCodeAt(this.zero+m)},h.prototype.lastIndexOfSignature=function(m){return this.data.lastIndexOf(m)-this.zero},h.prototype.readAndCheckSignature=function(m){return m===this.readData(4)},h.prototype.readData=function(m){this.checkOffset(m);var x=this.data.slice(this.zero+this.index,this.zero+this.index+m);return this.index+=m,x},c.exports=h},{"../utils":32,"./DataReader":18}],21:[function(r,c,f){var d=r("./ArrayReader");function h(m){d.call(this,m)}r("../utils").inherits(h,d),h.prototype.readData=function(m){if(this.checkOffset(m),m===0)return new Uint8Array(0);var x=this.data.subarray(this.zero+this.index,this.zero+this.index+m);return this.index+=m,x},c.exports=h},{"../utils":32,"./ArrayReader":17}],22:[function(r,c,f){var d=r("../utils"),h=r("../support"),m=r("./ArrayReader"),x=r("./StringReader"),g=r("./NodeBufferReader"),C=r("./Uint8ArrayReader");c.exports=function(_){var A=d.getTypeOf(_);return d.checkSupport(A),A!=="string"||h.uint8array?A==="nodebuffer"?new g(_):h.uint8array?new C(d.transformTo("uint8array",_)):new m(d.transformTo("array",_)):new x(_)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,c,f){f.LOCAL_FILE_HEADER="PK",f.CENTRAL_FILE_HEADER="PK",f.CENTRAL_DIRECTORY_END="PK",f.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",f.ZIP64_CENTRAL_DIRECTORY_END="PK",f.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(r,c,f){var d=r("./GenericWorker"),h=r("../utils");function m(x){d.call(this,"ConvertWorker to "+x),this.destType=x}h.inherits(m,d),m.prototype.processChunk=function(x){this.push({data:h.transformTo(this.destType,x.data),meta:x.meta})},c.exports=m},{"../utils":32,"./GenericWorker":28}],25:[function(r,c,f){var d=r("./GenericWorker"),h=r("../crc32");function m(){d.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(m,d),m.prototype.processChunk=function(x){this.streamInfo.crc32=h(x.data,this.streamInfo.crc32||0),this.push(x)},c.exports=m},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,c,f){var d=r("../utils"),h=r("./GenericWorker");function m(x){h.call(this,"DataLengthProbe for "+x),this.propName=x,this.withStreamInfo(x,0)}d.inherits(m,h),m.prototype.processChunk=function(x){if(x){var g=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=g+x.data.length}h.prototype.processChunk.call(this,x)},c.exports=m},{"../utils":32,"./GenericWorker":28}],27:[function(r,c,f){var d=r("../utils"),h=r("./GenericWorker");function m(x){h.call(this,"DataWorker");var g=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,x.then(function(C){g.dataIsReady=!0,g.data=C,g.max=C&&C.length||0,g.type=d.getTypeOf(C),g.isPaused||g._tickAndRepeat()},function(C){g.error(C)})}d.inherits(m,h),m.prototype.cleanUp=function(){h.prototype.cleanUp.call(this),this.data=null},m.prototype.resume=function(){return!!h.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,d.delay(this._tickAndRepeat,[],this)),!0)},m.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(d.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},m.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var x=null,g=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":x=this.data.substring(this.index,g);break;case"uint8array":x=this.data.subarray(this.index,g);break;case"array":case"nodebuffer":x=this.data.slice(this.index,g)}return this.index=g,this.push({data:x,meta:{percent:this.max?this.index/this.max*100:0}})},c.exports=m},{"../utils":32,"./GenericWorker":28}],28:[function(r,c,f){function d(h){this.name=h||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}d.prototype={push:function(h){this.emit("data",h)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(h){this.emit("error",h)}return!0},error:function(h){return!this.isFinished&&(this.isPaused?this.generatedError=h:(this.isFinished=!0,this.emit("error",h),this.previous&&this.previous.error(h),this.cleanUp()),!0)},on:function(h,m){return this._listeners[h].push(m),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(h,m){if(this._listeners[h])for(var x=0;x<this._listeners[h].length;x++)this._listeners[h][x].call(this,m)},pipe:function(h){return h.registerPrevious(this)},registerPrevious:function(h){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=h.streamInfo,this.mergeStreamInfo(),this.previous=h;var m=this;return h.on("data",function(x){m.processChunk(x)}),h.on("end",function(){m.end()}),h.on("error",function(x){m.error(x)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var h=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),h=!0),this.previous&&this.previous.resume(),!h},flush:function(){},processChunk:function(h){this.push(h)},withStreamInfo:function(h,m){return this.extraStreamInfo[h]=m,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var h in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,h)&&(this.streamInfo[h]=this.extraStreamInfo[h])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var h="Worker "+this.name;return this.previous?this.previous+" -> "+h:h}},c.exports=d},{}],29:[function(r,c,f){var d=r("../utils"),h=r("./ConvertWorker"),m=r("./GenericWorker"),x=r("../base64"),g=r("../support"),C=r("../external"),_=null;if(g.nodestream)try{_=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function A(N,p){return new C.Promise(function(b,v){var j=[],k=N._internalType,B=N._outputType,D=N._mimeType;N.on("data",function(M,O){j.push(M),p&&p(O)}).on("error",function(M){j=[],v(M)}).on("end",function(){try{var M=(function(O,X,$){switch(O){case"blob":return d.newBlob(d.transformTo("arraybuffer",X),$);case"base64":return x.encode(X);default:return d.transformTo(O,X)}})(B,(function(O,X){var $,oe=0,ce=null,q=0;for($=0;$<X.length;$++)q+=X[$].length;switch(O){case"string":return X.join("");case"array":return Array.prototype.concat.apply([],X);case"uint8array":for(ce=new Uint8Array(q),$=0;$<X.length;$++)ce.set(X[$],oe),oe+=X[$].length;return ce;case"nodebuffer":return Buffer.concat(X);default:throw new Error("concat : unsupported type '"+O+"'")}})(k,j),D);b(M)}catch(O){v(O)}j=[]}).resume()})}function w(N,p,b){var v=p;switch(p){case"blob":case"arraybuffer":v="uint8array";break;case"base64":v="string"}try{this._internalType=v,this._outputType=p,this._mimeType=b,d.checkSupport(v),this._worker=N.pipe(new h(v)),N.lock()}catch(j){this._worker=new m("error"),this._worker.error(j)}}w.prototype={accumulate:function(N){return A(this,N)},on:function(N,p){var b=this;return N==="data"?this._worker.on(N,function(v){p.call(b,v.data,v.meta)}):this._worker.on(N,function(){d.delay(p,arguments,b)}),this},resume:function(){return d.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(N){if(d.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new _(this,{objectMode:this._outputType!=="nodebuffer"},N)}},c.exports=w},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(r,c,f){if(f.base64=!0,f.array=!0,f.string=!0,f.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",f.nodebuffer=typeof Buffer<"u",f.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")f.blob=!1;else{var d=new ArrayBuffer(0);try{f.blob=new Blob([d],{type:"application/zip"}).size===0}catch{try{var h=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);h.append(d),f.blob=h.getBlob("application/zip").size===0}catch{f.blob=!1}}}try{f.nodestream=!!r("readable-stream").Readable}catch{f.nodestream=!1}},{"readable-stream":16}],31:[function(r,c,f){for(var d=r("./utils"),h=r("./support"),m=r("./nodejsUtils"),x=r("./stream/GenericWorker"),g=new Array(256),C=0;C<256;C++)g[C]=252<=C?6:248<=C?5:240<=C?4:224<=C?3:192<=C?2:1;g[254]=g[254]=1;function _(){x.call(this,"utf-8 decode"),this.leftOver=null}function A(){x.call(this,"utf-8 encode")}f.utf8encode=function(w){return h.nodebuffer?m.newBufferFrom(w,"utf-8"):(function(N){var p,b,v,j,k,B=N.length,D=0;for(j=0;j<B;j++)(64512&(b=N.charCodeAt(j)))==55296&&j+1<B&&(64512&(v=N.charCodeAt(j+1)))==56320&&(b=65536+(b-55296<<10)+(v-56320),j++),D+=b<128?1:b<2048?2:b<65536?3:4;for(p=h.uint8array?new Uint8Array(D):new Array(D),j=k=0;k<D;j++)(64512&(b=N.charCodeAt(j)))==55296&&j+1<B&&(64512&(v=N.charCodeAt(j+1)))==56320&&(b=65536+(b-55296<<10)+(v-56320),j++),b<128?p[k++]=b:(b<2048?p[k++]=192|b>>>6:(b<65536?p[k++]=224|b>>>12:(p[k++]=240|b>>>18,p[k++]=128|b>>>12&63),p[k++]=128|b>>>6&63),p[k++]=128|63&b);return p})(w)},f.utf8decode=function(w){return h.nodebuffer?d.transformTo("nodebuffer",w).toString("utf-8"):(function(N){var p,b,v,j,k=N.length,B=new Array(2*k);for(p=b=0;p<k;)if((v=N[p++])<128)B[b++]=v;else if(4<(j=g[v]))B[b++]=65533,p+=j-1;else{for(v&=j===2?31:j===3?15:7;1<j&&p<k;)v=v<<6|63&N[p++],j--;1<j?B[b++]=65533:v<65536?B[b++]=v:(v-=65536,B[b++]=55296|v>>10&1023,B[b++]=56320|1023&v)}return B.length!==b&&(B.subarray?B=B.subarray(0,b):B.length=b),d.applyFromCharCode(B)})(w=d.transformTo(h.uint8array?"uint8array":"array",w))},d.inherits(_,x),_.prototype.processChunk=function(w){var N=d.transformTo(h.uint8array?"uint8array":"array",w.data);if(this.leftOver&&this.leftOver.length){if(h.uint8array){var p=N;(N=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),N.set(p,this.leftOver.length)}else N=this.leftOver.concat(N);this.leftOver=null}var b=(function(j,k){var B;for((k=k||j.length)>j.length&&(k=j.length),B=k-1;0<=B&&(192&j[B])==128;)B--;return B<0||B===0?k:B+g[j[B]]>k?B:k})(N),v=N;b!==N.length&&(h.uint8array?(v=N.subarray(0,b),this.leftOver=N.subarray(b,N.length)):(v=N.slice(0,b),this.leftOver=N.slice(b,N.length))),this.push({data:f.utf8decode(v),meta:w.meta})},_.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:f.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},f.Utf8DecodeWorker=_,d.inherits(A,x),A.prototype.processChunk=function(w){this.push({data:f.utf8encode(w.data),meta:w.meta})},f.Utf8EncodeWorker=A},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,c,f){var d=r("./support"),h=r("./base64"),m=r("./nodejsUtils"),x=r("./external");function g(p){return p}function C(p,b){for(var v=0;v<p.length;++v)b[v]=255&p.charCodeAt(v);return b}r("setimmediate"),f.newBlob=function(p,b){f.checkSupport("blob");try{return new Blob([p],{type:b})}catch{try{var v=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return v.append(p),v.getBlob(b)}catch{throw new Error("Bug : can't construct the Blob.")}}};var _={stringifyByChunk:function(p,b,v){var j=[],k=0,B=p.length;if(B<=v)return String.fromCharCode.apply(null,p);for(;k<B;)b==="array"||b==="nodebuffer"?j.push(String.fromCharCode.apply(null,p.slice(k,Math.min(k+v,B)))):j.push(String.fromCharCode.apply(null,p.subarray(k,Math.min(k+v,B)))),k+=v;return j.join("")},stringifyByChar:function(p){for(var b="",v=0;v<p.length;v++)b+=String.fromCharCode(p[v]);return b},applyCanBeUsed:{uint8array:(function(){try{return d.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return d.nodebuffer&&String.fromCharCode.apply(null,m.allocBuffer(1)).length===1}catch{return!1}})()}};function A(p){var b=65536,v=f.getTypeOf(p),j=!0;if(v==="uint8array"?j=_.applyCanBeUsed.uint8array:v==="nodebuffer"&&(j=_.applyCanBeUsed.nodebuffer),j)for(;1<b;)try{return _.stringifyByChunk(p,v,b)}catch{b=Math.floor(b/2)}return _.stringifyByChar(p)}function w(p,b){for(var v=0;v<p.length;v++)b[v]=p[v];return b}f.applyFromCharCode=A;var N={};N.string={string:g,array:function(p){return C(p,new Array(p.length))},arraybuffer:function(p){return N.string.uint8array(p).buffer},uint8array:function(p){return C(p,new Uint8Array(p.length))},nodebuffer:function(p){return C(p,m.allocBuffer(p.length))}},N.array={string:A,array:g,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return m.newBufferFrom(p)}},N.arraybuffer={string:function(p){return A(new Uint8Array(p))},array:function(p){return w(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:g,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return m.newBufferFrom(new Uint8Array(p))}},N.uint8array={string:A,array:function(p){return w(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:g,nodebuffer:function(p){return m.newBufferFrom(p)}},N.nodebuffer={string:A,array:function(p){return w(p,new Array(p.length))},arraybuffer:function(p){return N.nodebuffer.uint8array(p).buffer},uint8array:function(p){return w(p,new Uint8Array(p.length))},nodebuffer:g},f.transformTo=function(p,b){if(b=b||"",!p)return b;f.checkSupport(p);var v=f.getTypeOf(b);return N[v][p](b)},f.resolve=function(p){for(var b=p.split("/"),v=[],j=0;j<b.length;j++){var k=b[j];k==="."||k===""&&j!==0&&j!==b.length-1||(k===".."?v.pop():v.push(k))}return v.join("/")},f.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":d.nodebuffer&&m.isBuffer(p)?"nodebuffer":d.uint8array&&p instanceof Uint8Array?"uint8array":d.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},f.checkSupport=function(p){if(!d[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},f.MAX_VALUE_16BITS=65535,f.MAX_VALUE_32BITS=-1,f.pretty=function(p){var b,v,j="";for(v=0;v<(p||"").length;v++)j+="\\x"+((b=p.charCodeAt(v))<16?"0":"")+b.toString(16).toUpperCase();return j},f.delay=function(p,b,v){setImmediate(function(){p.apply(v||null,b||[])})},f.inherits=function(p,b){function v(){}v.prototype=b.prototype,p.prototype=new v},f.extend=function(){var p,b,v={};for(p=0;p<arguments.length;p++)for(b in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],b)&&v[b]===void 0&&(v[b]=arguments[p][b]);return v},f.prepareContent=function(p,b,v,j,k){return x.Promise.resolve(b).then(function(B){return d.blob&&(B instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(B))!==-1)&&typeof FileReader<"u"?new x.Promise(function(D,M){var O=new FileReader;O.onload=function(X){D(X.target.result)},O.onerror=function(X){M(X.target.error)},O.readAsArrayBuffer(B)}):B}).then(function(B){var D=f.getTypeOf(B);return D?(D==="arraybuffer"?B=f.transformTo("uint8array",B):D==="string"&&(k?B=h.decode(B):v&&j!==!0&&(B=(function(M){return C(M,d.uint8array?new Uint8Array(M.length):new Array(M.length))})(B))),B):x.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(r,c,f){var d=r("./reader/readerFor"),h=r("./utils"),m=r("./signature"),x=r("./zipEntry"),g=r("./support");function C(_){this.files=[],this.loadOptions=_}C.prototype={checkSignature:function(_){if(!this.reader.readAndCheckSignature(_)){this.reader.index-=4;var A=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+h.pretty(A)+", expected "+h.pretty(_)+")")}},isSignature:function(_,A){var w=this.reader.index;this.reader.setIndex(_);var N=this.reader.readString(4)===A;return this.reader.setIndex(w),N},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var _=this.reader.readData(this.zipCommentLength),A=g.uint8array?"uint8array":"array",w=h.transformTo(A,_);this.zipComment=this.loadOptions.decodeFileName(w)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var _,A,w,N=this.zip64EndOfCentralSize-44;0<N;)_=this.reader.readInt(2),A=this.reader.readInt(4),w=this.reader.readData(A),this.zip64ExtensibleData[_]={id:_,length:A,value:w}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var _,A;for(_=0;_<this.files.length;_++)A=this.files[_],this.reader.setIndex(A.localHeaderOffset),this.checkSignature(m.LOCAL_FILE_HEADER),A.readLocalPart(this.reader),A.handleUTF8(),A.processAttributes()},readCentralDir:function(){var _;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(m.CENTRAL_FILE_HEADER);)(_=new x({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(_);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var _=this.reader.lastIndexOfSignature(m.CENTRAL_DIRECTORY_END);if(_<0)throw this.isSignature(0,m.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(_);var A=_;if(this.checkSignature(m.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===h.MAX_VALUE_16BITS||this.diskWithCentralDirStart===h.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===h.MAX_VALUE_16BITS||this.centralDirRecords===h.MAX_VALUE_16BITS||this.centralDirSize===h.MAX_VALUE_32BITS||this.centralDirOffset===h.MAX_VALUE_32BITS){if(this.zip64=!0,(_=this.reader.lastIndexOfSignature(m.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(_),this.checkSignature(m.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,m.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(m.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(m.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var w=this.centralDirOffset+this.centralDirSize;this.zip64&&(w+=20,w+=12+this.zip64EndOfCentralSize);var N=A-w;if(0<N)this.isSignature(A,m.CENTRAL_FILE_HEADER)||(this.reader.zero=N);else if(N<0)throw new Error("Corrupted zip: missing "+Math.abs(N)+" bytes.")},prepareReader:function(_){this.reader=d(_)},load:function(_){this.prepareReader(_),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},c.exports=C},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(r,c,f){var d=r("./reader/readerFor"),h=r("./utils"),m=r("./compressedObject"),x=r("./crc32"),g=r("./utf8"),C=r("./compressions"),_=r("./support");function A(w,N){this.options=w,this.loadOptions=N}A.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(w){var N,p;if(w.skip(22),this.fileNameLength=w.readInt(2),p=w.readInt(2),this.fileName=w.readData(this.fileNameLength),w.skip(p),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((N=(function(b){for(var v in C)if(Object.prototype.hasOwnProperty.call(C,v)&&C[v].magic===b)return C[v];return null})(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+h.pretty(this.compressionMethod)+" unknown (inner file : "+h.transformTo("string",this.fileName)+")");this.decompressed=new m(this.compressedSize,this.uncompressedSize,this.crc32,N,w.readData(this.compressedSize))},readCentralPart:function(w){this.versionMadeBy=w.readInt(2),w.skip(2),this.bitFlag=w.readInt(2),this.compressionMethod=w.readString(2),this.date=w.readDate(),this.crc32=w.readInt(4),this.compressedSize=w.readInt(4),this.uncompressedSize=w.readInt(4);var N=w.readInt(2);if(this.extraFieldsLength=w.readInt(2),this.fileCommentLength=w.readInt(2),this.diskNumberStart=w.readInt(2),this.internalFileAttributes=w.readInt(2),this.externalFileAttributes=w.readInt(4),this.localHeaderOffset=w.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");w.skip(N),this.readExtraFields(w),this.parseZIP64ExtraField(w),this.fileComment=w.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var w=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),w==0&&(this.dosPermissions=63&this.externalFileAttributes),w==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var w=d(this.extraFields[1].value);this.uncompressedSize===h.MAX_VALUE_32BITS&&(this.uncompressedSize=w.readInt(8)),this.compressedSize===h.MAX_VALUE_32BITS&&(this.compressedSize=w.readInt(8)),this.localHeaderOffset===h.MAX_VALUE_32BITS&&(this.localHeaderOffset=w.readInt(8)),this.diskNumberStart===h.MAX_VALUE_32BITS&&(this.diskNumberStart=w.readInt(4))}},readExtraFields:function(w){var N,p,b,v=w.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});w.index+4<v;)N=w.readInt(2),p=w.readInt(2),b=w.readData(p),this.extraFields[N]={id:N,length:p,value:b};w.setIndex(v)},handleUTF8:function(){var w=_.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=g.utf8decode(this.fileName),this.fileCommentStr=g.utf8decode(this.fileComment);else{var N=this.findExtraFieldUnicodePath();if(N!==null)this.fileNameStr=N;else{var p=h.transformTo(w,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var v=h.transformTo(w,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(v)}}},findExtraFieldUnicodePath:function(){var w=this.extraFields[28789];if(w){var N=d(w.value);return N.readInt(1)!==1||x(this.fileName)!==N.readInt(4)?null:g.utf8decode(N.readData(w.length-5))}return null},findExtraFieldUnicodeComment:function(){var w=this.extraFields[25461];if(w){var N=d(w.value);return N.readInt(1)!==1||x(this.fileComment)!==N.readInt(4)?null:g.utf8decode(N.readData(w.length-5))}return null}},c.exports=A},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(r,c,f){function d(N,p,b){this.name=N,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=p,this._dataBinary=b.binary,this.options={compression:b.compression,compressionOptions:b.compressionOptions}}var h=r("./stream/StreamHelper"),m=r("./stream/DataWorker"),x=r("./utf8"),g=r("./compressedObject"),C=r("./stream/GenericWorker");d.prototype={internalStream:function(N){var p=null,b="string";try{if(!N)throw new Error("No output type specified.");var v=(b=N.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),p=this._decompressWorker();var j=!this._dataBinary;j&&!v&&(p=p.pipe(new x.Utf8EncodeWorker)),!j&&v&&(p=p.pipe(new x.Utf8DecodeWorker))}catch(k){(p=new C("error")).error(k)}return new h(p,b,"")},async:function(N,p){return this.internalStream(N).accumulate(p)},nodeStream:function(N,p){return this.internalStream(N||"nodebuffer").toNodejsStream(p)},_compressWorker:function(N,p){if(this._data instanceof g&&this._data.compression.magic===N.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new x.Utf8EncodeWorker)),g.createWorkerFrom(b,N,p)},_decompressWorker:function(){return this._data instanceof g?this._data.getContentWorker():this._data instanceof C?this._data:new m(this._data)}};for(var _=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],A=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},w=0;w<_.length;w++)d.prototype[_[w]]=A;c.exports=d},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(r,c,f){(function(d){var h,m,x=d.MutationObserver||d.WebKitMutationObserver;if(x){var g=0,C=new x(N),_=d.document.createTextNode("");C.observe(_,{characterData:!0}),h=function(){_.data=g=++g%2}}else if(d.setImmediate||d.MessageChannel===void 0)h="document"in d&&"onreadystatechange"in d.document.createElement("script")?function(){var p=d.document.createElement("script");p.onreadystatechange=function(){N(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},d.document.documentElement.appendChild(p)}:function(){setTimeout(N,0)};else{var A=new d.MessageChannel;A.port1.onmessage=N,h=function(){A.port2.postMessage(0)}}var w=[];function N(){var p,b;m=!0;for(var v=w.length;v;){for(b=w,w=[],p=-1;++p<v;)b[p]();v=w.length}m=!1}c.exports=function(p){w.push(p)!==1||m||h()}}).call(this,typeof qs<"u"?qs:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(r,c,f){var d=r("immediate");function h(){}var m={},x=["REJECTED"],g=["FULFILLED"],C=["PENDING"];function _(v){if(typeof v!="function")throw new TypeError("resolver must be a function");this.state=C,this.queue=[],this.outcome=void 0,v!==h&&p(this,v)}function A(v,j,k){this.promise=v,typeof j=="function"&&(this.onFulfilled=j,this.callFulfilled=this.otherCallFulfilled),typeof k=="function"&&(this.onRejected=k,this.callRejected=this.otherCallRejected)}function w(v,j,k){d(function(){var B;try{B=j(k)}catch(D){return m.reject(v,D)}B===v?m.reject(v,new TypeError("Cannot resolve promise with itself")):m.resolve(v,B)})}function N(v){var j=v&&v.then;if(v&&(typeof v=="object"||typeof v=="function")&&typeof j=="function")return function(){j.apply(v,arguments)}}function p(v,j){var k=!1;function B(O){k||(k=!0,m.reject(v,O))}function D(O){k||(k=!0,m.resolve(v,O))}var M=b(function(){j(D,B)});M.status==="error"&&B(M.value)}function b(v,j){var k={};try{k.value=v(j),k.status="success"}catch(B){k.status="error",k.value=B}return k}(c.exports=_).prototype.finally=function(v){if(typeof v!="function")return this;var j=this.constructor;return this.then(function(k){return j.resolve(v()).then(function(){return k})},function(k){return j.resolve(v()).then(function(){throw k})})},_.prototype.catch=function(v){return this.then(null,v)},_.prototype.then=function(v,j){if(typeof v!="function"&&this.state===g||typeof j!="function"&&this.state===x)return this;var k=new this.constructor(h);return this.state!==C?w(k,this.state===g?v:j,this.outcome):this.queue.push(new A(k,v,j)),k},A.prototype.callFulfilled=function(v){m.resolve(this.promise,v)},A.prototype.otherCallFulfilled=function(v){w(this.promise,this.onFulfilled,v)},A.prototype.callRejected=function(v){m.reject(this.promise,v)},A.prototype.otherCallRejected=function(v){w(this.promise,this.onRejected,v)},m.resolve=function(v,j){var k=b(N,j);if(k.status==="error")return m.reject(v,k.value);var B=k.value;if(B)p(v,B);else{v.state=g,v.outcome=j;for(var D=-1,M=v.queue.length;++D<M;)v.queue[D].callFulfilled(j)}return v},m.reject=function(v,j){v.state=x,v.outcome=j;for(var k=-1,B=v.queue.length;++k<B;)v.queue[k].callRejected(j);return v},_.resolve=function(v){return v instanceof this?v:m.resolve(new this(h),v)},_.reject=function(v){var j=new this(h);return m.reject(j,v)},_.all=function(v){var j=this;if(Object.prototype.toString.call(v)!=="[object Array]")return this.reject(new TypeError("must be an array"));var k=v.length,B=!1;if(!k)return this.resolve([]);for(var D=new Array(k),M=0,O=-1,X=new this(h);++O<k;)$(v[O],O);return X;function $(oe,ce){j.resolve(oe).then(function(q){D[ce]=q,++M!==k||B||(B=!0,m.resolve(X,D))},function(q){B||(B=!0,m.reject(X,q))})}},_.race=function(v){var j=this;if(Object.prototype.toString.call(v)!=="[object Array]")return this.reject(new TypeError("must be an array"));var k=v.length,B=!1;if(!k)return this.resolve([]);for(var D=-1,M=new this(h);++D<k;)O=v[D],j.resolve(O).then(function(X){B||(B=!0,m.resolve(M,X))},function(X){B||(B=!0,m.reject(M,X))});var O;return M}},{immediate:36}],38:[function(r,c,f){var d={};(0,r("./lib/utils/common").assign)(d,r("./lib/deflate"),r("./lib/inflate"),r("./lib/zlib/constants")),c.exports=d},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(r,c,f){var d=r("./zlib/deflate"),h=r("./utils/common"),m=r("./utils/strings"),x=r("./zlib/messages"),g=r("./zlib/zstream"),C=Object.prototype.toString,_=0,A=-1,w=0,N=8;function p(v){if(!(this instanceof p))return new p(v);this.options=h.assign({level:A,method:N,chunkSize:16384,windowBits:15,memLevel:8,strategy:w,to:""},v||{});var j=this.options;j.raw&&0<j.windowBits?j.windowBits=-j.windowBits:j.gzip&&0<j.windowBits&&j.windowBits<16&&(j.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new g,this.strm.avail_out=0;var k=d.deflateInit2(this.strm,j.level,j.method,j.windowBits,j.memLevel,j.strategy);if(k!==_)throw new Error(x[k]);if(j.header&&d.deflateSetHeader(this.strm,j.header),j.dictionary){var B;if(B=typeof j.dictionary=="string"?m.string2buf(j.dictionary):C.call(j.dictionary)==="[object ArrayBuffer]"?new Uint8Array(j.dictionary):j.dictionary,(k=d.deflateSetDictionary(this.strm,B))!==_)throw new Error(x[k]);this._dict_set=!0}}function b(v,j){var k=new p(j);if(k.push(v,!0),k.err)throw k.msg||x[k.err];return k.result}p.prototype.push=function(v,j){var k,B,D=this.strm,M=this.options.chunkSize;if(this.ended)return!1;B=j===~~j?j:j===!0?4:0,typeof v=="string"?D.input=m.string2buf(v):C.call(v)==="[object ArrayBuffer]"?D.input=new Uint8Array(v):D.input=v,D.next_in=0,D.avail_in=D.input.length;do{if(D.avail_out===0&&(D.output=new h.Buf8(M),D.next_out=0,D.avail_out=M),(k=d.deflate(D,B))!==1&&k!==_)return this.onEnd(k),!(this.ended=!0);D.avail_out!==0&&(D.avail_in!==0||B!==4&&B!==2)||(this.options.to==="string"?this.onData(m.buf2binstring(h.shrinkBuf(D.output,D.next_out))):this.onData(h.shrinkBuf(D.output,D.next_out)))}while((0<D.avail_in||D.avail_out===0)&&k!==1);return B===4?(k=d.deflateEnd(this.strm),this.onEnd(k),this.ended=!0,k===_):B!==2||(this.onEnd(_),!(D.avail_out=0))},p.prototype.onData=function(v){this.chunks.push(v)},p.prototype.onEnd=function(v){v===_&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=v,this.msg=this.strm.msg},f.Deflate=p,f.deflate=b,f.deflateRaw=function(v,j){return(j=j||{}).raw=!0,b(v,j)},f.gzip=function(v,j){return(j=j||{}).gzip=!0,b(v,j)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(r,c,f){var d=r("./zlib/inflate"),h=r("./utils/common"),m=r("./utils/strings"),x=r("./zlib/constants"),g=r("./zlib/messages"),C=r("./zlib/zstream"),_=r("./zlib/gzheader"),A=Object.prototype.toString;function w(p){if(!(this instanceof w))return new w(p);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},p||{});var b=this.options;b.raw&&0<=b.windowBits&&b.windowBits<16&&(b.windowBits=-b.windowBits,b.windowBits===0&&(b.windowBits=-15)),!(0<=b.windowBits&&b.windowBits<16)||p&&p.windowBits||(b.windowBits+=32),15<b.windowBits&&b.windowBits<48&&(15&b.windowBits)==0&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new C,this.strm.avail_out=0;var v=d.inflateInit2(this.strm,b.windowBits);if(v!==x.Z_OK)throw new Error(g[v]);this.header=new _,d.inflateGetHeader(this.strm,this.header)}function N(p,b){var v=new w(b);if(v.push(p,!0),v.err)throw v.msg||g[v.err];return v.result}w.prototype.push=function(p,b){var v,j,k,B,D,M,O=this.strm,X=this.options.chunkSize,$=this.options.dictionary,oe=!1;if(this.ended)return!1;j=b===~~b?b:b===!0?x.Z_FINISH:x.Z_NO_FLUSH,typeof p=="string"?O.input=m.binstring2buf(p):A.call(p)==="[object ArrayBuffer]"?O.input=new Uint8Array(p):O.input=p,O.next_in=0,O.avail_in=O.input.length;do{if(O.avail_out===0&&(O.output=new h.Buf8(X),O.next_out=0,O.avail_out=X),(v=d.inflate(O,x.Z_NO_FLUSH))===x.Z_NEED_DICT&&$&&(M=typeof $=="string"?m.string2buf($):A.call($)==="[object ArrayBuffer]"?new Uint8Array($):$,v=d.inflateSetDictionary(this.strm,M)),v===x.Z_BUF_ERROR&&oe===!0&&(v=x.Z_OK,oe=!1),v!==x.Z_STREAM_END&&v!==x.Z_OK)return this.onEnd(v),!(this.ended=!0);O.next_out&&(O.avail_out!==0&&v!==x.Z_STREAM_END&&(O.avail_in!==0||j!==x.Z_FINISH&&j!==x.Z_SYNC_FLUSH)||(this.options.to==="string"?(k=m.utf8border(O.output,O.next_out),B=O.next_out-k,D=m.buf2string(O.output,k),O.next_out=B,O.avail_out=X-B,B&&h.arraySet(O.output,O.output,k,B,0),this.onData(D)):this.onData(h.shrinkBuf(O.output,O.next_out)))),O.avail_in===0&&O.avail_out===0&&(oe=!0)}while((0<O.avail_in||O.avail_out===0)&&v!==x.Z_STREAM_END);return v===x.Z_STREAM_END&&(j=x.Z_FINISH),j===x.Z_FINISH?(v=d.inflateEnd(this.strm),this.onEnd(v),this.ended=!0,v===x.Z_OK):j!==x.Z_SYNC_FLUSH||(this.onEnd(x.Z_OK),!(O.avail_out=0))},w.prototype.onData=function(p){this.chunks.push(p)},w.prototype.onEnd=function(p){p===x.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},f.Inflate=w,f.inflate=N,f.inflateRaw=function(p,b){return(b=b||{}).raw=!0,N(p,b)},f.ungzip=N},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(r,c,f){var d=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";f.assign=function(x){for(var g=Array.prototype.slice.call(arguments,1);g.length;){var C=g.shift();if(C){if(typeof C!="object")throw new TypeError(C+"must be non-object");for(var _ in C)C.hasOwnProperty(_)&&(x[_]=C[_])}}return x},f.shrinkBuf=function(x,g){return x.length===g?x:x.subarray?x.subarray(0,g):(x.length=g,x)};var h={arraySet:function(x,g,C,_,A){if(g.subarray&&x.subarray)x.set(g.subarray(C,C+_),A);else for(var w=0;w<_;w++)x[A+w]=g[C+w]},flattenChunks:function(x){var g,C,_,A,w,N;for(g=_=0,C=x.length;g<C;g++)_+=x[g].length;for(N=new Uint8Array(_),g=A=0,C=x.length;g<C;g++)w=x[g],N.set(w,A),A+=w.length;return N}},m={arraySet:function(x,g,C,_,A){for(var w=0;w<_;w++)x[A+w]=g[C+w]},flattenChunks:function(x){return[].concat.apply([],x)}};f.setTyped=function(x){x?(f.Buf8=Uint8Array,f.Buf16=Uint16Array,f.Buf32=Int32Array,f.assign(f,h)):(f.Buf8=Array,f.Buf16=Array,f.Buf32=Array,f.assign(f,m))},f.setTyped(d)},{}],42:[function(r,c,f){var d=r("./common"),h=!0,m=!0;try{String.fromCharCode.apply(null,[0])}catch{h=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{m=!1}for(var x=new d.Buf8(256),g=0;g<256;g++)x[g]=252<=g?6:248<=g?5:240<=g?4:224<=g?3:192<=g?2:1;function C(_,A){if(A<65537&&(_.subarray&&m||!_.subarray&&h))return String.fromCharCode.apply(null,d.shrinkBuf(_,A));for(var w="",N=0;N<A;N++)w+=String.fromCharCode(_[N]);return w}x[254]=x[254]=1,f.string2buf=function(_){var A,w,N,p,b,v=_.length,j=0;for(p=0;p<v;p++)(64512&(w=_.charCodeAt(p)))==55296&&p+1<v&&(64512&(N=_.charCodeAt(p+1)))==56320&&(w=65536+(w-55296<<10)+(N-56320),p++),j+=w<128?1:w<2048?2:w<65536?3:4;for(A=new d.Buf8(j),p=b=0;b<j;p++)(64512&(w=_.charCodeAt(p)))==55296&&p+1<v&&(64512&(N=_.charCodeAt(p+1)))==56320&&(w=65536+(w-55296<<10)+(N-56320),p++),w<128?A[b++]=w:(w<2048?A[b++]=192|w>>>6:(w<65536?A[b++]=224|w>>>12:(A[b++]=240|w>>>18,A[b++]=128|w>>>12&63),A[b++]=128|w>>>6&63),A[b++]=128|63&w);return A},f.buf2binstring=function(_){return C(_,_.length)},f.binstring2buf=function(_){for(var A=new d.Buf8(_.length),w=0,N=A.length;w<N;w++)A[w]=_.charCodeAt(w);return A},f.buf2string=function(_,A){var w,N,p,b,v=A||_.length,j=new Array(2*v);for(w=N=0;w<v;)if((p=_[w++])<128)j[N++]=p;else if(4<(b=x[p]))j[N++]=65533,w+=b-1;else{for(p&=b===2?31:b===3?15:7;1<b&&w<v;)p=p<<6|63&_[w++],b--;1<b?j[N++]=65533:p<65536?j[N++]=p:(p-=65536,j[N++]=55296|p>>10&1023,j[N++]=56320|1023&p)}return C(j,N)},f.utf8border=function(_,A){var w;for((A=A||_.length)>_.length&&(A=_.length),w=A-1;0<=w&&(192&_[w])==128;)w--;return w<0||w===0?A:w+x[_[w]]>A?w:A}},{"./common":41}],43:[function(r,c,f){c.exports=function(d,h,m,x){for(var g=65535&d|0,C=d>>>16&65535|0,_=0;m!==0;){for(m-=_=2e3<m?2e3:m;C=C+(g=g+h[x++]|0)|0,--_;);g%=65521,C%=65521}return g|C<<16|0}},{}],44:[function(r,c,f){c.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(r,c,f){var d=(function(){for(var h,m=[],x=0;x<256;x++){h=x;for(var g=0;g<8;g++)h=1&h?3988292384^h>>>1:h>>>1;m[x]=h}return m})();c.exports=function(h,m,x,g){var C=d,_=g+x;h^=-1;for(var A=g;A<_;A++)h=h>>>8^C[255&(h^m[A])];return-1^h}},{}],46:[function(r,c,f){var d,h=r("../utils/common"),m=r("./trees"),x=r("./adler32"),g=r("./crc32"),C=r("./messages"),_=0,A=4,w=0,N=-2,p=-1,b=4,v=2,j=8,k=9,B=286,D=30,M=19,O=2*B+1,X=15,$=3,oe=258,ce=oe+$+1,q=42,P=113,E=1,ne=2,Q=3,Z=4;function we(S,pe){return S.msg=C[pe],pe}function F(S){return(S<<1)-(4<S?9:0)}function he(S){for(var pe=S.length;0<=--pe;)S[pe]=0}function z(S){var pe=S.state,le=pe.pending;le>S.avail_out&&(le=S.avail_out),le!==0&&(h.arraySet(S.output,pe.pending_buf,pe.pending_out,le,S.next_out),S.next_out+=le,pe.pending_out+=le,S.total_out+=le,S.avail_out-=le,pe.pending-=le,pe.pending===0&&(pe.pending_out=0))}function U(S,pe){m._tr_flush_block(S,0<=S.block_start?S.block_start:-1,S.strstart-S.block_start,pe),S.block_start=S.strstart,z(S.strm)}function te(S,pe){S.pending_buf[S.pending++]=pe}function ae(S,pe){S.pending_buf[S.pending++]=pe>>>8&255,S.pending_buf[S.pending++]=255&pe}function Y(S,pe){var le,V,L=S.max_chain_length,W=S.strstart,K=S.prev_length,I=S.nice_match,H=S.strstart>S.w_size-ce?S.strstart-(S.w_size-ce):0,de=S.window,be=S.w_mask,fe=S.prev,Ee=S.strstart+oe,De=de[W+K-1],Oe=de[W+K];S.prev_length>=S.good_match&&(L>>=2),I>S.lookahead&&(I=S.lookahead);do if(de[(le=pe)+K]===Oe&&de[le+K-1]===De&&de[le]===de[W]&&de[++le]===de[W+1]){W+=2,le++;do;while(de[++W]===de[++le]&&de[++W]===de[++le]&&de[++W]===de[++le]&&de[++W]===de[++le]&&de[++W]===de[++le]&&de[++W]===de[++le]&&de[++W]===de[++le]&&de[++W]===de[++le]&&W<Ee);if(V=oe-(Ee-W),W=Ee-oe,K<V){if(S.match_start=pe,I<=(K=V))break;De=de[W+K-1],Oe=de[W+K]}}while((pe=fe[pe&be])>H&&--L!=0);return K<=S.lookahead?K:S.lookahead}function me(S){var pe,le,V,L,W,K,I,H,de,be,fe=S.w_size;do{if(L=S.window_size-S.lookahead-S.strstart,S.strstart>=fe+(fe-ce)){for(h.arraySet(S.window,S.window,fe,fe,0),S.match_start-=fe,S.strstart-=fe,S.block_start-=fe,pe=le=S.hash_size;V=S.head[--pe],S.head[pe]=fe<=V?V-fe:0,--le;);for(pe=le=fe;V=S.prev[--pe],S.prev[pe]=fe<=V?V-fe:0,--le;);L+=fe}if(S.strm.avail_in===0)break;if(K=S.strm,I=S.window,H=S.strstart+S.lookahead,de=L,be=void 0,be=K.avail_in,de<be&&(be=de),le=be===0?0:(K.avail_in-=be,h.arraySet(I,K.input,K.next_in,be,H),K.state.wrap===1?K.adler=x(K.adler,I,be,H):K.state.wrap===2&&(K.adler=g(K.adler,I,be,H)),K.next_in+=be,K.total_in+=be,be),S.lookahead+=le,S.lookahead+S.insert>=$)for(W=S.strstart-S.insert,S.ins_h=S.window[W],S.ins_h=(S.ins_h<<S.hash_shift^S.window[W+1])&S.hash_mask;S.insert&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[W+$-1])&S.hash_mask,S.prev[W&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=W,W++,S.insert--,!(S.lookahead+S.insert<$)););}while(S.lookahead<ce&&S.strm.avail_in!==0)}function Ne(S,pe){for(var le,V;;){if(S.lookahead<ce){if(me(S),S.lookahead<ce&&pe===_)return E;if(S.lookahead===0)break}if(le=0,S.lookahead>=$&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,le=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart),le!==0&&S.strstart-le<=S.w_size-ce&&(S.match_length=Y(S,le)),S.match_length>=$)if(V=m._tr_tally(S,S.strstart-S.match_start,S.match_length-$),S.lookahead-=S.match_length,S.match_length<=S.max_lazy_match&&S.lookahead>=$){for(S.match_length--;S.strstart++,S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,le=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart,--S.match_length!=0;);S.strstart++}else S.strstart+=S.match_length,S.match_length=0,S.ins_h=S.window[S.strstart],S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+1])&S.hash_mask;else V=m._tr_tally(S,0,S.window[S.strstart]),S.lookahead--,S.strstart++;if(V&&(U(S,!1),S.strm.avail_out===0))return E}return S.insert=S.strstart<$-1?S.strstart:$-1,pe===A?(U(S,!0),S.strm.avail_out===0?Q:Z):S.last_lit&&(U(S,!1),S.strm.avail_out===0)?E:ne}function ke(S,pe){for(var le,V,L;;){if(S.lookahead<ce){if(me(S),S.lookahead<ce&&pe===_)return E;if(S.lookahead===0)break}if(le=0,S.lookahead>=$&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,le=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart),S.prev_length=S.match_length,S.prev_match=S.match_start,S.match_length=$-1,le!==0&&S.prev_length<S.max_lazy_match&&S.strstart-le<=S.w_size-ce&&(S.match_length=Y(S,le),S.match_length<=5&&(S.strategy===1||S.match_length===$&&4096<S.strstart-S.match_start)&&(S.match_length=$-1)),S.prev_length>=$&&S.match_length<=S.prev_length){for(L=S.strstart+S.lookahead-$,V=m._tr_tally(S,S.strstart-1-S.prev_match,S.prev_length-$),S.lookahead-=S.prev_length-1,S.prev_length-=2;++S.strstart<=L&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,le=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart),--S.prev_length!=0;);if(S.match_available=0,S.match_length=$-1,S.strstart++,V&&(U(S,!1),S.strm.avail_out===0))return E}else if(S.match_available){if((V=m._tr_tally(S,0,S.window[S.strstart-1]))&&U(S,!1),S.strstart++,S.lookahead--,S.strm.avail_out===0)return E}else S.match_available=1,S.strstart++,S.lookahead--}return S.match_available&&(V=m._tr_tally(S,0,S.window[S.strstart-1]),S.match_available=0),S.insert=S.strstart<$-1?S.strstart:$-1,pe===A?(U(S,!0),S.strm.avail_out===0?Q:Z):S.last_lit&&(U(S,!1),S.strm.avail_out===0)?E:ne}function Ae(S,pe,le,V,L){this.good_length=S,this.max_lazy=pe,this.nice_length=le,this.max_chain=V,this.func=L}function Ue(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=j,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new h.Buf16(2*O),this.dyn_dtree=new h.Buf16(2*(2*D+1)),this.bl_tree=new h.Buf16(2*(2*M+1)),he(this.dyn_ltree),he(this.dyn_dtree),he(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new h.Buf16(X+1),this.heap=new h.Buf16(2*B+1),he(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new h.Buf16(2*B+1),he(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Ie(S){var pe;return S&&S.state?(S.total_in=S.total_out=0,S.data_type=v,(pe=S.state).pending=0,pe.pending_out=0,pe.wrap<0&&(pe.wrap=-pe.wrap),pe.status=pe.wrap?q:P,S.adler=pe.wrap===2?0:1,pe.last_flush=_,m._tr_init(pe),w):we(S,N)}function He(S){var pe=Ie(S);return pe===w&&(function(le){le.window_size=2*le.w_size,he(le.head),le.max_lazy_match=d[le.level].max_lazy,le.good_match=d[le.level].good_length,le.nice_match=d[le.level].nice_length,le.max_chain_length=d[le.level].max_chain,le.strstart=0,le.block_start=0,le.lookahead=0,le.insert=0,le.match_length=le.prev_length=$-1,le.match_available=0,le.ins_h=0})(S.state),pe}function ct(S,pe,le,V,L,W){if(!S)return N;var K=1;if(pe===p&&(pe=6),V<0?(K=0,V=-V):15<V&&(K=2,V-=16),L<1||k<L||le!==j||V<8||15<V||pe<0||9<pe||W<0||b<W)return we(S,N);V===8&&(V=9);var I=new Ue;return(S.state=I).strm=S,I.wrap=K,I.gzhead=null,I.w_bits=V,I.w_size=1<<I.w_bits,I.w_mask=I.w_size-1,I.hash_bits=L+7,I.hash_size=1<<I.hash_bits,I.hash_mask=I.hash_size-1,I.hash_shift=~~((I.hash_bits+$-1)/$),I.window=new h.Buf8(2*I.w_size),I.head=new h.Buf16(I.hash_size),I.prev=new h.Buf16(I.w_size),I.lit_bufsize=1<<L+6,I.pending_buf_size=4*I.lit_bufsize,I.pending_buf=new h.Buf8(I.pending_buf_size),I.d_buf=1*I.lit_bufsize,I.l_buf=3*I.lit_bufsize,I.level=pe,I.strategy=W,I.method=le,He(S)}d=[new Ae(0,0,0,0,function(S,pe){var le=65535;for(le>S.pending_buf_size-5&&(le=S.pending_buf_size-5);;){if(S.lookahead<=1){if(me(S),S.lookahead===0&&pe===_)return E;if(S.lookahead===0)break}S.strstart+=S.lookahead,S.lookahead=0;var V=S.block_start+le;if((S.strstart===0||S.strstart>=V)&&(S.lookahead=S.strstart-V,S.strstart=V,U(S,!1),S.strm.avail_out===0)||S.strstart-S.block_start>=S.w_size-ce&&(U(S,!1),S.strm.avail_out===0))return E}return S.insert=0,pe===A?(U(S,!0),S.strm.avail_out===0?Q:Z):(S.strstart>S.block_start&&(U(S,!1),S.strm.avail_out),E)}),new Ae(4,4,8,4,Ne),new Ae(4,5,16,8,Ne),new Ae(4,6,32,32,Ne),new Ae(4,4,16,16,ke),new Ae(8,16,32,32,ke),new Ae(8,16,128,128,ke),new Ae(8,32,128,256,ke),new Ae(32,128,258,1024,ke),new Ae(32,258,258,4096,ke)],f.deflateInit=function(S,pe){return ct(S,pe,j,15,8,0)},f.deflateInit2=ct,f.deflateReset=He,f.deflateResetKeep=Ie,f.deflateSetHeader=function(S,pe){return S&&S.state?S.state.wrap!==2?N:(S.state.gzhead=pe,w):N},f.deflate=function(S,pe){var le,V,L,W;if(!S||!S.state||5<pe||pe<0)return S?we(S,N):N;if(V=S.state,!S.output||!S.input&&S.avail_in!==0||V.status===666&&pe!==A)return we(S,S.avail_out===0?-5:N);if(V.strm=S,le=V.last_flush,V.last_flush=pe,V.status===q)if(V.wrap===2)S.adler=0,te(V,31),te(V,139),te(V,8),V.gzhead?(te(V,(V.gzhead.text?1:0)+(V.gzhead.hcrc?2:0)+(V.gzhead.extra?4:0)+(V.gzhead.name?8:0)+(V.gzhead.comment?16:0)),te(V,255&V.gzhead.time),te(V,V.gzhead.time>>8&255),te(V,V.gzhead.time>>16&255),te(V,V.gzhead.time>>24&255),te(V,V.level===9?2:2<=V.strategy||V.level<2?4:0),te(V,255&V.gzhead.os),V.gzhead.extra&&V.gzhead.extra.length&&(te(V,255&V.gzhead.extra.length),te(V,V.gzhead.extra.length>>8&255)),V.gzhead.hcrc&&(S.adler=g(S.adler,V.pending_buf,V.pending,0)),V.gzindex=0,V.status=69):(te(V,0),te(V,0),te(V,0),te(V,0),te(V,0),te(V,V.level===9?2:2<=V.strategy||V.level<2?4:0),te(V,3),V.status=P);else{var K=j+(V.w_bits-8<<4)<<8;K|=(2<=V.strategy||V.level<2?0:V.level<6?1:V.level===6?2:3)<<6,V.strstart!==0&&(K|=32),K+=31-K%31,V.status=P,ae(V,K),V.strstart!==0&&(ae(V,S.adler>>>16),ae(V,65535&S.adler)),S.adler=1}if(V.status===69)if(V.gzhead.extra){for(L=V.pending;V.gzindex<(65535&V.gzhead.extra.length)&&(V.pending!==V.pending_buf_size||(V.gzhead.hcrc&&V.pending>L&&(S.adler=g(S.adler,V.pending_buf,V.pending-L,L)),z(S),L=V.pending,V.pending!==V.pending_buf_size));)te(V,255&V.gzhead.extra[V.gzindex]),V.gzindex++;V.gzhead.hcrc&&V.pending>L&&(S.adler=g(S.adler,V.pending_buf,V.pending-L,L)),V.gzindex===V.gzhead.extra.length&&(V.gzindex=0,V.status=73)}else V.status=73;if(V.status===73)if(V.gzhead.name){L=V.pending;do{if(V.pending===V.pending_buf_size&&(V.gzhead.hcrc&&V.pending>L&&(S.adler=g(S.adler,V.pending_buf,V.pending-L,L)),z(S),L=V.pending,V.pending===V.pending_buf_size)){W=1;break}W=V.gzindex<V.gzhead.name.length?255&V.gzhead.name.charCodeAt(V.gzindex++):0,te(V,W)}while(W!==0);V.gzhead.hcrc&&V.pending>L&&(S.adler=g(S.adler,V.pending_buf,V.pending-L,L)),W===0&&(V.gzindex=0,V.status=91)}else V.status=91;if(V.status===91)if(V.gzhead.comment){L=V.pending;do{if(V.pending===V.pending_buf_size&&(V.gzhead.hcrc&&V.pending>L&&(S.adler=g(S.adler,V.pending_buf,V.pending-L,L)),z(S),L=V.pending,V.pending===V.pending_buf_size)){W=1;break}W=V.gzindex<V.gzhead.comment.length?255&V.gzhead.comment.charCodeAt(V.gzindex++):0,te(V,W)}while(W!==0);V.gzhead.hcrc&&V.pending>L&&(S.adler=g(S.adler,V.pending_buf,V.pending-L,L)),W===0&&(V.status=103)}else V.status=103;if(V.status===103&&(V.gzhead.hcrc?(V.pending+2>V.pending_buf_size&&z(S),V.pending+2<=V.pending_buf_size&&(te(V,255&S.adler),te(V,S.adler>>8&255),S.adler=0,V.status=P)):V.status=P),V.pending!==0){if(z(S),S.avail_out===0)return V.last_flush=-1,w}else if(S.avail_in===0&&F(pe)<=F(le)&&pe!==A)return we(S,-5);if(V.status===666&&S.avail_in!==0)return we(S,-5);if(S.avail_in!==0||V.lookahead!==0||pe!==_&&V.status!==666){var I=V.strategy===2?(function(H,de){for(var be;;){if(H.lookahead===0&&(me(H),H.lookahead===0)){if(de===_)return E;break}if(H.match_length=0,be=m._tr_tally(H,0,H.window[H.strstart]),H.lookahead--,H.strstart++,be&&(U(H,!1),H.strm.avail_out===0))return E}return H.insert=0,de===A?(U(H,!0),H.strm.avail_out===0?Q:Z):H.last_lit&&(U(H,!1),H.strm.avail_out===0)?E:ne})(V,pe):V.strategy===3?(function(H,de){for(var be,fe,Ee,De,Oe=H.window;;){if(H.lookahead<=oe){if(me(H),H.lookahead<=oe&&de===_)return E;if(H.lookahead===0)break}if(H.match_length=0,H.lookahead>=$&&0<H.strstart&&(fe=Oe[Ee=H.strstart-1])===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]){De=H.strstart+oe;do;while(fe===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]&&fe===Oe[++Ee]&&Ee<De);H.match_length=oe-(De-Ee),H.match_length>H.lookahead&&(H.match_length=H.lookahead)}if(H.match_length>=$?(be=m._tr_tally(H,1,H.match_length-$),H.lookahead-=H.match_length,H.strstart+=H.match_length,H.match_length=0):(be=m._tr_tally(H,0,H.window[H.strstart]),H.lookahead--,H.strstart++),be&&(U(H,!1),H.strm.avail_out===0))return E}return H.insert=0,de===A?(U(H,!0),H.strm.avail_out===0?Q:Z):H.last_lit&&(U(H,!1),H.strm.avail_out===0)?E:ne})(V,pe):d[V.level].func(V,pe);if(I!==Q&&I!==Z||(V.status=666),I===E||I===Q)return S.avail_out===0&&(V.last_flush=-1),w;if(I===ne&&(pe===1?m._tr_align(V):pe!==5&&(m._tr_stored_block(V,0,0,!1),pe===3&&(he(V.head),V.lookahead===0&&(V.strstart=0,V.block_start=0,V.insert=0))),z(S),S.avail_out===0))return V.last_flush=-1,w}return pe!==A?w:V.wrap<=0?1:(V.wrap===2?(te(V,255&S.adler),te(V,S.adler>>8&255),te(V,S.adler>>16&255),te(V,S.adler>>24&255),te(V,255&S.total_in),te(V,S.total_in>>8&255),te(V,S.total_in>>16&255),te(V,S.total_in>>24&255)):(ae(V,S.adler>>>16),ae(V,65535&S.adler)),z(S),0<V.wrap&&(V.wrap=-V.wrap),V.pending!==0?w:1)},f.deflateEnd=function(S){var pe;return S&&S.state?(pe=S.state.status)!==q&&pe!==69&&pe!==73&&pe!==91&&pe!==103&&pe!==P&&pe!==666?we(S,N):(S.state=null,pe===P?we(S,-3):w):N},f.deflateSetDictionary=function(S,pe){var le,V,L,W,K,I,H,de,be=pe.length;if(!S||!S.state||(W=(le=S.state).wrap)===2||W===1&&le.status!==q||le.lookahead)return N;for(W===1&&(S.adler=x(S.adler,pe,be,0)),le.wrap=0,be>=le.w_size&&(W===0&&(he(le.head),le.strstart=0,le.block_start=0,le.insert=0),de=new h.Buf8(le.w_size),h.arraySet(de,pe,be-le.w_size,le.w_size,0),pe=de,be=le.w_size),K=S.avail_in,I=S.next_in,H=S.input,S.avail_in=be,S.next_in=0,S.input=pe,me(le);le.lookahead>=$;){for(V=le.strstart,L=le.lookahead-($-1);le.ins_h=(le.ins_h<<le.hash_shift^le.window[V+$-1])&le.hash_mask,le.prev[V&le.w_mask]=le.head[le.ins_h],le.head[le.ins_h]=V,V++,--L;);le.strstart=V,le.lookahead=$-1,me(le)}return le.strstart+=le.lookahead,le.block_start=le.strstart,le.insert=le.lookahead,le.lookahead=0,le.match_length=le.prev_length=$-1,le.match_available=0,S.next_in=I,S.input=H,S.avail_in=K,le.wrap=W,w},f.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(r,c,f){c.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(r,c,f){c.exports=function(d,h){var m,x,g,C,_,A,w,N,p,b,v,j,k,B,D,M,O,X,$,oe,ce,q,P,E,ne;m=d.state,x=d.next_in,E=d.input,g=x+(d.avail_in-5),C=d.next_out,ne=d.output,_=C-(h-d.avail_out),A=C+(d.avail_out-257),w=m.dmax,N=m.wsize,p=m.whave,b=m.wnext,v=m.window,j=m.hold,k=m.bits,B=m.lencode,D=m.distcode,M=(1<<m.lenbits)-1,O=(1<<m.distbits)-1;e:do{k<15&&(j+=E[x++]<<k,k+=8,j+=E[x++]<<k,k+=8),X=B[j&M];t:for(;;){if(j>>>=$=X>>>24,k-=$,($=X>>>16&255)===0)ne[C++]=65535&X;else{if(!(16&$)){if((64&$)==0){X=B[(65535&X)+(j&(1<<$)-1)];continue t}if(32&$){m.mode=12;break e}d.msg="invalid literal/length code",m.mode=30;break e}oe=65535&X,($&=15)&&(k<$&&(j+=E[x++]<<k,k+=8),oe+=j&(1<<$)-1,j>>>=$,k-=$),k<15&&(j+=E[x++]<<k,k+=8,j+=E[x++]<<k,k+=8),X=D[j&O];a:for(;;){if(j>>>=$=X>>>24,k-=$,!(16&($=X>>>16&255))){if((64&$)==0){X=D[(65535&X)+(j&(1<<$)-1)];continue a}d.msg="invalid distance code",m.mode=30;break e}if(ce=65535&X,k<($&=15)&&(j+=E[x++]<<k,(k+=8)<$&&(j+=E[x++]<<k,k+=8)),w<(ce+=j&(1<<$)-1)){d.msg="invalid distance too far back",m.mode=30;break e}if(j>>>=$,k-=$,($=C-_)<ce){if(p<($=ce-$)&&m.sane){d.msg="invalid distance too far back",m.mode=30;break e}if(P=v,(q=0)===b){if(q+=N-$,$<oe){for(oe-=$;ne[C++]=v[q++],--$;);q=C-ce,P=ne}}else if(b<$){if(q+=N+b-$,($-=b)<oe){for(oe-=$;ne[C++]=v[q++],--$;);if(q=0,b<oe){for(oe-=$=b;ne[C++]=v[q++],--$;);q=C-ce,P=ne}}}else if(q+=b-$,$<oe){for(oe-=$;ne[C++]=v[q++],--$;);q=C-ce,P=ne}for(;2<oe;)ne[C++]=P[q++],ne[C++]=P[q++],ne[C++]=P[q++],oe-=3;oe&&(ne[C++]=P[q++],1<oe&&(ne[C++]=P[q++]))}else{for(q=C-ce;ne[C++]=ne[q++],ne[C++]=ne[q++],ne[C++]=ne[q++],2<(oe-=3););oe&&(ne[C++]=ne[q++],1<oe&&(ne[C++]=ne[q++]))}break}}break}}while(x<g&&C<A);x-=oe=k>>3,j&=(1<<(k-=oe<<3))-1,d.next_in=x,d.next_out=C,d.avail_in=x<g?g-x+5:5-(x-g),d.avail_out=C<A?A-C+257:257-(C-A),m.hold=j,m.bits=k}},{}],49:[function(r,c,f){var d=r("../utils/common"),h=r("./adler32"),m=r("./crc32"),x=r("./inffast"),g=r("./inftrees"),C=1,_=2,A=0,w=-2,N=1,p=852,b=592;function v(q){return(q>>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)}function j(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new d.Buf16(320),this.work=new d.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function k(q){var P;return q&&q.state?(P=q.state,q.total_in=q.total_out=P.total=0,q.msg="",P.wrap&&(q.adler=1&P.wrap),P.mode=N,P.last=0,P.havedict=0,P.dmax=32768,P.head=null,P.hold=0,P.bits=0,P.lencode=P.lendyn=new d.Buf32(p),P.distcode=P.distdyn=new d.Buf32(b),P.sane=1,P.back=-1,A):w}function B(q){var P;return q&&q.state?((P=q.state).wsize=0,P.whave=0,P.wnext=0,k(q)):w}function D(q,P){var E,ne;return q&&q.state?(ne=q.state,P<0?(E=0,P=-P):(E=1+(P>>4),P<48&&(P&=15)),P&&(P<8||15<P)?w:(ne.window!==null&&ne.wbits!==P&&(ne.window=null),ne.wrap=E,ne.wbits=P,B(q))):w}function M(q,P){var E,ne;return q?(ne=new j,(q.state=ne).window=null,(E=D(q,P))!==A&&(q.state=null),E):w}var O,X,$=!0;function oe(q){if($){var P;for(O=new d.Buf32(512),X=new d.Buf32(32),P=0;P<144;)q.lens[P++]=8;for(;P<256;)q.lens[P++]=9;for(;P<280;)q.lens[P++]=7;for(;P<288;)q.lens[P++]=8;for(g(C,q.lens,0,288,O,0,q.work,{bits:9}),P=0;P<32;)q.lens[P++]=5;g(_,q.lens,0,32,X,0,q.work,{bits:5}),$=!1}q.lencode=O,q.lenbits=9,q.distcode=X,q.distbits=5}function ce(q,P,E,ne){var Q,Z=q.state;return Z.window===null&&(Z.wsize=1<<Z.wbits,Z.wnext=0,Z.whave=0,Z.window=new d.Buf8(Z.wsize)),ne>=Z.wsize?(d.arraySet(Z.window,P,E-Z.wsize,Z.wsize,0),Z.wnext=0,Z.whave=Z.wsize):(ne<(Q=Z.wsize-Z.wnext)&&(Q=ne),d.arraySet(Z.window,P,E-ne,Q,Z.wnext),(ne-=Q)?(d.arraySet(Z.window,P,E-ne,ne,0),Z.wnext=ne,Z.whave=Z.wsize):(Z.wnext+=Q,Z.wnext===Z.wsize&&(Z.wnext=0),Z.whave<Z.wsize&&(Z.whave+=Q))),0}f.inflateReset=B,f.inflateReset2=D,f.inflateResetKeep=k,f.inflateInit=function(q){return M(q,15)},f.inflateInit2=M,f.inflate=function(q,P){var E,ne,Q,Z,we,F,he,z,U,te,ae,Y,me,Ne,ke,Ae,Ue,Ie,He,ct,S,pe,le,V,L=0,W=new d.Buf8(4),K=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!q||!q.state||!q.output||!q.input&&q.avail_in!==0)return w;(E=q.state).mode===12&&(E.mode=13),we=q.next_out,Q=q.output,he=q.avail_out,Z=q.next_in,ne=q.input,F=q.avail_in,z=E.hold,U=E.bits,te=F,ae=he,pe=A;e:for(;;)switch(E.mode){case N:if(E.wrap===0){E.mode=13;break}for(;U<16;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(2&E.wrap&&z===35615){W[E.check=0]=255&z,W[1]=z>>>8&255,E.check=m(E.check,W,2,0),U=z=0,E.mode=2;break}if(E.flags=0,E.head&&(E.head.done=!1),!(1&E.wrap)||(((255&z)<<8)+(z>>8))%31){q.msg="incorrect header check",E.mode=30;break}if((15&z)!=8){q.msg="unknown compression method",E.mode=30;break}if(U-=4,S=8+(15&(z>>>=4)),E.wbits===0)E.wbits=S;else if(S>E.wbits){q.msg="invalid window size",E.mode=30;break}E.dmax=1<<S,q.adler=E.check=1,E.mode=512&z?10:12,U=z=0;break;case 2:for(;U<16;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(E.flags=z,(255&E.flags)!=8){q.msg="unknown compression method",E.mode=30;break}if(57344&E.flags){q.msg="unknown header flags set",E.mode=30;break}E.head&&(E.head.text=z>>8&1),512&E.flags&&(W[0]=255&z,W[1]=z>>>8&255,E.check=m(E.check,W,2,0)),U=z=0,E.mode=3;case 3:for(;U<32;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}E.head&&(E.head.time=z),512&E.flags&&(W[0]=255&z,W[1]=z>>>8&255,W[2]=z>>>16&255,W[3]=z>>>24&255,E.check=m(E.check,W,4,0)),U=z=0,E.mode=4;case 4:for(;U<16;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}E.head&&(E.head.xflags=255&z,E.head.os=z>>8),512&E.flags&&(W[0]=255&z,W[1]=z>>>8&255,E.check=m(E.check,W,2,0)),U=z=0,E.mode=5;case 5:if(1024&E.flags){for(;U<16;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}E.length=z,E.head&&(E.head.extra_len=z),512&E.flags&&(W[0]=255&z,W[1]=z>>>8&255,E.check=m(E.check,W,2,0)),U=z=0}else E.head&&(E.head.extra=null);E.mode=6;case 6:if(1024&E.flags&&(F<(Y=E.length)&&(Y=F),Y&&(E.head&&(S=E.head.extra_len-E.length,E.head.extra||(E.head.extra=new Array(E.head.extra_len)),d.arraySet(E.head.extra,ne,Z,Y,S)),512&E.flags&&(E.check=m(E.check,ne,Y,Z)),F-=Y,Z+=Y,E.length-=Y),E.length))break e;E.length=0,E.mode=7;case 7:if(2048&E.flags){if(F===0)break e;for(Y=0;S=ne[Z+Y++],E.head&&S&&E.length<65536&&(E.head.name+=String.fromCharCode(S)),S&&Y<F;);if(512&E.flags&&(E.check=m(E.check,ne,Y,Z)),F-=Y,Z+=Y,S)break e}else E.head&&(E.head.name=null);E.length=0,E.mode=8;case 8:if(4096&E.flags){if(F===0)break e;for(Y=0;S=ne[Z+Y++],E.head&&S&&E.length<65536&&(E.head.comment+=String.fromCharCode(S)),S&&Y<F;);if(512&E.flags&&(E.check=m(E.check,ne,Y,Z)),F-=Y,Z+=Y,S)break e}else E.head&&(E.head.comment=null);E.mode=9;case 9:if(512&E.flags){for(;U<16;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(z!==(65535&E.check)){q.msg="header crc mismatch",E.mode=30;break}U=z=0}E.head&&(E.head.hcrc=E.flags>>9&1,E.head.done=!0),q.adler=E.check=0,E.mode=12;break;case 10:for(;U<32;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}q.adler=E.check=v(z),U=z=0,E.mode=11;case 11:if(E.havedict===0)return q.next_out=we,q.avail_out=he,q.next_in=Z,q.avail_in=F,E.hold=z,E.bits=U,2;q.adler=E.check=1,E.mode=12;case 12:if(P===5||P===6)break e;case 13:if(E.last){z>>>=7&U,U-=7&U,E.mode=27;break}for(;U<3;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}switch(E.last=1&z,U-=1,3&(z>>>=1)){case 0:E.mode=14;break;case 1:if(oe(E),E.mode=20,P!==6)break;z>>>=2,U-=2;break e;case 2:E.mode=17;break;case 3:q.msg="invalid block type",E.mode=30}z>>>=2,U-=2;break;case 14:for(z>>>=7&U,U-=7&U;U<32;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if((65535&z)!=(z>>>16^65535)){q.msg="invalid stored block lengths",E.mode=30;break}if(E.length=65535&z,U=z=0,E.mode=15,P===6)break e;case 15:E.mode=16;case 16:if(Y=E.length){if(F<Y&&(Y=F),he<Y&&(Y=he),Y===0)break e;d.arraySet(Q,ne,Z,Y,we),F-=Y,Z+=Y,he-=Y,we+=Y,E.length-=Y;break}E.mode=12;break;case 17:for(;U<14;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(E.nlen=257+(31&z),z>>>=5,U-=5,E.ndist=1+(31&z),z>>>=5,U-=5,E.ncode=4+(15&z),z>>>=4,U-=4,286<E.nlen||30<E.ndist){q.msg="too many length or distance symbols",E.mode=30;break}E.have=0,E.mode=18;case 18:for(;E.have<E.ncode;){for(;U<3;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}E.lens[K[E.have++]]=7&z,z>>>=3,U-=3}for(;E.have<19;)E.lens[K[E.have++]]=0;if(E.lencode=E.lendyn,E.lenbits=7,le={bits:E.lenbits},pe=g(0,E.lens,0,19,E.lencode,0,E.work,le),E.lenbits=le.bits,pe){q.msg="invalid code lengths set",E.mode=30;break}E.have=0,E.mode=19;case 19:for(;E.have<E.nlen+E.ndist;){for(;Ae=(L=E.lencode[z&(1<<E.lenbits)-1])>>>16&255,Ue=65535&L,!((ke=L>>>24)<=U);){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(Ue<16)z>>>=ke,U-=ke,E.lens[E.have++]=Ue;else{if(Ue===16){for(V=ke+2;U<V;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(z>>>=ke,U-=ke,E.have===0){q.msg="invalid bit length repeat",E.mode=30;break}S=E.lens[E.have-1],Y=3+(3&z),z>>>=2,U-=2}else if(Ue===17){for(V=ke+3;U<V;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}U-=ke,S=0,Y=3+(7&(z>>>=ke)),z>>>=3,U-=3}else{for(V=ke+7;U<V;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}U-=ke,S=0,Y=11+(127&(z>>>=ke)),z>>>=7,U-=7}if(E.have+Y>E.nlen+E.ndist){q.msg="invalid bit length repeat",E.mode=30;break}for(;Y--;)E.lens[E.have++]=S}}if(E.mode===30)break;if(E.lens[256]===0){q.msg="invalid code -- missing end-of-block",E.mode=30;break}if(E.lenbits=9,le={bits:E.lenbits},pe=g(C,E.lens,0,E.nlen,E.lencode,0,E.work,le),E.lenbits=le.bits,pe){q.msg="invalid literal/lengths set",E.mode=30;break}if(E.distbits=6,E.distcode=E.distdyn,le={bits:E.distbits},pe=g(_,E.lens,E.nlen,E.ndist,E.distcode,0,E.work,le),E.distbits=le.bits,pe){q.msg="invalid distances set",E.mode=30;break}if(E.mode=20,P===6)break e;case 20:E.mode=21;case 21:if(6<=F&&258<=he){q.next_out=we,q.avail_out=he,q.next_in=Z,q.avail_in=F,E.hold=z,E.bits=U,x(q,ae),we=q.next_out,Q=q.output,he=q.avail_out,Z=q.next_in,ne=q.input,F=q.avail_in,z=E.hold,U=E.bits,E.mode===12&&(E.back=-1);break}for(E.back=0;Ae=(L=E.lencode[z&(1<<E.lenbits)-1])>>>16&255,Ue=65535&L,!((ke=L>>>24)<=U);){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(Ae&&(240&Ae)==0){for(Ie=ke,He=Ae,ct=Ue;Ae=(L=E.lencode[ct+((z&(1<<Ie+He)-1)>>Ie)])>>>16&255,Ue=65535&L,!(Ie+(ke=L>>>24)<=U);){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}z>>>=Ie,U-=Ie,E.back+=Ie}if(z>>>=ke,U-=ke,E.back+=ke,E.length=Ue,Ae===0){E.mode=26;break}if(32&Ae){E.back=-1,E.mode=12;break}if(64&Ae){q.msg="invalid literal/length code",E.mode=30;break}E.extra=15&Ae,E.mode=22;case 22:if(E.extra){for(V=E.extra;U<V;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}E.length+=z&(1<<E.extra)-1,z>>>=E.extra,U-=E.extra,E.back+=E.extra}E.was=E.length,E.mode=23;case 23:for(;Ae=(L=E.distcode[z&(1<<E.distbits)-1])>>>16&255,Ue=65535&L,!((ke=L>>>24)<=U);){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if((240&Ae)==0){for(Ie=ke,He=Ae,ct=Ue;Ae=(L=E.distcode[ct+((z&(1<<Ie+He)-1)>>Ie)])>>>16&255,Ue=65535&L,!(Ie+(ke=L>>>24)<=U);){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}z>>>=Ie,U-=Ie,E.back+=Ie}if(z>>>=ke,U-=ke,E.back+=ke,64&Ae){q.msg="invalid distance code",E.mode=30;break}E.offset=Ue,E.extra=15&Ae,E.mode=24;case 24:if(E.extra){for(V=E.extra;U<V;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}E.offset+=z&(1<<E.extra)-1,z>>>=E.extra,U-=E.extra,E.back+=E.extra}if(E.offset>E.dmax){q.msg="invalid distance too far back",E.mode=30;break}E.mode=25;case 25:if(he===0)break e;if(Y=ae-he,E.offset>Y){if((Y=E.offset-Y)>E.whave&&E.sane){q.msg="invalid distance too far back",E.mode=30;break}me=Y>E.wnext?(Y-=E.wnext,E.wsize-Y):E.wnext-Y,Y>E.length&&(Y=E.length),Ne=E.window}else Ne=Q,me=we-E.offset,Y=E.length;for(he<Y&&(Y=he),he-=Y,E.length-=Y;Q[we++]=Ne[me++],--Y;);E.length===0&&(E.mode=21);break;case 26:if(he===0)break e;Q[we++]=E.length,he--,E.mode=21;break;case 27:if(E.wrap){for(;U<32;){if(F===0)break e;F--,z|=ne[Z++]<<U,U+=8}if(ae-=he,q.total_out+=ae,E.total+=ae,ae&&(q.adler=E.check=E.flags?m(E.check,Q,ae,we-ae):h(E.check,Q,ae,we-ae)),ae=he,(E.flags?z:v(z))!==E.check){q.msg="incorrect data check",E.mode=30;break}U=z=0}E.mode=28;case 28:if(E.wrap&&E.flags){for(;U<32;){if(F===0)break e;F--,z+=ne[Z++]<<U,U+=8}if(z!==(4294967295&E.total)){q.msg="incorrect length check",E.mode=30;break}U=z=0}E.mode=29;case 29:pe=1;break e;case 30:pe=-3;break e;case 31:return-4;default:return w}return q.next_out=we,q.avail_out=he,q.next_in=Z,q.avail_in=F,E.hold=z,E.bits=U,(E.wsize||ae!==q.avail_out&&E.mode<30&&(E.mode<27||P!==4))&&ce(q,q.output,q.next_out,ae-q.avail_out)?(E.mode=31,-4):(te-=q.avail_in,ae-=q.avail_out,q.total_in+=te,q.total_out+=ae,E.total+=ae,E.wrap&&ae&&(q.adler=E.check=E.flags?m(E.check,Q,ae,q.next_out-ae):h(E.check,Q,ae,q.next_out-ae)),q.data_type=E.bits+(E.last?64:0)+(E.mode===12?128:0)+(E.mode===20||E.mode===15?256:0),(te==0&&ae===0||P===4)&&pe===A&&(pe=-5),pe)},f.inflateEnd=function(q){if(!q||!q.state)return w;var P=q.state;return P.window&&(P.window=null),q.state=null,A},f.inflateGetHeader=function(q,P){var E;return q&&q.state?(2&(E=q.state).wrap)==0?w:((E.head=P).done=!1,A):w},f.inflateSetDictionary=function(q,P){var E,ne=P.length;return q&&q.state?(E=q.state).wrap!==0&&E.mode!==11?w:E.mode===11&&h(1,P,ne,0)!==E.check?-3:ce(q,P,ne,ne)?(E.mode=31,-4):(E.havedict=1,A):w},f.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(r,c,f){var d=r("../utils/common"),h=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],m=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],x=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],g=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];c.exports=function(C,_,A,w,N,p,b,v){var j,k,B,D,M,O,X,$,oe,ce=v.bits,q=0,P=0,E=0,ne=0,Q=0,Z=0,we=0,F=0,he=0,z=0,U=null,te=0,ae=new d.Buf16(16),Y=new d.Buf16(16),me=null,Ne=0;for(q=0;q<=15;q++)ae[q]=0;for(P=0;P<w;P++)ae[_[A+P]]++;for(Q=ce,ne=15;1<=ne&&ae[ne]===0;ne--);if(ne<Q&&(Q=ne),ne===0)return N[p++]=20971520,N[p++]=20971520,v.bits=1,0;for(E=1;E<ne&&ae[E]===0;E++);for(Q<E&&(Q=E),q=F=1;q<=15;q++)if(F<<=1,(F-=ae[q])<0)return-1;if(0<F&&(C===0||ne!==1))return-1;for(Y[1]=0,q=1;q<15;q++)Y[q+1]=Y[q]+ae[q];for(P=0;P<w;P++)_[A+P]!==0&&(b[Y[_[A+P]]++]=P);if(O=C===0?(U=me=b,19):C===1?(U=h,te-=257,me=m,Ne-=257,256):(U=x,me=g,-1),q=E,M=p,we=P=z=0,B=-1,D=(he=1<<(Z=Q))-1,C===1&&852<he||C===2&&592<he)return 1;for(;;){for(X=q-we,oe=b[P]<O?($=0,b[P]):b[P]>O?($=me[Ne+b[P]],U[te+b[P]]):($=96,0),j=1<<q-we,E=k=1<<Z;N[M+(z>>we)+(k-=j)]=X<<24|$<<16|oe|0,k!==0;);for(j=1<<q-1;z&j;)j>>=1;if(j!==0?(z&=j-1,z+=j):z=0,P++,--ae[q]==0){if(q===ne)break;q=_[A+b[P]]}if(Q<q&&(z&D)!==B){for(we===0&&(we=Q),M+=E,F=1<<(Z=q-we);Z+we<ne&&!((F-=ae[Z+we])<=0);)Z++,F<<=1;if(he+=1<<Z,C===1&&852<he||C===2&&592<he)return 1;N[B=z&D]=Q<<24|Z<<16|M-p|0}}return z!==0&&(N[M+z]=q-we<<24|64<<16|0),v.bits=Q,0}},{"../utils/common":41}],51:[function(r,c,f){c.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(r,c,f){var d=r("../utils/common"),h=0,m=1;function x(L){for(var W=L.length;0<=--W;)L[W]=0}var g=0,C=29,_=256,A=_+1+C,w=30,N=19,p=2*A+1,b=15,v=16,j=7,k=256,B=16,D=17,M=18,O=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],X=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],$=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],oe=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ce=new Array(2*(A+2));x(ce);var q=new Array(2*w);x(q);var P=new Array(512);x(P);var E=new Array(256);x(E);var ne=new Array(C);x(ne);var Q,Z,we,F=new Array(w);function he(L,W,K,I,H){this.static_tree=L,this.extra_bits=W,this.extra_base=K,this.elems=I,this.max_length=H,this.has_stree=L&&L.length}function z(L,W){this.dyn_tree=L,this.max_code=0,this.stat_desc=W}function U(L){return L<256?P[L]:P[256+(L>>>7)]}function te(L,W){L.pending_buf[L.pending++]=255&W,L.pending_buf[L.pending++]=W>>>8&255}function ae(L,W,K){L.bi_valid>v-K?(L.bi_buf|=W<<L.bi_valid&65535,te(L,L.bi_buf),L.bi_buf=W>>v-L.bi_valid,L.bi_valid+=K-v):(L.bi_buf|=W<<L.bi_valid&65535,L.bi_valid+=K)}function Y(L,W,K){ae(L,K[2*W],K[2*W+1])}function me(L,W){for(var K=0;K|=1&L,L>>>=1,K<<=1,0<--W;);return K>>>1}function Ne(L,W,K){var I,H,de=new Array(b+1),be=0;for(I=1;I<=b;I++)de[I]=be=be+K[I-1]<<1;for(H=0;H<=W;H++){var fe=L[2*H+1];fe!==0&&(L[2*H]=me(de[fe]++,fe))}}function ke(L){var W;for(W=0;W<A;W++)L.dyn_ltree[2*W]=0;for(W=0;W<w;W++)L.dyn_dtree[2*W]=0;for(W=0;W<N;W++)L.bl_tree[2*W]=0;L.dyn_ltree[2*k]=1,L.opt_len=L.static_len=0,L.last_lit=L.matches=0}function Ae(L){8<L.bi_valid?te(L,L.bi_buf):0<L.bi_valid&&(L.pending_buf[L.pending++]=L.bi_buf),L.bi_buf=0,L.bi_valid=0}function Ue(L,W,K,I){var H=2*W,de=2*K;return L[H]<L[de]||L[H]===L[de]&&I[W]<=I[K]}function Ie(L,W,K){for(var I=L.heap[K],H=K<<1;H<=L.heap_len&&(H<L.heap_len&&Ue(W,L.heap[H+1],L.heap[H],L.depth)&&H++,!Ue(W,I,L.heap[H],L.depth));)L.heap[K]=L.heap[H],K=H,H<<=1;L.heap[K]=I}function He(L,W,K){var I,H,de,be,fe=0;if(L.last_lit!==0)for(;I=L.pending_buf[L.d_buf+2*fe]<<8|L.pending_buf[L.d_buf+2*fe+1],H=L.pending_buf[L.l_buf+fe],fe++,I===0?Y(L,H,W):(Y(L,(de=E[H])+_+1,W),(be=O[de])!==0&&ae(L,H-=ne[de],be),Y(L,de=U(--I),K),(be=X[de])!==0&&ae(L,I-=F[de],be)),fe<L.last_lit;);Y(L,k,W)}function ct(L,W){var K,I,H,de=W.dyn_tree,be=W.stat_desc.static_tree,fe=W.stat_desc.has_stree,Ee=W.stat_desc.elems,De=-1;for(L.heap_len=0,L.heap_max=p,K=0;K<Ee;K++)de[2*K]!==0?(L.heap[++L.heap_len]=De=K,L.depth[K]=0):de[2*K+1]=0;for(;L.heap_len<2;)de[2*(H=L.heap[++L.heap_len]=De<2?++De:0)]=1,L.depth[H]=0,L.opt_len--,fe&&(L.static_len-=be[2*H+1]);for(W.max_code=De,K=L.heap_len>>1;1<=K;K--)Ie(L,de,K);for(H=Ee;K=L.heap[1],L.heap[1]=L.heap[L.heap_len--],Ie(L,de,1),I=L.heap[1],L.heap[--L.heap_max]=K,L.heap[--L.heap_max]=I,de[2*H]=de[2*K]+de[2*I],L.depth[H]=(L.depth[K]>=L.depth[I]?L.depth[K]:L.depth[I])+1,de[2*K+1]=de[2*I+1]=H,L.heap[1]=H++,Ie(L,de,1),2<=L.heap_len;);L.heap[--L.heap_max]=L.heap[1],(function(Oe,it){var Yt,St,da,Pe,gt,Tt,st=it.dyn_tree,Mn=it.max_code,Sl=it.stat_desc.static_tree,jl=it.stat_desc.has_stree,Va=it.stat_desc.extra_bits,va=it.stat_desc.extra_base,Qt=it.stat_desc.max_length,Dt=0;for(Pe=0;Pe<=b;Pe++)Oe.bl_count[Pe]=0;for(st[2*Oe.heap[Oe.heap_max]+1]=0,Yt=Oe.heap_max+1;Yt<p;Yt++)Qt<(Pe=st[2*st[2*(St=Oe.heap[Yt])+1]+1]+1)&&(Pe=Qt,Dt++),st[2*St+1]=Pe,Mn<St||(Oe.bl_count[Pe]++,gt=0,va<=St&&(gt=Va[St-va]),Tt=st[2*St],Oe.opt_len+=Tt*(Pe+gt),jl&&(Oe.static_len+=Tt*(Sl[2*St+1]+gt)));if(Dt!==0){do{for(Pe=Qt-1;Oe.bl_count[Pe]===0;)Pe--;Oe.bl_count[Pe]--,Oe.bl_count[Pe+1]+=2,Oe.bl_count[Qt]--,Dt-=2}while(0<Dt);for(Pe=Qt;Pe!==0;Pe--)for(St=Oe.bl_count[Pe];St!==0;)Mn<(da=Oe.heap[--Yt])||(st[2*da+1]!==Pe&&(Oe.opt_len+=(Pe-st[2*da+1])*st[2*da],st[2*da+1]=Pe),St--)}})(L,W),Ne(de,De,L.bl_count)}function S(L,W,K){var I,H,de=-1,be=W[1],fe=0,Ee=7,De=4;for(be===0&&(Ee=138,De=3),W[2*(K+1)+1]=65535,I=0;I<=K;I++)H=be,be=W[2*(I+1)+1],++fe<Ee&&H===be||(fe<De?L.bl_tree[2*H]+=fe:H!==0?(H!==de&&L.bl_tree[2*H]++,L.bl_tree[2*B]++):fe<=10?L.bl_tree[2*D]++:L.bl_tree[2*M]++,de=H,De=(fe=0)===be?(Ee=138,3):H===be?(Ee=6,3):(Ee=7,4))}function pe(L,W,K){var I,H,de=-1,be=W[1],fe=0,Ee=7,De=4;for(be===0&&(Ee=138,De=3),I=0;I<=K;I++)if(H=be,be=W[2*(I+1)+1],!(++fe<Ee&&H===be)){if(fe<De)for(;Y(L,H,L.bl_tree),--fe!=0;);else H!==0?(H!==de&&(Y(L,H,L.bl_tree),fe--),Y(L,B,L.bl_tree),ae(L,fe-3,2)):fe<=10?(Y(L,D,L.bl_tree),ae(L,fe-3,3)):(Y(L,M,L.bl_tree),ae(L,fe-11,7));de=H,De=(fe=0)===be?(Ee=138,3):H===be?(Ee=6,3):(Ee=7,4)}}x(F);var le=!1;function V(L,W,K,I){ae(L,(g<<1)+(I?1:0),3),(function(H,de,be,fe){Ae(H),te(H,be),te(H,~be),d.arraySet(H.pending_buf,H.window,de,be,H.pending),H.pending+=be})(L,W,K)}f._tr_init=function(L){le||((function(){var W,K,I,H,de,be=new Array(b+1);for(H=I=0;H<C-1;H++)for(ne[H]=I,W=0;W<1<<O[H];W++)E[I++]=H;for(E[I-1]=H,H=de=0;H<16;H++)for(F[H]=de,W=0;W<1<<X[H];W++)P[de++]=H;for(de>>=7;H<w;H++)for(F[H]=de<<7,W=0;W<1<<X[H]-7;W++)P[256+de++]=H;for(K=0;K<=b;K++)be[K]=0;for(W=0;W<=143;)ce[2*W+1]=8,W++,be[8]++;for(;W<=255;)ce[2*W+1]=9,W++,be[9]++;for(;W<=279;)ce[2*W+1]=7,W++,be[7]++;for(;W<=287;)ce[2*W+1]=8,W++,be[8]++;for(Ne(ce,A+1,be),W=0;W<w;W++)q[2*W+1]=5,q[2*W]=me(W,5);Q=new he(ce,O,_+1,A,b),Z=new he(q,X,0,w,b),we=new he(new Array(0),$,0,N,j)})(),le=!0),L.l_desc=new z(L.dyn_ltree,Q),L.d_desc=new z(L.dyn_dtree,Z),L.bl_desc=new z(L.bl_tree,we),L.bi_buf=0,L.bi_valid=0,ke(L)},f._tr_stored_block=V,f._tr_flush_block=function(L,W,K,I){var H,de,be=0;0<L.level?(L.strm.data_type===2&&(L.strm.data_type=(function(fe){var Ee,De=4093624447;for(Ee=0;Ee<=31;Ee++,De>>>=1)if(1&De&&fe.dyn_ltree[2*Ee]!==0)return h;if(fe.dyn_ltree[18]!==0||fe.dyn_ltree[20]!==0||fe.dyn_ltree[26]!==0)return m;for(Ee=32;Ee<_;Ee++)if(fe.dyn_ltree[2*Ee]!==0)return m;return h})(L)),ct(L,L.l_desc),ct(L,L.d_desc),be=(function(fe){var Ee;for(S(fe,fe.dyn_ltree,fe.l_desc.max_code),S(fe,fe.dyn_dtree,fe.d_desc.max_code),ct(fe,fe.bl_desc),Ee=N-1;3<=Ee&&fe.bl_tree[2*oe[Ee]+1]===0;Ee--);return fe.opt_len+=3*(Ee+1)+5+5+4,Ee})(L),H=L.opt_len+3+7>>>3,(de=L.static_len+3+7>>>3)<=H&&(H=de)):H=de=K+5,K+4<=H&&W!==-1?V(L,W,K,I):L.strategy===4||de===H?(ae(L,2+(I?1:0),3),He(L,ce,q)):(ae(L,4+(I?1:0),3),(function(fe,Ee,De,Oe){var it;for(ae(fe,Ee-257,5),ae(fe,De-1,5),ae(fe,Oe-4,4),it=0;it<Oe;it++)ae(fe,fe.bl_tree[2*oe[it]+1],3);pe(fe,fe.dyn_ltree,Ee-1),pe(fe,fe.dyn_dtree,De-1)})(L,L.l_desc.max_code+1,L.d_desc.max_code+1,be+1),He(L,L.dyn_ltree,L.dyn_dtree)),ke(L),I&&Ae(L)},f._tr_tally=function(L,W,K){return L.pending_buf[L.d_buf+2*L.last_lit]=W>>>8&255,L.pending_buf[L.d_buf+2*L.last_lit+1]=255&W,L.pending_buf[L.l_buf+L.last_lit]=255&K,L.last_lit++,W===0?L.dyn_ltree[2*K]++:(L.matches++,W--,L.dyn_ltree[2*(E[K]+_+1)]++,L.dyn_dtree[2*U(W)]++),L.last_lit===L.lit_bufsize-1},f._tr_align=function(L){ae(L,2,3),Y(L,k,ce),(function(W){W.bi_valid===16?(te(W,W.bi_buf),W.bi_buf=0,W.bi_valid=0):8<=W.bi_valid&&(W.pending_buf[W.pending++]=255&W.bi_buf,W.bi_buf>>=8,W.bi_valid-=8)})(L)}},{"../utils/common":41}],53:[function(r,c,f){c.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(r,c,f){(function(d){(function(h,m){if(!h.setImmediate){var x,g,C,_,A=1,w={},N=!1,p=h.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(h);b=b&&b.setTimeout?b:h,x={}.toString.call(h.process)==="[object process]"?function(B){process.nextTick(function(){j(B)})}:(function(){if(h.postMessage&&!h.importScripts){var B=!0,D=h.onmessage;return h.onmessage=function(){B=!1},h.postMessage("","*"),h.onmessage=D,B}})()?(_="setImmediate$"+Math.random()+"$",h.addEventListener?h.addEventListener("message",k,!1):h.attachEvent("onmessage",k),function(B){h.postMessage(_+B,"*")}):h.MessageChannel?((C=new MessageChannel).port1.onmessage=function(B){j(B.data)},function(B){C.port2.postMessage(B)}):p&&"onreadystatechange"in p.createElement("script")?(g=p.documentElement,function(B){var D=p.createElement("script");D.onreadystatechange=function(){j(B),D.onreadystatechange=null,g.removeChild(D),D=null},g.appendChild(D)}):function(B){setTimeout(j,0,B)},b.setImmediate=function(B){typeof B!="function"&&(B=new Function(""+B));for(var D=new Array(arguments.length-1),M=0;M<D.length;M++)D[M]=arguments[M+1];var O={callback:B,args:D};return w[A]=O,x(A),A++},b.clearImmediate=v}function v(B){delete w[B]}function j(B){if(N)setTimeout(j,0,B);else{var D=w[B];if(D){N=!0;try{(function(M){var O=M.callback,X=M.args;switch(X.length){case 0:O();break;case 1:O(X[0]);break;case 2:O(X[0],X[1]);break;case 3:O(X[0],X[1],X[2]);break;default:O.apply(m,X)}})(D)}finally{v(B),N=!1}}}}function k(B){B.source===h&&typeof B.data=="string"&&B.data.indexOf(_)===0&&j(+B.data.slice(_.length))}})(typeof self>"u"?d===void 0?this:d:self)}).call(this,typeof qs<"u"?qs:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Ec)),Ec.exports}var kb=Eb();const Ab=Hc(kb),zb=i=>{switch(i.split(".").pop()?.toLowerCase()||""){case"pdf":return"picture_as_pdf";case"csv":case"xls":case"xlsx":return"table_view";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"image";case"txt":case"md":return"description";case"json":return"data_object";case"zip":case"tar":case"gz":return"folder_zip";default:return"insert_drive_file"}},Gs=6e4,kc=200,rp=200,vi=1e6,Ac=2e3,zc=2e3,Rb=360,Vp=12,Ks=Rb+Vp,Ob=4,Tb=4,Db=({index:i,style:u,data:r})=>{const c=r[i];return c?l.jsx("div",{style:{...u,paddingBottom:Vp},children:l.jsx(Yp,{capture:c})}):null},Mb=i=>`${(i/(1024*1024)).toFixed(2)} MB`,Ub=i=>{if(typeof i=="boolean")return i;if(typeof i=="string"){const u=i.trim().toLowerCase();if(u==="true")return!0;if(u==="false")return!1}return null},Is=(i,u)=>i.length<=u?{text:i,truncated:!1}:{text:i.slice(0,u),truncated:!0},Bb=i=>!i||i.data===void 0||i.data===null?{reason:"No data to copy."}:{raw:i.data},Zs=(i,u,r)=>i.length<=u?i:(r.push(`first ${u.toLocaleString()} chars`),i.slice(0,u)),Lb=i=>{const u=[];if(typeof i=="string")return{text:Zs(i,vi,u),truncated:u.length>0,reason:u.join(", ")};if(Array.isArray(i)){let c=i;i.length>Ac&&(c=i.slice(0,Ac),u.push(`first ${Ac.toLocaleString()} items`));let f="";try{f=JSON.stringify(c,null,2)}catch{f=String(c)}return f=Zs(f,vi,u),{text:f,truncated:u.length>0,reason:u.join(", ")}}if(i&&typeof i=="object"){let c=i;const f=Object.keys(i);f.length>zc&&(c=f.slice(0,zc).reduce((h,m)=>(h[m]=i[m],h),{}),u.push(`first ${zc.toLocaleString()} keys`));let d="";try{d=JSON.stringify(c,null,2)}catch{d=String(c)}return d=Zs(d,vi,u),{text:d,truncated:u.length>0,reason:u.join(", ")}}return{text:Zs(String(i),vi,u),truncated:u.length>0,reason:u.join(", ")}},Hb=i=>{if(typeof i=="string")return i;try{return JSON.stringify(i,null,2)}catch{return String(i)}},op=i=>{if(!i||i.data===void 0||i.data===null||i.data==="")return{text:"",truncated:!1,language:"plain"};const u=i.data;if(typeof u=="string"){const c=u.trim(),f=c.startsWith("<")&&c.includes(">")?"html":c.startsWith("{")||c.startsWith("[")?"json":"plain",d=Is(u,Gs);return{text:d.text,truncated:d.truncated,language:f}}if(Array.isArray(u)){const c=u.length>kc?u.slice(0,kc):u,f=JSON.stringify(c,null,2),d=Is(f,Gs);return{text:d.text,truncated:d.truncated||u.length>kc,language:"json"}}if(u&&typeof u=="object"){const c=Object.keys(u);let f=u,d=!1;c.length>rp&&(d=!0,f=c.slice(0,rp).reduce((x,g)=>(x[g]=u[g],x),{}));const h=JSON.stringify(f,null,2),m=Is(h,Gs);return{text:m.text,truncated:m.truncated||d,language:"json"}}const r=Is(String(u),Gs);return{text:r.text,truncated:r.truncated,language:"plain"}},qb=i=>{const u=[];let r=[],c="",f=!1;for(let d=0;d<i.length;d+=1){const h=i[d];f?h==='"'?i[d+1]==='"'?(c+='"',d+=1):f=!1:c+=h:h==='"'?f=!0:h===","?(r.push(c),c=""):h===`
|
|
13
13
|
`?(r.push(c),u.push(r),r=[],c=""):h==="\r"||(c+=h)}return r.push(c),(r.length>1||r[0]!==""||u.length>0)&&u.push(r),u},Yb=i=>{if(!i)return null;if(typeof i=="string"){const u=i.trim();if(!u.includes(",")||!u.includes(`
|
|
14
|
-
`))return null;const r=qb(u).filter(d=>d.some(h=>String(h||"").trim()!==""));if(r.length<2)return null;const c=r[0].map((d,h)=>String(d||"").trim()||`column_${h+1}`),f=r.slice(1);return c.length<2?null:{headers:c,rows:f}}if(Array.isArray(i)){if(i.length===0)return null;if(i.every(u=>u&&typeof u=="object"&&!Array.isArray(u))){const u=[];if(i.forEach(c=>{Object.keys(c).forEach(f=>{u.includes(f)||u.push(f)})}),u.length===0)return null;const r=i.map(c=>u.map(f=>c[f]??""));return{headers:u,rows:r}}if(i.every(u=>Array.isArray(u))){const u=Math.max(...i.map(c=>c.length));return{headers:Array.from({length:u},(c,f)=>`column_${f+1}`),rows:i}}return null}if(i&&typeof i=="object"){const u=Object.keys(i);return u.length===0?null:{headers:u,rows:[u.map(r=>i[r]??"")]}}return null},Vb=(i,u)=>i==null?null:typeof i=="string"?u?{content:i,mime:"text/csv",ext:"csv"}:{content:i,mime:"application/json",ext:"json"}:{content:JSON.stringify(i,null,2),mime:"application/json",ext:"json"},Gb=(i,u,r)=>{const c=new Blob([u],{type:r}),f=URL.createObjectURL(c),d=document.createElement("a");d.href=f,d.download=i,document.body.appendChild(d),d.click(),d.remove(),URL.revokeObjectURL(f)},Kb=({results:i,pinnedResults:u,isExecuting:r,isHeadful:c,runId:f,onConfirm:d,onNotify:h,onPin:m,onUnpin:x,fullWidth:g,useNovnc:C})=>{const[_,A]=R.useState(null),[w,N]=R.useState("raw"),[p,b]=R.useState("data"),[v,j]=R.useState(()=>u&&!i?"pinned":"latest"),k=R.useMemo(()=>C===null?"checking":C?"novnc":"native",[C]),[B,D]=R.useState(!1),[M,O]=R.useState(!1),[X,$]=R.useState([]),oe=R.useRef(null),ce=v==="pinned"&&u?u:i,q=R.useMemo(()=>Yb(ce?.data),[ce?.data]),P=R.useMemo(()=>ce&&ce.data!==void 0&&ce.data!==null&&ce.data!==""?op(ce):null,[ce]),E=R.useMemo(()=>ce?.screenshotUrl?`${ce.screenshotUrl}${v==="latest"?`?t=${Date.now()}`:""}`:null,[ce?.screenshotUrl,v]),ne=F=>{const he=Ub(F);return he!==null?he?l.jsx(_e,{name:"check",className:"text-xs text-blue-400"}):"":F??""},Q=async()=>{O(!0);try{const F=f?`?runId=${encodeURIComponent(f)}`:"",he=await fetch(`/api/data/captures${F}`),z=he.ok?await he.json():{captures:[]};$(Array.isArray(z.captures)?z.captures:[])}catch{$([])}finally{O(!1)}};R.useEffect(()=>{N(q?"table":"raw"),!ce?.downloads||ce.downloads.length===0?b("data"):ce?.data||b("downloads")},[ce]),R.useEffect(()=>{if(i){j("latest");return}u&&j("pinned")},[i,u]),R.useEffect(()=>{!u&&v==="pinned"&&j("latest")},[u,v]);const Z=async(F,he,z)=>{if(!F){h("Nothing to copy.","error");return}let U=F;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(U);else{const te=document.createElement("textarea");te.value=U,te.style.position="fixed",te.style.left="-999999px",te.style.top="-999999px",document.body.appendChild(te),te.focus(),te.select(),document.execCommand("copy"),te.remove()}A(he),setTimeout(()=>A(null),2e3),z?.truncatedNotice?h("Copied truncated data.","success"):U.length!==F.length&&h("Copied a truncated preview.","success")}catch(te){console.error("Copy failed:",te),h("Copy failed.","error")}};if(c&&v==="latest"){const{origin:F,hostname:he}=window.location,z=`${F}/novnc.html?host=${he}&path=websockify`,U=()=>{const te=oe.current;if(te){if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}te.requestFullscreen?.().catch(()=>{})}};return k==="native"?l.jsxs("div",{className:"glass-card rounded-[32px] overflow-hidden h-[80vh] w-full relative flex flex-col items-center justify-center p-8 text-center gap-4",children:[l.jsx("div",{className:"text-[12px] font-bold uppercase tracking-widest text-white",children:"Headful Session Active"}),l.jsx("div",{className:"text-[10px] font-bold uppercase tracking-widest text-amber-500/80 max-w-lg leading-relaxed",children:"Figranium is not optimized for native browser windows. Please install the proper tools for stability (Xvfb, x11vnc, websockify) or simply use the Docker version."})]}):k==="checking"?l.jsx("div",{className:"glass-card rounded-[32px] overflow-hidden h-[80vh] w-full relative flex items-center justify-center",children:l.jsx("div",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Checking headful viewer..."})}):l.jsxs("div",{ref:oe,className:"glass-card rounded-[32px] overflow-hidden h-[80vh] w-full relative",children:[l.jsx("button",{type:"button",onClick:U,className:"absolute top-4 right-4 z-10 px-3 py-2 rounded-xl border border-white/20 bg-black/40 text-[9px] font-bold uppercase tracking-widest text-white/80 hover:bg-black/60 transition-all",title:"Toggle fullscreen",children:"Fullscreen"}),l.jsx("iframe",{src:z,className:"absolute inset-0 w-full h-full",title:"Headful Browser"})]})}if(!ce&&!(r&&v==="latest"))return l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center space-y-4 opacity-20",children:[l.jsx("div",{className:"w-16 h-16 border border-white/10 rounded-full flex items-center justify-center",children:l.jsx(_e,{name:"terminal",className:"text-2xl text-white"})}),l.jsx("p",{className:"text-[9px] font-bold uppercase tracking-[0.3em]",children:"Ready"})]});const we=g?"space-y-12 relative z-10 w-full":"space-y-12 relative z-10 max-w-5xl mx-auto";return l.jsxs("div",{className:we,children:[l.jsxs("div",{className:"flex items-end justify-between border-b border-white/5 pb-10",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.3em]",children:"Preview"}),l.jsx("h2",{className:"text-xl font-mono text-white truncate max-w-xl tracking-tight italic",children:ce?.finalUrl||ce?.url||""})]}),l.jsx("div",{className:`px-4 py-2 rounded-xl text-[9px] font-bold uppercase tracking-[0.2em] ${v==="pinned"?"bg-amber-500/10 text-amber-300":r?"bg-blue-500/10 text-blue-400 animate-pulse":"bg-green-500/10 text-green-400"}`,children:v==="pinned"?"Pinned":r?"Running":"Finished"})]}),l.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[l.jsxs("div",{className:"glass-card rounded-[32px] overflow-hidden flex flex-col min-h-[400px]",children:[l.jsxs("div",{className:"p-6 border-b border-white/5 flex items-center justify-between text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:[l.jsx("span",{children:"Screenshot"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-white/20",children:ce?.timestamp||"--:--:--"}),l.jsx("button",{type:"button",onClick:()=>{D(!0),Q()},className:"px-3 py-2 rounded-xl border border-white/10 text-[8px] font-bold uppercase tracking-widest text-white/70 hover:text-white hover:bg-white/5 transition-all",children:"View All Captures"})]})]}),l.jsx("div",{className:"relative bg-black flex-1 flex items-center justify-center overflow-hidden",children:E?l.jsx("img",{src:E,className:"absolute inset-0 w-full h-full object-contain transition-opacity duration-1000"}):l.jsx("div",{className:"text-[8px] font-bold text-white/5 uppercase tracking-widest",children:"Waiting for Frame..."})})]}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8 flex flex-col h-[400px]",children:[l.jsx("span",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest mb-6 border-b border-white/5 pb-4",children:"Activity Log"}),l.jsxs("div",{className:"flex-1 font-mono text-[10px] text-gray-400 space-y-2 overflow-y-auto custom-scrollbar pr-2",children:[ce?.logs?.map((F,he)=>l.jsxs("div",{className:"flex gap-2",children:[l.jsx("span",{className:"text-white/10 shrink-0",children:"›"})," ",l.jsx("span",{children:F})]},he)),r&&v==="latest"&&(!ce?.logs||ce?.logs.length===0)&&l.jsx("div",{className:"animate-pulse",children:"Connecting to kernel..."})]})]})]}),B&&l.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-6",children:l.jsxs("div",{className:"glass-card rounded-[32px] w-full max-w-5xl max-h-[85vh] overflow-hidden flex flex-col",children:[l.jsxs("div",{className:"p-6 border-b border-white/10 flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-widest",children:"Captures"}),l.jsx("div",{className:"text-sm font-bold text-white",children:"Recordings and Screenshots"})]}),l.jsx("button",{onClick:()=>D(!1),className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all bg-white/5 border-white/10 text-white hover:bg-white/10",children:"Close"})]}),l.jsxs("div",{className:"p-6 overflow-y-auto custom-scrollbar",children:[M&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading captures..."}),!M&&X.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No captures found."}),!M&&X.length>0&&l.jsx(nr,{height:Math.min(Math.max(Ks,X.length*Ks),Ks*Ob),width:"100%",itemCount:X.length,itemSize:Ks,overscanCount:Tb,itemData:X,className:"custom-scrollbar",children:Db})]})]})}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8 flex flex-col relative",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-white/5 pb-4 mb-6",children:[l.jsx("span",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:p==="downloads"?"Downloads":"Data"}),l.jsxs("div",{className:"flex items-center gap-2",children:[ce?.downloads&&ce.downloads.length>0&&l.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 border border-white/10",children:["data","downloads"].map(F=>l.jsx("button",{onClick:()=>b(F),className:`px-3 py-1 rounded text-[8px] font-bold uppercase tracking-widest transition-all ${p===F?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:F},F))}),u&&l.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 border border-white/10",children:["latest","pinned"].map(F=>l.jsx("button",{onClick:()=>j(F),className:`px-3 py-1 rounded text-[8px] font-bold uppercase tracking-widest transition-all ${v===F?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:F},F))}),q&&p==="data"&&l.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 border border-white/10",children:["table","raw"].map(F=>l.jsx("button",{onClick:()=>N(F),className:`px-3 py-1 rounded text-[8px] font-bold uppercase tracking-widest transition-all ${w===F?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:F},F))}),v==="pinned"?l.jsx("button",{onClick:()=>{x?.(),j("latest")},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-amber-200 hover:bg-white/10",title:"Unpin data",children:"Unpin"}):l.jsx("button",{onClick:()=>{if(!ce){h("No data to pin.","error");return}m?.(ce),j("pinned")},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-white hover:bg-white/10",title:"Pin data",children:u?"Update Pin":"Pin"}),p==="data"&&l.jsx("button",{onClick:()=>{const F=Vb(ce?.data,q);if(!F){h("No data to export.","error");return}const he=`doppelganger-data-${new Date().toISOString().replace(/[:.]/g,"-")}.${F.ext}`;Gb(he,F.content,F.mime),h(`Exported ${F.ext.toUpperCase()}.`,"success")},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-white hover:bg-white/10",title:"Export extracted data",children:"Export"}),p==="downloads"&&l.jsxs("button",{onClick:async()=>{if(!(!ce?.downloads||ce.downloads.length===0)){if(ce.downloads.length===1){const F=ce.downloads[0],he=document.createElement("a");he.href=F.path,he.download=F.name,document.body.appendChild(he),he.click(),he.remove(),h(`Downloading ${F.name}`,"success");return}h("Generating ZIP...","success");try{const F=new Ab;for(const te of ce.downloads){const Y=await(await fetch(te.path)).blob();F.file(te.name,Y)}const he=await F.generateAsync({type:"blob"}),z=URL.createObjectURL(he),U=document.createElement("a");U.href=z,U.download=`doppelganger-downloads-${new Date().toISOString().replace(/[:.]/g,"-")}.zip`,document.body.appendChild(U),U.click(),U.remove(),URL.revokeObjectURL(z)}catch(F){console.error("Failed to zip files:",F),h("Failed to zip files.","error")}}},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-white hover:bg-white/10",title:ce?.downloads?.length===1?"Download File":"Download ZIP",children:[l.jsx(_e,{name:"folder_zip",className:"text-[14px]"}),ce?.downloads?.length===1?"Download":"Download ZIP"]}),p==="data"&&l.jsxs("button",{onClick:async()=>{const F=Bb(ce);if(F.reason){h(F.reason||"Data too large to copy safely.","error");return}const he=op(ce);let U=Hb(F.raw),te=!1;he.truncated&&(await d({message:"Preview is truncated for performance.",confirmLabel:"Copy full",cancelLabel:"Copy preview"})||(U=he.text||"",te=!0)),U.length>vi&&(await d({message:`Copying ${Mb(U.length)} may freeze your browser.`,confirmLabel:"Copy full",cancelLabel:te?"Copy preview":"Copy truncated"})||(U=Lb(F.raw).text,te=!0)),Z(U,"data",{skipSizeConfirm:!0,truncatedNotice:te})},className:`px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 ${_==="data"?"bg-green-500/10 border-green-500/20 text-green-400":"bg-white/5 border-white/10 text-white hover:bg-white/10"}`,title:"Copy extracted data",children:[_==="data"?l.jsx(_e,{name:"check",className:"text-sm"}):l.jsx(_e,{name:"content_copy",className:"text-sm"}),_==="data"?"Copied":"Copy"]})]})]}),P?.truncated&&l.jsx("button",{type:"button",onClick:()=>h("Preview truncated for performance.","error"),className:"absolute top-5 right-5 h-2.5 w-2.5 rounded-full bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.6)]",title:"Preview truncated","aria-label":"Preview truncated"}),l.jsx("div",{className:"max-h-[70vh] overflow-y-auto custom-scrollbar pr-2 relative",children:(()=>{const F=ce&&ce.data!==void 0&&ce.data!==null&&ce.data!=="",he=ce&&ce.downloads&&ce.downloads.length>0;return r&&v==="latest"&&(!ce||!F&&!he)?l.jsx("pre",{className:"font-mono text-[10px] text-blue-300/60 whitespace-pre-wrap leading-relaxed",children:"Buffering data stream..."}):!ce||!F&&!he?l.jsx("pre",{className:"font-mono text-[10px] text-blue-300/60 whitespace-pre-wrap leading-relaxed",children:"No data available."}):l.jsx("div",{className:"h-full",children:p==="downloads"?l.jsx("div",{className:"space-y-2",children:ce.downloads.map((z,U)=>l.jsxs("div",{className:"flex items-center justify-between bg-white/[0.02] border border-white/5 rounded-xl p-4 hover:bg-white/[0.04] transition-colors",children:[l.jsxs("div",{className:"flex items-center gap-4 overflow-hidden pr-4",children:[l.jsx("div",{className:"p-3 bg-white/5 rounded-lg border border-white/10 shrink-0",children:l.jsx(_e,{name:zb(z.name),className:"text-2xl text-white/70"})}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("h4",{className:"text-sm font-bold text-white truncate",children:z.name}),l.jsx("p",{className:"text-[10px] text-gray-500 truncate mt-1",children:z.url})]})]}),l.jsx("a",{href:z.path,download:z.name,className:"shrink-0 p-3 rounded-lg border border-white/10 bg-white/5 text-white/80 hover:bg-white/10 hover:text-white transition-all flex items-center justify-center",title:"Download file","aria-label":"Download file",children:l.jsx(_e,{name:"download",className:"text-[18px]"})})]},U))}):q&&w==="table"?l.jsx("div",{className:"overflow-auto custom-scrollbar rounded-2xl border border-white/10",children:l.jsxs("table",{className:"min-w-full table-auto text-[10px] text-left text-white/80 font-mono",children:[l.jsx("thead",{className:"bg-white/5 text-[9px] uppercase tracking-widest text-white/50",children:l.jsx("tr",{children:q.headers.map(z=>l.jsx("th",{className:"px-3 py-2 border-b border-white/10 whitespace-nowrap",children:z},z))})}),l.jsx("tbody",{children:q.rows.map((z,U)=>l.jsx("tr",{className:"odd:bg-white/[0.02]",children:q.headers.map((te,ae)=>l.jsx("td",{className:"px-3 py-2 border-b border-white/5 align-top whitespace-normal break-words",children:ne(z[ae])},`${U}-${ae}`))},U))})]})}):l.jsx(Si,{readOnly:!0,value:P?.text||"",language:P?.language||"plain"})})})()})]})]})},Gp=R.memo(Kb),Ib=({isOpen:i,onToggle:u,results:r,pinnedResults:c,isExecuting:f,isHeadfulOpen:d,runId:h,onConfirm:m,onNotify:x,onPinResults:g,onUnpinResults:C,useNovnc:_})=>l.jsxs("div",{className:`fixed top-0 right-0 h-full w-[600px] max-w-[90vw] bg-[#080808] border-l border-white/10 shadow-2xl transition-transform duration-500 ease-in-out z-40 transform ${i?"translate-x-0":"translate-x-full"}`,children:[l.jsx("button",{onClick:u,className:"absolute top-1/2 -left-8 -translate-y-1/2 w-8 h-24 bg-[#111] border border-r-0 border-white/10 rounded-l-xl flex items-center justify-center cursor-pointer shadow-[-8px_0_15px_rgba(0,0,0,0.5)] transition-all hover:bg-white/5 hover:w-10 hover:-left-10 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":i?"Close Results Drawer":"Open Results Drawer",title:i?"Close Results Drawer":"Open Results Drawer",children:l.jsx(_e,{name:"drag_indicator",className:`text-white/30 text-xl transition-transform duration-500 ${i?"rotate-180":""}`})}),l.jsx("div",{className:"h-full w-full overflow-y-auto custom-scrollbar p-6",children:l.jsx(Gp,{results:r,pinnedResults:c,isExecuting:f,isHeadful:d,runId:h,onConfirm:m,onNotify:x,onPin:g,onUnpin:C,fullWidth:!0,useNovnc:_})})]}),Zb=({versionPreview:i,onClose:u,onRunSnapshot:r})=>i?l.jsx("div",{className:"fixed inset-0 z-[210] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",children:l.jsxs("div",{className:"glass-card w-full max-w-6xl rounded-[32px] border border-white/10 p-8 shadow-2xl flex flex-col max-h-[90vh]",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-white/5 pb-4 mb-6",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.3em]",children:"Task Snapshot"}),l.jsx("div",{className:"text-lg font-bold text-white",children:i.snapshot.name}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[new Date(i.timestamp).toLocaleString()," | ",i.snapshot.mode]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:u,className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Close"}),l.jsx("button",{onClick:()=>{r(i.snapshot),u()},className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white text-black hover:bg-white/90 transition-all",children:"Run Version"})]})]}),l.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 overflow-y-auto custom-scrollbar pr-2 flex-1 min-h-0",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:"Snapshot JSON"}),l.jsx(Si,{readOnly:!0,value:JSON.stringify(i.snapshot,null,2),language:"json",className:"min-h-[320px]"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:"Output"}),l.jsx("div",{className:"glass-card rounded-2xl p-6 border border-white/10 text-[10px] text-gray-500",children:"No output captured for this snapshot yet. Run this version to see results."})]})]})]})}):null,Xb=({isHeadfulOpen:i,isInspectMode:u,isInspectLoading:r,isExecuting:c,useNovnc:f,onToggleInspect:d,onStopHeadful:h})=>{const m=R.useRef(null);if(!i)return null;const{origin:x,hostname:g}=window.location,C=`${x}/novnc.html?host=${g}&path=websockify`,_=()=>{const A=m.current;if(A){if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}A.requestFullscreen?.().catch(()=>{})}};return l.jsx("div",{className:"fixed inset-0 z-[100] bg-black/40 backdrop-blur-md flex items-center justify-center p-8 pointer-events-auto",children:l.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[800px] bg-black/60 backdrop-blur-3xl border border-white/20 rounded-[32px] shadow-2xl overflow-hidden flex flex-col",children:[l.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between px-6 py-4 border-b border-white/10 bg-black/20 gap-4",children:[l.jsx("div",{className:"flex flex-col gap-1",children:l.jsx("div",{className:"flex items-center gap-3",children:l.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-white",children:"Active Browser Session"})})}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("button",{type:"button",onClick:d,disabled:r||c,className:`px-3 py-1.5 rounded-xl border text-[9px] font-bold uppercase tracking-widest transition-all flex items-center gap-2 disabled:opacity-30 disabled:cursor-not-allowed ${u?"border-green-500/30 bg-green-500/20 text-green-400 hover:bg-green-500/30":"border-white/10 text-white/60 hover:text-white hover:bg-white/10"}`,title:u?"Stop inspecting elements":"Highlight elements on hover",children:[r?l.jsx("div",{className:"w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"}):l.jsx(_e,{name:u?"visibility_off":"center_focus_strong",className:"text-[14px]"}),u?"Stop Inspect":"Inspect UI"]}),l.jsx("button",{type:"button",onClick:_,className:"p-2 text-white/60 hover:text-white transition-colors",title:"Toggle fullscreen",children:l.jsx(_e,{name:"fullscreen",className:"text-[16px]"})}),l.jsx("button",{type:"button",onClick:h,className:"p-2 text-white/60 hover:text-white transition-colors",title:"Close Browser",children:l.jsx(_e,{name:"close",className:"text-[16px]"})})]})]}),l.jsx("div",{ref:m,className:"flex-1 relative bg-black flex items-center justify-center",children:f===!1?l.jsxs("div",{className:"text-center p-8",children:[l.jsx(_e,{name:"open_in_new",className:"text-6xl text-white/20 mb-4 block"}),l.jsx("h3",{className:"text-white text-lg font-bold mb-2",children:"Browser Opened Natively"}),l.jsx("p",{className:"text-white/60 text-sm max-w-md mx-auto leading-relaxed mb-6",children:"The headful browser has been launched in a separate window on your desktop. Use that window to pick selectors. It will automatically sync back here."}),l.jsxs("div",{className:"text-[11px] text-amber-500/80 max-w-md mx-auto bg-amber-500/10 p-4 rounded-xl border border-amber-500/20 text-left",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-2 font-bold uppercase tracking-widest text-amber-500",children:[l.jsx(_e,{name:"warning",className:"text-base"}),l.jsx("span",{children:"Disclaimer"})]}),"Figranium is not optimized for native browser windows. On ",l.jsx("strong",{children:"Wayland displays"}),", you ",l.jsx("strong",{children:"HAVE TO use Docker"}),", or you will have to deal with the problems of a physical browser losing focus or failing to capture clicks.",l.jsx("br",{}),l.jsx("br",{}),"For maximum stability, please install the proper tools (Xvfb, x11vnc, websockify) or use the official Docker image."]})]}):l.jsx("iframe",{src:C,className:"absolute inset-0 w-full h-full border-0",title:"Headful Browser"})})]})})},sa=({value:i,onChange:u,onBlur:r,placeholder:c,variables:f,className:d,syntax:h="plain"})=>{const m=R.useRef(null);return R.useEffect(()=>{if(m.current){const x=m.current.innerHTML,g=qp(i,h,f);if(x!==g){const C=window.getSelection();let _=0;if(C&&C.rangeCount>0){const A=C.getRangeAt(0),w=A.cloneRange();w.selectNodeContents(m.current),w.setEnd(A.endContainer,A.endOffset),_=w.toString().length}if(m.current.innerHTML=g,_>0){const A=document.createTreeWalker(m.current,NodeFilter.SHOW_TEXT);let w=0,N=A.nextNode();for(;N;){const p=N.textContent?.length||0;if(w+p>=_){const b=document.createRange();b.setStart(N,_-w),b.collapse(!0),C?.removeAllRanges(),C?.addRange(b);break}w+=p,N=A.nextNode()}}}}},[i,f]),l.jsx("div",{ref:m,contentEditable:!0,className:`rich-input-content w-full bg-transparent focus:outline-none text-white min-h-[1.5rem] ${d}`,"data-placeholder":c,onInput:x=>u(x.currentTarget.textContent||""),onBlur:x=>{const g=x.currentTarget.textContent||"";u(g),r?.(g)}})},$b=[{value:"Control",label:"Ctrl"},{value:"Shift",label:"Shift"},{value:"Alt",label:"Alt"},{value:"Meta",label:"Meta"}],Qb=["Enter","Tab","Escape","Space","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","F1","F2","F3","F4","F5"].concat([...Array(10)].map((i,u)=>`${u}`)).concat(Array.from({length:26},(i,u)=>String.fromCharCode(65+u))),Jb=[{value:"replace",label:"Replace Text"},{value:"append",label:"Append Text"}],Fb=i=>{if(!i)return{modifiers:[],baseKey:""};const u=i.split("+"),r=u.pop()||"";return{modifiers:u,baseKey:r}},cp=(i,u)=>[...i.filter(Boolean),u].filter(Boolean).join("+"),up=i=>{const u=(i||"").trim(),r=u.match(/^\{\$([\w.]+)\}$/);return r?r[1]:u},Pb=i=>{let u="";return i.type==="click"||i.type==="hover"||i.type==="scroll"||i.type==="wait_selector"?u=i.selector||"":i.type==="type"||i.type==="navigate"||i.type==="wait"||i.type==="javascript"||i.type==="repeat"||i.type==="start"||i.type==="screenshot"||i.type==="wait_downloads"||i.type==="stop"?u=i.value||"":i.type==="set"||i.type==="foreach"||i.type==="merge"?u=i.varName||"":i.type==="press"?u=i.key||"":(i.type==="if"||i.type==="while")&&(u=i.conditionVar||""),u.trim()},pn={string:[{value:"equals",label:"Equals"},{value:"not_equals",label:"Not equal"},{value:"contains",label:"Contains"},{value:"starts_with",label:"Starts with"},{value:"ends_with",label:"Ends with"},{value:"matches",label:"Matches regex"}],number:[{value:"equals",label:"Equals"},{value:"not_equals",label:"Not equal"},{value:"gt",label:"Greater than"},{value:"gte",label:"Greater or equal"},{value:"lt",label:"Less than"},{value:"lte",label:"Less or equal"}],boolean:[{value:"is_true",label:"Is true"},{value:"is_false",label:"Is false"}]},dp=R.memo(({action:i,index:u,status:r,isDragging:c,isDragOver:f,translateY:d,variables:h,availableTasks:m,onUpdate:x,onAutoSave:g,onOpenPalette:C,onOpenContextMenu:_,onPointerDown:A,dragTransformY:w,onStartInspect:N,isSelected:p,selectorOptions:b})=>{const[v,j]=R.useState(!1),k=r==="running"?"border-yellow-400/60":r==="success"?"border-green-400/60":r==="error"?"border-red-400/70":r==="skipped"?"border-gray-500/40":"",B=O=>{const X="text-[12px]";return O==="if"||O==="else"?l.jsx(_e,{name:"call_split",className:`${X} text-white`}):O==="end"?l.jsx(_e,{name:"subdirectory_arrow_right",className:`${X} text-gray-500`}):O==="while"||O==="repeat"?l.jsx(_e,{name:"repeat",className:`${X} text-white`}):O==="foreach"?l.jsx(_e,{name:"list",className:`${X} text-white`}):O==="on_error"?l.jsx(_e,{name:"warning",className:`${X} text-red-400`}):O==="set"?l.jsx(_e,{name:"data_object",className:`${X} text-white`}):O==="stop"?l.jsx(_e,{name:"stop",className:`${X} text-white`}):O==="click"?l.jsx(_e,{name:"ads_click",className:`${X} text-white`}):O==="type"?l.jsx(_e,{name:"text_format",className:`${X} text-white`}):O==="hover"?l.jsx(_e,{name:"my_location",className:`${X} text-white`}):O==="press"?l.jsx(_e,{name:"keyboard",className:`${X} text-white`}):O==="wait"?l.jsx(_e,{name:"schedule",className:`${X} text-white`}):O==="wait_selector"?l.jsx(_e,{name:"schedule",className:`${X} text-white`}):O==="scroll"?l.jsx(_e,{name:"swap_vert",className:`${X} text-white`}):O==="javascript"?l.jsx(_e,{name:"code",className:`${X} text-white`}):O==="csv"?l.jsx(_e,{name:"table_chart",className:`${X} text-white`}):O==="merge"?l.jsx(_e,{name:"layers",className:`${X} text-white`}):O==="screenshot"?l.jsx(_e,{name:"photo_camera",className:`${X} text-white`}):O==="start"?l.jsx(_e,{name:"play_circle",className:`${X} text-white`}):O==="navigate"?l.jsx(_e,{name:"navigation",className:`${X} text-white`}):l.jsx("span",{className:"text-[9px] text-white/20",children:"|"})},D=O=>!O||!(O instanceof HTMLElement)?!1:!!O.closest('input, textarea, select, button, a, [contenteditable="true"], [data-no-drag="true"]'),M=c?`translateY(${w||0}px)`:d?`translateY(${d}px)`:void 0;return l.jsxs("div",{id:`action-${i.id}`,"data-action-id":i.id,onPointerDown:O=>{D(O.target)||O.button===0&&(O.preventDefault(),A(O,i.id,u))},onContextMenu:O=>_(O,i.id),className:`bg-black min-w-[280px] w-full max-w-sm mx-auto border p-5 rounded-2xl space-y-4 group/item relative transition-[transform,box-shadow,opacity,filter,background-color,border-color] duration-150 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-transform select-none touch-none ${k||(p?"border-blue-500 ring-2 ring-blue-500/50":"border-white/20")} ${c?"ring-2 ring-white/40 scale-[1.02] shadow-[0_30px_80px_rgba(0,0,0,0.45)] opacity-85 z-20 mx-auto":""} ${f&&!c?"ring-2 ring-blue-400/60 bg-blue-500/5":""} ${i.disabled?"opacity-40 grayscale":""}`,style:{transform:M},children:[l.jsxs("div",{className:"flex items-center justify-between cursor-pointer",onClick:()=>j(!v),children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"text-[8px] font-bold text-white/20 font-mono tracking-tighter",children:(u+1).toString().padStart(2,"0")}),l.jsx("div",{className:"w-4 h-4 flex items-center justify-center",children:B(i.type)}),l.jsx("button",{onClick:O=>{O.stopPropagation(),C(i.id)},className:"action-type-select text-[10px] font-bold uppercase tracking-[0.2em] text-white focus:outline-none cursor-pointer rounded focus-visible:ring-2 focus-visible:ring-white/50","aria-label":`Change action type: ${i.type}`,children:Dc.find(O=>O.type===i.type)?.label||i.type}),!v&&l.jsx("span",{className:"ml-2 text-white/40 text-[9px] font-mono truncate max-w-[150px] pointer-events-none",children:Pb(i)})]}),l.jsx("div",{className:"flex items-center gap-2",children:l.jsx(_e,{name:v?"expand_less":"expand_more",className:"text-base text-gray-600"})})]}),v&&l.jsxs(l.Fragment,{children:[(i.type==="click"||i.type==="type"||i.type==="hover"||i.type==="wait_selector"||i.type==="scroll")&&l.jsxs("div",{className:"space-y-1.5 relative",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1 block",children:i.type==="scroll"?"Selector (Optional)":"Selector"}),l.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all flex items-center gap-2 relative",children:[l.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[l.jsx(sa,{value:i.selector||"",onChange:O=>x(i.id,{selector:O}),onBlur:()=>g(),variables:h,placeholder:i.type==="scroll"?".scroll-container or leave empty":".btn-primary"}),b&&b.length>1&&l.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:b.map((O,X)=>l.jsx("button",{onClick:$=>{$.stopPropagation(),x(i.id,{selector:O},!0)},className:`text-[9px] px-1.5 py-0.5 rounded border transition-colors ${i.selector===O?"bg-blue-500/20 border-blue-500/50 text-blue-300":"bg-white/[0.02] border-white/10 text-white/40 hover:text-white/80 hover:bg-white/[0.05]"}`,title:"Use this alternative selector",children:O},X))})]}),l.jsx("button",{onClick:()=>{N&&N(i.id)},disabled:i.disabled,className:"text-white transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 flex items-center justify-center opacity-50 hover:opacity-100 shrink-0 disabled:opacity-20 disabled:hover:opacity-20 disabled:cursor-not-allowed rounded",title:"Pick Selector in Browser","aria-label":"Pick Selector in Browser",children:l.jsx(_e,{name:"my_location",className:"text-lg"})})]})]}),i.type==="scroll"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Scroll Speed (ms)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.key||"",onChange:O=>x(i.id,{key:O}),onBlur:()=>g(),variables:h,placeholder:"500"})})]}),(i.type==="navigate"||i.type==="type"||i.type==="wait"||i.type==="wait_selector"||i.type==="javascript"||i.type==="csv")&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:i.type==="navigate"?"URL":i.type==="type"?"Content":i.type==="wait"?"Seconds":i.type==="wait_selector"?"Timeout (Sec)":i.type==="csv"?"CSV Input":"Script"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:i.type==="javascript"?l.jsx(Si,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),language:"javascript",variables:h,className:"min-h-[120px]",placeholder:"return document.title"}):i.type==="csv"?l.jsx(Si,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),language:"plain",variables:h,className:"min-h-[120px]",placeholder:"name,age\\nAda,31"}):l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),variables:h,placeholder:i.type==="navigate"?"https://example.com":i.type==="type"?"Search keywords":i.type==="wait"?"3":i.type==="wait_selector"?"10":"400"})}),i.type==="type"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Mode"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx("select",{value:i.typeMode||"replace",onChange:O=>{x(i.id,{typeMode:O.target.value},!0)},className:"custom-select w-full bg-transparent border-none px-0 py-0 text-[11px] text-white",children:Jb.map(O=>l.jsx("option",{value:O.value,children:O.label},O.value))})})]})]}),i.type==="screenshot"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Label (Optional)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),variables:h,placeholder:"checkout-step"})})]}),i.type==="press"&&(()=>{const{modifiers:O,baseKey:X}=Fb(i.key);return l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Key"}),l.jsx("div",{className:"grid grid-cols-2 gap-1 text-[10px] text-white",children:$b.map($=>l.jsxs("label",{className:"inline-flex items-center space-x-1",children:[l.jsx("input",{type:"checkbox",checked:O.includes($.value),onChange:oe=>{const ce=oe.target.checked?[...O,$.value]:O.filter(q=>q!==$.value);x(i.id,{key:cp(ce,X)},!0)},className:"h-3 w-3 rounded border border-white/30 bg-black/80"}),l.jsx("span",{className:"uppercase text-[9px] text-white/70",children:$.label})]},$.value))}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsxs("select",{value:X,onChange:$=>x(i.id,{key:cp(O,$.target.value)},!0),className:"custom-select w-full bg-transparent border-none px-0 py-0 text-[11px] text-white",children:[l.jsx("option",{value:"",children:"Select key"}),Qb.map($=>l.jsx("option",{value:$,children:$},$))]})})]})})(),i.type==="if"&&(()=>{const O=Object.keys(h||{}),X=up(i.conditionVar||""),$=X&&h?.[X]?.type,oe=i.conditionVarType||$||"string",ce=pn[oe]||pn.string,q=i.conditionOp||ce[0].value;return l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Condition"}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Variable"}),l.jsx("input",{type:"text",list:`if-var-${i.id}`,value:i.conditionVar||"",onChange:P=>x(i.id,{conditionVar:P.target.value}),onBlur:()=>g(),placeholder:"variable name",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"}),O.length>0&&l.jsx("datalist",{id:`if-var-${i.id}`,children:O.map(P=>l.jsx("option",{value:P},P))})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Type"}),l.jsxs("select",{value:oe,onChange:P=>{const E=P.target.value,ne=pn[E]||pn.string;x(i.id,{conditionVarType:E,conditionOp:ne[0].value,conditionValue:E==="boolean"?"":i.conditionValue||""},!0)},className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:[l.jsx("option",{value:"string",children:"String"}),l.jsx("option",{value:"number",children:"Number"}),l.jsx("option",{value:"boolean",children:"Boolean"})]})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Relation"}),l.jsx("select",{value:q,onChange:P=>x(i.id,{conditionOp:P.target.value},!0),className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:ce.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))})]})]}),oe!=="boolean"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Value"}),l.jsx("input",{type:oe==="number"?"number":"text",value:i.conditionValue||"",onChange:P=>x(i.id,{conditionValue:P.target.value}),onBlur:()=>g(),placeholder:oe==="number"?"0":"value",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"})]})]})})(),i.type==="while"&&(()=>{const O=Object.keys(h||{}),X=up(i.conditionVar||""),$=X&&h?.[X]?.type,oe=i.conditionVarType||$||"string",ce=pn[oe]||pn.string,q=i.conditionOp||ce[0].value;return l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Condition"}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Variable"}),l.jsx("input",{type:"text",list:`while-var-${i.id}`,value:i.conditionVar||"",onChange:P=>x(i.id,{conditionVar:P.target.value}),onBlur:()=>g(),placeholder:"variable name",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"}),O.length>0&&l.jsx("datalist",{id:`while-var-${i.id}`,children:O.map(P=>l.jsx("option",{value:P},P))})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Type"}),l.jsxs("select",{value:oe,onChange:P=>{const E=P.target.value,ne=pn[E]||pn.string;x(i.id,{conditionVarType:E,conditionOp:ne[0].value,conditionValue:E==="boolean"?"":i.conditionValue||""},!0)},className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:[l.jsx("option",{value:"string",children:"String"}),l.jsx("option",{value:"number",children:"Number"}),l.jsx("option",{value:"boolean",children:"Boolean"})]})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Relation"}),l.jsx("select",{value:q,onChange:P=>x(i.id,{conditionOp:P.target.value},!0),className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:ce.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))})]})]}),oe!=="boolean"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Value"}),l.jsx("input",{type:oe==="number"?"number":"text",value:i.conditionValue||"",onChange:P=>x(i.id,{conditionValue:P.target.value}),onBlur:()=>g(),placeholder:oe==="number"?"0":"value",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"})]})]})})(),i.type==="repeat"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Times"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),variables:h,placeholder:"3"})})]}),i.type==="foreach"&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Selector (Optional)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.selector||"",onChange:O=>x(i.id,{selector:O}),variables:h,placeholder:".list-item"})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Variable (Array Name)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.varName||"",onChange:O=>x(i.id,{varName:O}),variables:h,placeholder:"items"})})]})]}),i.type==="set"&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Variable Name"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.varName||"",onChange:O=>x(i.id,{varName:O}),variables:h,placeholder:"status"})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Value"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),variables:h,placeholder:"ready"})})]})]}),i.type==="merge"&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Sources"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),variables:h,placeholder:"items, extraItems, {$block.output}"})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Target Variable (Optional)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.varName||"",onChange:O=>x(i.id,{varName:O}),variables:h,placeholder:"allItems"})})]})]}),i.type==="stop"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Outcome"}),l.jsxs("select",{value:i.value||"success",onChange:O=>x(i.id,{value:O.target.value},!0),className:"custom-select w-full bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[9px] font-bold uppercase tracking-[0.2em] text-white/70 focus:outline-none",children:[l.jsx("option",{value:"success",children:"Success"}),l.jsx("option",{value:"error",children:"Error"})]})]}),i.type==="on_error"&&l.jsx("div",{className:"text-[8px] text-gray-600 uppercase tracking-widest",children:"Runs if any action fails."}),i.type==="start"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Task"}),l.jsxs("select",{value:i.value||"",onChange:O=>x(i.id,{value:O.target.value},!0),className:"custom-select w-full bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[9px] font-bold uppercase tracking-[0.2em] text-white/70 focus:outline-none",children:[l.jsx("option",{value:"",disabled:!0,children:"Select task"}),m.length===0&&l.jsx("option",{value:"",disabled:!0,children:"No other tasks"}),m.map(O=>l.jsx("option",{value:O.id,children:O.name||O.id},O.id))]})]})]})]})}),Wb=({currentTask:i,setCurrentTask:u,canvasOffset:r,canvasScale:c,canvasViewportRef:f,triggerExpanded:d,setTriggerExpanded:h,onOpenCabinet:m,handleAutoSave:x,dragState:g,dragOverIndex:C,selectedActionIds:_,actionStatusById:A,availableTasks:w,selectorOptionsById:N,updateAction:p,openActionPalette:b,openContextMenu:v,handleActionPointerDown:j,onOpenHeadful:k,isHeadfulOpen:B,onPointerDown:D,onPointerMove:M,onPointerUp:O,onPointerCancel:X,selectionBox:$})=>{const oe=(ce,q,P=0)=>{const E=[];let ne=ce;for(;ne<q;){const Q=ne,Z=i.actions[Q];if(!Z){ne++;continue}if(Z.type==="if"||Z.type==="while"){const we=ne;let F=1,he=ne+1,z=-1;for(;he<q&&F>0;){const Ne=i.actions[he];if((Ne.type==="if"||Ne.type==="while")&&F++,Ne.type==="end"&&(F--,F===0))break;Ne.type==="else"&&F===1&&Z.type==="if"&&(z=he),he++}const U=he,te=we+1,ae=z!==-1?z:U,Y=z!==-1?z+1:-1,me=z!==-1?U:-1;E.push(l.jsxs("div",{className:"flex flex-col items-center w-full",children:[l.jsx("div",{className:"w-[360px]",children:l.jsx(dp,{action:Z,index:Q,isDragOver:C===Q&&g?.id!==Z.id,isDragging:g?.id===Z.id,dragTransformY:g?.id===Z.id?g.currentY-g.startY:void 0,isSelected:_.has(Z.id),status:A[Z.id],translateY:0,variables:i.variables,availableTasks:w,selectorOptions:N[Z.id],onUpdate:p,onAutoSave:x,onOpenPalette:b,onOpenContextMenu:v,onPointerDown:j,onStartInspect:Ne=>{B||k?.(i.url||"https://www.google.com",Ne,i,i.variables)}})}),l.jsxs("div",{className:"flex gap-16 mt-4 relative",children:[l.jsxs("div",{className:"flex flex-col items-center min-w-[200px]",children:[l.jsx("div",{className:"text-[8px] font-bold text-white/60 uppercase tracking-widest mb-2",children:Z.type==="while"?"Loop":"True"}),l.jsx("div",{className:"w-px h-6 bg-white/25"}),l.jsx("div",{className:"flex flex-col items-center gap-3",children:oe(te,ae,P+1)}),l.jsxs("div",{className:"mt-2 flex flex-col items-center",children:[l.jsx("div",{className:"w-px h-4 bg-white/20"}),l.jsx("button",{onClick:()=>b(void 0,ae),className:"w-12 h-12 border border-dashed border-white/15 rounded-xl hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-lg text-gray-500 group-hover:text-white transition-colors"})})]})]}),Z.type==="if"&&l.jsxs("div",{className:"flex flex-col items-center min-w-[200px]",children:[l.jsx("div",{className:"text-[8px] font-bold text-white/60 uppercase tracking-widest mb-2",children:"Otherwise"}),l.jsx("div",{className:"w-px h-6 bg-white/25"}),l.jsx("div",{className:"flex flex-col items-center gap-3",children:Y!==-1?oe(Y,me,P+1):null}),l.jsxs("div",{className:"mt-2 flex flex-col items-center",children:[l.jsx("div",{className:"w-px h-4 bg-white/20"}),l.jsx("button",{onClick:()=>{if(Y!==-1)b(void 0,me);else{const Ne={id:"act_"+Date.now()+"_else",type:"else",selector:"",value:""},ke=[...i.actions];ke.splice(U,0,Ne),u({...i,actions:ke}),x({...i,actions:ke}),setTimeout(()=>b(void 0,U+1),50)}},className:"w-12 h-12 border border-dashed border-white/15 rounded-xl hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-lg text-gray-500 group-hover:text-white transition-colors"})})]})]})]}),l.jsxs("div",{className:"flex flex-col items-center mt-3",children:[l.jsx("div",{className:"w-px h-2 bg-white/25"}),l.jsx("button",{onClick:()=>b(void 0,U+1),className:"w-8 h-8 border border-dashed border-white/10 rounded-lg hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-sm text-gray-600 group-hover:text-white transition-colors"})}),l.jsx("div",{className:"w-px h-2 bg-white/25"})]})]},Z.id)),ne=U+1}else Z.type==="end"||Z.type==="else"||E.push(l.jsxs("div",{className:"flex flex-col items-center",children:[l.jsx("div",{className:"w-[360px]",children:l.jsx(dp,{action:Z,index:Q,isDragOver:C===Q&&g?.id!==Z.id,isDragging:g?.id===Z.id,dragTransformY:g?.id===Z.id?g.currentY-g.startY:void 0,isSelected:_.has(Z.id),status:A[Z.id],translateY:0,variables:i.variables,availableTasks:w,selectorOptions:N[Z.id],onUpdate:p,onAutoSave:x,onOpenPalette:b,onOpenContextMenu:v,onPointerDown:j,onStartInspect:we=>{B||k?.(i.url||"https://www.google.com",we,i,i.variables)}})}),ne<q-1&&i.actions[ne+1]?.type!=="end"&&l.jsxs("div",{className:"flex flex-col items-center my-1",children:[l.jsx("div",{className:"w-px h-2 bg-white/25"}),l.jsx("button",{onClick:()=>b(void 0,Q+1),className:"w-8 h-8 border border-dashed border-white/10 rounded-lg hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-sm text-gray-600 group-hover:text-white transition-colors"})}),l.jsx("div",{className:"w-px h-2 bg-white/25"})]})]},Z.id)),ne++}return E};return l.jsxs("div",{ref:f,className:"flex-1 overflow-hidden relative cursor-grab active:cursor-grabbing select-none",style:{touchAction:"none"},onPointerDown:D,onPointerMove:M,onPointerUp:O,onPointerCancel:X,children:[l.jsxs("div",{className:"absolute origin-top-left",style:{transform:`translate(${r.x}px, ${r.y}px) scale(${c})`},children:[l.jsx("div",{className:"absolute pointer-events-none z-0",style:{inset:"-1000vw -1000vh",backgroundImage:`radial-gradient(circle, rgba(255,255,255,0.3) ${.8/c}px, transparent 0)`,backgroundSize:"20px 20px"}}),l.jsxs("div",{className:"flex flex-col items-center",style:{paddingTop:"60px",minWidth:"500px"},children:[l.jsxs("div",{className:"w-[360px] bg-black border border-white/15 p-5 rounded-2xl shadow-2xl shadow-black/50 select-text cursor-auto relative z-10",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3 cursor-pointer",onClick:()=>h(!d),children:[l.jsx(_e,{name:"bolt",className:"text-white/40 text-base"}),l.jsx("h3",{className:"text-white/60 font-bold tracking-widest uppercase text-[10px]",children:"On Execution"}),l.jsx(_e,{name:d?"expand_less":"expand_more",className:"text-xs text-gray-600"})]}),l.jsx("button",{onClick:()=>m("mode"),className:"p-2 rounded-lg hover:bg-white/10 text-white/30 hover:text-white transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"Task Settings","aria-label":"Task Settings",children:l.jsx(_e,{name:"settings",className:"text-lg"})})]}),d&&l.jsxs("div",{className:"space-y-4 mt-4 pt-3 border-t border-white/10",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"URL"}),l.jsx("div",{className:"w-full bg-[#111] border border-white/10 rounded-lg px-3 py-2 text-sm focus-within:border-white/30 transition-all",children:l.jsx(sa,{value:i.url,onChange:ce=>u({...i,url:ce}),onBlur:()=>x(),variables:i.variables,placeholder:"https://..."})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Wait (sec)"}),l.jsx("input",{type:"number",value:i.wait,onChange:ce=>u({...i,wait:parseFloat(ce.target.value)||0}),onBlur:()=>x(),className:"w-full bg-[#111] border border-white/10 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/30 transition-all text-white"})]})]})]}),i.mode==="agent"&&l.jsx("div",{className:"w-px h-10 bg-white/25"}),i.mode==="agent"&&l.jsx("div",{className:"flex flex-col items-center w-full select-text cursor-auto",children:l.jsxs("div",{className:"space-y-6 w-full flex flex-col items-center relative",children:[oe(0,i.actions.length),l.jsxs("div",{className:"pt-2 flex flex-col items-center",children:[l.jsx("div",{className:"w-px h-6 bg-white/10"}),l.jsxs("button",{onClick:()=>b(),className:"w-[360px] bg-[#0a0a0a] border border-dashed border-white/15 rounded-2xl p-6 hover:border-white/30 hover:bg-white/[0.03] transition-all flex flex-col items-center justify-center gap-2 group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/5 group-hover:bg-white/10 transition-all flex items-center justify-center",children:l.jsx(_e,{name:"add",className:"text-2xl text-gray-500 group-hover:text-white transition-colors"})}),l.jsx("span",{className:"text-[9px] font-bold uppercase tracking-[0.2em] text-gray-500 group-hover:text-gray-300 transition-colors",children:"Add Action"})]})]})]})})]})]}),$&&l.jsx("div",{className:"fixed inset-0 pointer-events-none z-20 overflow-hidden",children:l.jsx("div",{className:"absolute bg-blue-500/10 border border-blue-400",style:{left:Math.min($.startX,$.currentX),top:Math.min($.startY,$.currentY),width:Math.abs($.currentX-$.startX),height:Math.abs($.currentY-$.startY)}})})]})},Kp=({currentTask:i,setCurrentTask:u,tasks:r=[],isExecuting:c,onSave:f,onRun:d,results:h,pinnedResults:m,onConfirm:x,onNotify:g,onPinResults:C,onUnpinResults:_,onRunSnapshot:A,runId:w,onStop:N,isHeadfulOpen:p,onOpenHeadful:b,onStopHeadful:v,useNovnc:j})=>{const k=ob();cb(i,K=>u(K),(K,I)=>f(K,I));const B=ub(i,u,(K,I)=>f(K,I)),D=db(i,g,x,K=>u(K)),M=fb(i,p,B.updateAction,g,v),{proxyList:O,proxyListLoaded:X}=hb(),[$,oe]=R.useState(null),[,ce]=R.useState(null),[q,P]=R.useState(!1),[E,ne]=R.useState(!1),[Q,Z]=R.useState("mode"),[we,F]=R.useState(null),[he,z]=R.useState(""),[U,te]=R.useState(null),[ae,Y]=R.useState(null),[me,Ne]=R.useState({}),[ke,Ae]=R.useState(!1),[Ue,Ie]=R.useState(!1);R.useEffect(()=>{if(!w||i.mode!=="agent")return;Ne({});const K=new EventSource(`/api/executions/stream?runId=${encodeURIComponent(w)}`,{withCredentials:!0});return K.onmessage=I=>{if(I.data)try{const H=JSON.parse(I.data);H&&H.actionId&&H.status&&Ne(de=>({...de,[H.actionId]:H.status}))}catch{}},()=>K.close()},[w,i.mode]);const He=R.useCallback(K=>{f(K||i,!1)},[f,i]),ct=(K="mode")=>{Z(K),K==="history"&&D.loadVersions(),ne(!0)},S=R.useCallback((K,I)=>{P(!0),z(""),te(K||null),Y(I!==void 0?I:null)},[]),pe=K=>{const I=K.tagName.toLowerCase();return I==="input"||I==="textarea"||K.isContentEditable||K.closest('[data-interactive-target="true"]')};R.useEffect(()=>{const K=I=>{if(!pe(I.target))if(I.key==="Backspace"||I.key==="Delete"){if(B.selectedActionIds.size>0){I.preventDefault();let H=[...i.actions];B.selectedActionIds.forEach(be=>{const fe=H.findIndex(Ee=>Ee.id===be);if(fe!==-1){const Ee=H[fe];if(Ee.type==="if"||Ee.type==="while"){let De=1;for(let Oe=fe+1;Oe<H.length;Oe++)if((H[Oe].type==="if"||H[Oe].type==="while")&&De++,H[Oe].type==="end"&&De--,De===0){H.splice(Oe,1);break}}H.splice(fe,1)}});const de={...i,actions:H};u(de),He(de),B.setSelectedActionIds(new Set)}}else(I.ctrlKey||I.metaKey)&&I.key==="a"?(I.preventDefault(),B.setSelectedActionIds(new Set(i.actions.map(H=>H.id)))):(I.metaKey||I.ctrlKey)&&I.key==="k"&&(I.preventDefault(),q||S())};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[B,i,He,q,S,u]);const le=R.useCallback((K,I)=>{K.preventDefault();const H=8,de=200,be=190,fe=Math.min(Math.max(K.clientX+12,H),window.innerWidth-de-H),Ee=Math.min(Math.max(K.clientY+12,H),window.innerHeight-be-H);oe({id:I,x:fe,y:Ee})},[]),V=K=>({...K,id:"act_"+Date.now()+"_"+Math.floor(Math.random()*1e3)}),L=K=>{const I={id:"act_"+Date.now(),type:K,selector:"",value:""};if((K==="set"||K==="merge")&&(I.varName=""),K==="start"&&(I.value=""),K==="type"&&(I.typeMode="replace"),K==="if"||K==="while"){I.conditionVar="",I.conditionVarType="string",I.conditionOp="equals",I.conditionValue="";const H={id:"act_"+Date.now()+"_end",type:"end",selector:"",value:""},de={...i,actions:[...i.actions,I,H]};u(de),He(de)}else{K==="wait_downloads"&&(I.value="30");const H={...i,actions:[...i.actions,I]};u(H),He(H)}},W=R.useMemo(()=>r.filter(K=>String(K.id||"")!==String(i.id||"")),[r,i.id]);return l.jsxs("div",{className:"flex-1 flex overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500 bg-black relative",children:[l.jsx(pb,{currentTask:i,onUpdateTaskName:K=>u({...i,name:K}),onAutoSave:He,onOpenHistory:()=>ct("history")}),l.jsx(Wb,{currentTask:i,setCurrentTask:u,canvasOffset:k.canvasOffset,canvasScale:k.canvasScale,canvasViewportRef:k.canvasViewportRef,triggerExpanded:Ue,setTriggerExpanded:Ie,onOpenCabinet:ct,handleAutoSave:He,dragState:B.dragState,dragOverIndex:B.dragOverIndex,selectedActionIds:B.selectedActionIds,setSelectedActionIds:B.setSelectedActionIds,actionStatusById:me,availableTasks:W,selectorOptionsById:M.selectorOptionsById,updateAction:B.updateAction,openActionPalette:S,openContextMenu:le,handleActionPointerDown:B.handleActionPointerDown,onOpenHeadful:(K,I)=>{M.setActiveInspectActionId(I||null),b?.(K,I,i,i.variables)},isHeadfulOpen:p,onPointerDown:K=>{if(K.button===1||K.button===0&&k.spaceHeldRef.current)k.startPanning(K);else if(K.button===0&&!pe(K.target)){if(K.target.closest("[data-action-id]"))return;F({startX:K.clientX,startY:K.clientY,currentX:K.clientX,currentY:K.clientY}),!K.shiftKey&&!K.ctrlKey&&!K.metaKey&&B.setSelectedActionIds(new Set),K.target.setPointerCapture?.(K.pointerId)}},onPointerMove:K=>{if(k.isPanning.current)k.handlePanning(K.nativeEvent);else if(we){F(be=>be?{...be,currentX:K.clientX,currentY:K.clientY}:null);const I={left:Math.min(we.startX,K.clientX),right:Math.max(we.startX,K.clientX),top:Math.min(we.startY,K.clientY),bottom:Math.max(we.startY,K.clientY)},H=document.querySelectorAll("[data-action-id]"),de=new Set(K.shiftKey||K.ctrlKey||K.metaKey?Array.from(B.selectedActionIds):[]);H.forEach(be=>{const fe=be.getBoundingClientRect();!(fe.right<I.left||fe.left>I.right||fe.bottom<I.top||fe.top>I.bottom)&&de.add(be.getAttribute("data-action-id"))}),B.setSelectedActionIds(de)}},onPointerUp:()=>{k.stopPanning(),F(null)},onPointerCancel:()=>{k.stopPanning(),F(null)},selectionBox:we}),l.jsxs("div",{className:"absolute bottom-24 left-6 z-30 flex flex-col gap-1 bg-[#111] border border-white/10 rounded-xl p-1 shadow-xl",children:[l.jsx("button",{onClick:()=>k.setCanvasScale(Math.min(2,k.canvasScale*1.2)),className:"w-8 h-8 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center text-sm font-bold",children:"+"}),l.jsxs("div",{className:"text-[8px] text-center text-gray-500 font-bold select-none",children:[Math.round(k.canvasScale*100),"%"]}),l.jsx("button",{onClick:()=>k.setCanvasScale(Math.max(.25,k.canvasScale*.8)),className:"w-8 h-8 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center text-sm font-bold",children:"−"}),l.jsx("button",{onClick:()=>{k.setCanvasScale(1);const K=k.canvasViewportRef.current;k.setCanvasOffset({x:((K?K.clientWidth:1e3)-400)/2,y:20})},className:"w-8 h-8 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center",children:l.jsx(_e,{name:"fit_screen",className:"text-sm"})})]}),$&&(()=>{const K=i.actions.findIndex(be=>be.id===$.id),I=i.actions[K];if(!I)return null;const H=B.selectedActionIds.has(I.id)&&B.selectedActionIds.size>1,de=H?Array.from(B.selectedActionIds):[I.id];return l.jsxs("div",{className:"action-context-menu fixed z-50 w-[200px] bg-[#0b0b0b] border border-white/10 rounded-xl shadow-2xl p-2 text-[10px] font-bold uppercase tracking-widest text-white/80",style:{left:$.x,top:$.y},children:[l.jsxs("button",{onClick:()=>{const be=!I.disabled,fe=i.actions.map(De=>de.includes(De.id)?{...De,disabled:be}:De),Ee={...i,actions:fe};u(Ee),He(Ee),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:[I.disabled?"Enable":"Disable"," ",H?"All":""]}),l.jsxs("button",{onClick:()=>{const be=i.actions.filter(Ee=>!de.includes(Ee.id)),fe={...i,actions:be};u(fe),He(fe),oe(null),B.setSelectedActionIds(new Set)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors text-red-400",children:["Delete ",H?"All":""]}),l.jsx("button",{onClick:()=>{ce(V(I)),B.removeAction(I.id),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:"Cut"}),l.jsx("button",{onClick:()=>{ce(V(I)),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:"Copy"}),l.jsxs("button",{onClick:()=>{const fe=i.actions.filter(Oe=>de.includes(Oe.id)).map(Oe=>V(Oe)),Ee=[...i.actions];Ee.splice(K+1,0,...fe);const De={...i,actions:Ee};u(De),He(De),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:["Duplicate ",H?"All":""]})]})})(),l.jsx(eb,{open:q,query:he,onQueryChange:z,onClose:()=>P(!1),onSelect:K=>{if(U)B.updateAction(U,{type:K},!0);else if(ae!==null){const I={id:"act_"+Date.now(),type:K,selector:"",value:""};(K==="set"||K==="merge")&&(I.varName=""),K==="start"&&(I.value=""),K==="type"&&(I.typeMode="replace"),(K==="if"||K==="while")&&(I.conditionVar="",I.conditionVarType="string",I.conditionOp="equals",I.conditionValue=""),K==="wait_downloads"&&(I.value="30");const H=[...i.actions];if(K==="if"||K==="while"){const be={id:"act_"+Date.now()+"_end",type:"end",selector:"",value:""};H.splice(ae,0,I,be)}else H.splice(ae,0,I);const de={...i,actions:H};u(de),He(de)}else L(K);P(!1),Y(null)}}),l.jsx(Ib,{isOpen:ke,onToggle:()=>Ae(!ke),results:h,pinnedResults:m,isExecuting:c,isHeadfulOpen:p||!1,runId:w,onConfirm:x,onNotify:g,onPinResults:C,onUnpinResults:_,useNovnc:j}),l.jsx(Zb,{versionPreview:D.versionPreview,onClose:()=>D.setVersionPreview(null),onRunSnapshot:A}),l.jsx(Xb,{isHeadfulOpen:p||!1,isInspectMode:M.isInspectMode,isInspectLoading:M.isInspectLoading,isExecuting:c,useNovnc:j,onToggleInspect:M.handleToggleInspect,onStopHeadful:()=>v?.()}),l.jsx(mb,{isExecuting:c,isHeadfulOpen:p||!1,onRun:()=>{Ae(!0),d()},onStop:N,onOpenHeadful:()=>b?.(i.url||"https://www.google.com",void 0,i,i.variables),onStopHeadful:v}),l.jsx(rb,{isOpen:E,onClose:()=>ne(!1),currentTask:i,onUpdateTask:K=>{const I={...i,...K};u(I),He(I)},proxyListLoaded:X,proxyList:O,initialTab:Q,versions:D.versions,versionsLoading:D.versionsLoading,onRollback:D.rollbackToVersion,onPreview:D.openVersionPreview})]})},ey=({config:i,onConfirm:u})=>{const[r,c]=R.useState(i.startEditing||!1),[f,d]=R.useState(i.startEditing&&i.value||""),[h,m]=R.useState(!1),x=()=>{d(i.value||""),m(!1),c(!0)},g=()=>{c(!1),d(""),m(!1)},C=async()=>{const w=f.trim();await i.onSave(w),c(!1)},_=async()=>{i.onRegenerate&&await i.onRegenerate()},A=i.loading?"Loading...":i.value?"••••••••••••••••••••••••••••••••••••••••":"No key set";return l.jsxs("div",{className:"flex flex-col gap-4 py-4 border-b border-white/5 last:border-0",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-blue-400 overflow-hidden",children:i.iconUrl?l.jsx("img",{src:i.iconUrl,alt:i.name,className:"w-6 h-6 object-contain"}):i.iconComponent?l.jsx(i.iconComponent,{className:"w-5 h-5"}):l.jsx(_e,{name:i.icon||"key",className:"text-xl"})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"text-sm font-bold text-white uppercase tracking-widest",children:i.name}),i.badge&&l.jsx("span",{className:`text-[8px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full ${i.badge==="Primary"?"bg-blue-500/20 text-blue-400 border border-blue-500/30":"bg-white/10 text-white/50 border border-white/10"}`,children:i.badge})]}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:i.description})]})]}),r?l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"flex-1 flex items-center gap-3 rounded-2xl bg-black/40 border border-white/30 focus-within:border-white px-4 py-2 transition-all",children:[l.jsx("input",{type:h?"text":"password",value:f,onChange:w=>d(w.target.value),disabled:i.saving,placeholder:"Enter new API key...",className:"flex-1 bg-transparent text-[10px] text-white font-mono focus:outline-none",autoFocus:!0}),l.jsx("button",{onClick:()=>m(!h),type:"button",className:"p-2 rounded-xl text-white/50 hover:text-white hover:bg-white/10 transition-all",title:h?"Hide value":"Show value","aria-label":h?"Hide value":"Show value",children:l.jsx(_e,{name:h?"visibility_off":"visibility",className:"text-base"})})]}),l.jsx("button",{onClick:g,disabled:i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-transparent border border-white/20 text-white hover:bg-white/10 transition-all disabled:opacity-50",children:"Cancel"}),l.jsxs("button",{onClick:C,disabled:i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-blue-500 text-white hover:bg-blue-400 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[l.jsx(_e,{name:"save",className:"text-base"}),i.saving?"Saving...":"Save"]})]}):l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"flex-1 rounded-2xl bg-black/40 border border-white/10 px-4 py-3 font-mono text-[10px] text-blue-200/80 break-all min-h-[44px] flex items-center",children:l.jsx("span",{className:"opacity-80 select-none",children:A})}),!i.readOnly&&l.jsxs("button",{onClick:x,disabled:i.loading||i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-white/10 text-white hover:bg-white/20 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[l.jsx(_e,{name:"edit",className:"text-base"}),"Edit"]}),i.onRegenerate&&l.jsxs("button",{onClick:_,disabled:i.loading||i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-white text-black hover:scale-105 transition-all disabled:opacity-50 disabled:hover:scale-100 disabled:cursor-not-allowed flex items-center gap-2",children:[l.jsx(_e,{name:"autorenew",className:"text-base"}),i.saving?"Generating...":"Regenerate"]}),i.showCopyButton&&i.value&&l.jsx(Ws,{text:i.value,className:"p-3 rounded-2xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",iconClassName:"text-base"}),i.onDelete&&l.jsx("button",{onClick:async()=>{(u?await u(`Are you sure you want to delete the ${i.name}?`):confirm(`Are you sure you want to delete the ${i.name}?`))&&await i.onDelete?.()},disabled:i.loading||i.saving,className:"p-3 rounded-2xl bg-white/5 border border-white/10 text-red-400 hover:bg-red-500/20 hover:border-red-500/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed",title:"Delete Key","aria-label":"Delete Key",children:l.jsx(_e,{name:"delete",className:"text-base"})})]})]})},ty=({keys:i,availableProviders:u,onAddProvider:r,dbProviders:c,onAddDbCredential:f,onConfirm:d})=>{const[h,m]=R.useState(!1),[x,g]=R.useState("list"),[C,_]=R.useState(null),[A,w]=R.useState({name:"",baseUrl:"https://api.baserow.io",token:""}),[N,p]=R.useState(!1),[b,v]=R.useState(null),j=u&&u.length>0&&r||c&&c.length>0&&f,k=()=>{m(!1),g("list"),_(null),w({name:"",baseUrl:"https://api.baserow.io",token:""}),v(null)},B=M=>{_(M),g("db-form"),v(null)},D=async()=>{if(!(!C||!A.name||!A.token||!f)){p(!0),v(null);try{await f({name:A.name,provider:C.providerKey,config:{baseUrl:A.baseUrl,token:A.token}})?k():v("Failed to save credential. Check the server console for details.")}catch(M){console.error("[ApiKeysPanel] handleDbSave error:",M),v("An unexpected error occurred.")}finally{p(!1)}}};return R.useEffect(()=>{if(h){document.body.style.overflow="hidden";const M=document.querySelector("main");M&&(M.style.overflow="hidden")}else{document.body.style.overflow="";const M=document.querySelector("main");M&&(M.style.overflow="")}return()=>{document.body.style.overflow="";const M=document.querySelector("main");M&&(M.style.overflow="")}},[h]),l.jsxs("div",{className:"glass-card p-8 rounded-[40px]",children:[l.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-bold text-white uppercase tracking-widest",children:"API Keys"}),l.jsx("p",{className:"text-[10px] text-gray-400 uppercase tracking-widest mt-1",children:"Manage external integrations and API access"})]}),j&&l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>m(!0),className:"px-6 py-3 rounded-2xl text-[10px] font-bold uppercase tracking-widest bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-all flex items-center gap-2 border border-blue-500/10",children:[l.jsx(_e,{name:"add",className:"text-base"}),"Add API Key"]}),h&&Xg.createPortal(l.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/80 backdrop-blur-md animate-in fade-in duration-200",style:{position:"fixed",top:0,left:0,right:0,bottom:0},onClick:M=>{M.target===M.currentTarget&&k()},children:l.jsxs("div",{className:"glass-card max-w-2xl w-full p-10 rounded-[40px] shadow-2xl relative border border-white/10 animate-in zoom-in-95 duration-300 bg-gray-900/80",children:[l.jsx("button",{onClick:k,className:"absolute top-6 right-6 p-3 rounded-2xl text-white/50 hover:text-white hover:bg-white/10 transition-all","aria-label":"Close",children:l.jsx(_e,{name:"close",className:"text-2xl"})}),x==="list"&&l.jsxs(l.Fragment,{children:[l.jsx("h3",{className:"text-2xl font-bold text-white tracking-wide mb-2",children:"Add Key"}),l.jsx("p",{className:"text-sm text-white/50 mb-8",children:"Choose what you'd like to add."}),u&&u.length>0&&r&&l.jsxs("div",{className:"mb-8",children:[l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em] mb-4",children:"AI Providers"}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:u.map(M=>l.jsxs("button",{onClick:()=>{M.disabled||(r(M.id),k())},disabled:M.disabled,className:`flex items-start gap-4 p-5 rounded-3xl border transition-all text-left ${M.disabled?"border-white/5 bg-white/5 opacity-40 cursor-not-allowed grayscale":"border-white/10 hover:border-blue-400/30 hover:bg-blue-500/5 cursor-pointer group"}`,children:[l.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 overflow-hidden ${M.disabled?"bg-black/20":"bg-white/5 group-hover:scale-110 transition-transform"}`,children:M.iconUrl?l.jsx("img",{src:M.iconUrl,alt:M.name,className:"w-8 h-8 object-contain drop-shadow-md"}):M.iconComponent?l.jsx(M.iconComponent,{className:"w-6 h-6 text-white"}):l.jsx(_e,{name:"api",className:"text-xl text-white"})}),l.jsxs("div",{className:"flex-1",children:[l.jsx("div",{className:"text-base font-bold text-white mb-1",children:M.name}),l.jsx("div",{className:"text-[10px] text-white/50 uppercase tracking-widest",children:M.disabled?"Coming Soon":"Available"})]})]},M.id))})]}),c&&c.length>0&&f&&l.jsxs("div",{children:[l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em] mb-4",children:"Database / Output"}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:c.map(M=>l.jsxs("button",{onClick:()=>!M.disabled&&B(M),disabled:M.disabled,className:`flex items-start gap-4 p-5 rounded-3xl border transition-all text-left ${M.disabled?"border-white/5 bg-white/5 opacity-40 cursor-not-allowed grayscale":"border-white/10 hover:border-emerald-400/30 hover:bg-emerald-500/5 cursor-pointer group"}`,children:[l.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 overflow-hidden ${M.disabled?"bg-black/20":"bg-white/5 group-hover:scale-110 transition-transform"}`,children:M.iconUrl?l.jsx("img",{src:M.iconUrl,alt:M.name,className:"w-8 h-8 object-contain drop-shadow-md"}):l.jsx(_e,{name:"database",className:"text-xl text-white"})}),l.jsxs("div",{className:"flex-1",children:[l.jsx("div",{className:"text-base font-bold text-white mb-1",children:M.name}),l.jsx("div",{className:"text-[10px] text-white/50 uppercase tracking-widest",children:M.disabled?"Coming Soon":"Available"})]})]},M.providerKey))})]})]}),x==="db-form"&&C&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{onClick:()=>g("list"),className:"flex items-center gap-2 text-[10px] font-bold text-gray-500 hover:text-white uppercase tracking-widest mb-6 transition-colors",children:[l.jsx(_e,{name:"arrow_back",className:"text-sm"}),"Back"]}),l.jsxs("h3",{className:"text-2xl font-bold text-white tracking-wide mb-2",children:["Add ",C.name]}),l.jsxs("p",{className:"text-sm text-white/50 mb-8",children:["Enter your ",C.name," credentials."]}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("label",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Name"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/10 rounded-2xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-white/30 transition-colors",placeholder:"e.g. My Baserow",value:A.name,onChange:M=>w(O=>({...O,name:M.target.value})),autoFocus:!0})]}),C.providerKey==="baserow"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("label",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Base URL"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/10 rounded-2xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-white/30 transition-colors",placeholder:"https://api.baserow.io",value:A.baseUrl,onChange:M=>w(O=>({...O,baseUrl:M.target.value}))})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("label",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"API Token"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/10 rounded-2xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-white/30 transition-colors font-mono",placeholder:"Token",type:"password",value:A.token,onChange:M=>w(O=>({...O,token:M.target.value}))})]})]}),b&&l.jsx("p",{className:"mt-4 text-[10px] text-red-400 bg-red-500/10 border border-red-500/20 rounded-xl px-3 py-2",children:b}),l.jsxs("div",{className:"flex gap-3 mt-4",children:[l.jsx("button",{onClick:k,className:"px-6 py-3 rounded-2xl text-[10px] font-bold uppercase tracking-widest bg-transparent border border-white/10 text-gray-400 hover:text-white hover:border-white/20 transition-all",children:"Cancel"}),l.jsx("button",{onClick:D,disabled:N||!A.name||!A.token,className:"flex-1 py-3 rounded-2xl text-[10px] font-bold uppercase tracking-widest bg-white text-black hover:bg-white/90 transition-all disabled:opacity-40 disabled:cursor-not-allowed",children:N?"Saving…":"Save Credential"})]})]})]})}),document.body)]})]}),l.jsx("div",{className:"flex flex-col",children:i.map(M=>l.jsx(ey,{config:M,onConfirm:d},M.id))})]})},ay=({onClearStorage:i})=>l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"delete",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Storage"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Manage stored data"})]})]}),l.jsxs("div",{className:"flex gap-4",children:[l.jsx("button",{onClick:()=>i("screenshots"),className:"flex-1 px-6 py-4 bg-red-500/5 border border-red-500/10 text-red-400 rounded-2xl text-[9px] font-bold uppercase tracking-widest hover:bg-red-500/10 transition-all",children:"Clear Captures"}),l.jsx("button",{onClick:()=>i("cookies"),className:"flex-1 px-6 py-4 bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 rounded-2xl text-[9px] font-bold uppercase tracking-widest hover:bg-yellow-500/10 transition-all",children:"Reset Cookies"})]})]}),ny=72,Ip=6,Xs=ny+Ip,ly=5,iy=2,sy=({index:i,style:u,data:r})=>{const c=r.captures[i];return c?l.jsx("div",{style:{...u,paddingBottom:Ip},children:l.jsxs("div",{className:"flex items-center justify-between gap-4 p-4 rounded-2xl border border-white/10 bg-white/[0.02]",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest",children:c.type==="recording"?"Recording":"Screenshot"}),l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:c.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("a",{href:c.url,target:"_blank",rel:"noreferrer",className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all","aria-label":`Open ${c.name}`,children:"Open"}),l.jsx("button",{onClick:()=>r.onDelete(c.name),className:"px-3 py-2 rounded-xl border border-red-500/20 text-[9px] font-bold uppercase tracking-widest text-red-300 hover:bg-red-500/10 transition-all",children:"Delete"})]})]})}):null},ry=({captures:i,loading:u,onRefresh:r,onDelete:c})=>{const f=Math.min(Math.max(Xs,i.length*Xs),Xs*ly),d=R.useMemo(()=>({captures:i,onDelete:c}),[i,c]);return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Captures"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Recordings and screenshots"})]}),l.jsx("button",{onClick:r,disabled:u,className:"px-4 py-2 border border-white/10 text-[9px] font-bold rounded-xl uppercase tracking-widest text-white/70 hover:text-white hover:bg-white/5 transition-all disabled:opacity-50",children:"Refresh"})]}),u&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading captures..."}),!u&&i.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No captures found."}),!u&&i.length>0&&l.jsx(nr,{height:f,width:"100%",itemCount:i.length,itemSize:Xs,overscanCount:iy,itemData:d,children:sy})]})},Rc=i=>`${i.name}|${i.domain||""}|${i.path||""}|${i.expires||""}`,fp=i=>{if(!i)return!1;let u=0;for(let r=0;r<i.length;r+=1){const c=i.charCodeAt(r);(c===9||c===10||c===13||c>=32&&c<=126)&&(u+=1)}return u/i.length>=.85},oy=i=>{if(!i)return null;if(/%[0-9A-Fa-f]{2}/.test(i))try{const u=decodeURIComponent(i);if(u!==i&&fp(u))return{value:u,kind:"URL"}}catch{}if(/^[A-Za-z0-9+/=]+$/.test(i)&&i.length>=12&&i.length%4===0)try{const u=atob(i);if(u&&fp(u))return{value:u,kind:"Base64"}}catch{}return null},cy=({cookies:i,originsCount:u,loading:r,onClear:c,onDelete:f})=>{const[d,h]=R.useState({}),[m,x]=R.useState({}),g=A=>{const w=Rc(A);h(N=>({...N,[w]:!N[w]}))},C=A=>{const w=Rc(A);x(N=>({...N,[w]:!N[w]}))},_=R.useMemo(()=>i.map(A=>{const w=Rc(A),N=A.value||"";return{cookie:A,key:w,value:N,decodedCandidate:oy(N)}}),[i]);return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"database",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Cookies"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Browser storage state"})]})]}),l.jsx("button",{onClick:c,className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 hover:bg-yellow-500/10 transition-all",children:"Clear Cookies"})]}),r&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading data..."}),!r&&i.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No cookies found."}),l.jsx("div",{className:"space-y-3",children:_.map(({cookie:A,key:w,value:N,decodedCandidate:p})=>{const b=!!d[w],v=!!p&&!!m[w],j=v&&p?p.value:N,k=b||j.length<=120?j:`${j.slice(0,120)}...`;return l.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-2xl p-4 space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest truncate",children:A.name}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[A.domain||"local"," | ",A.path||"/",A.expires?` | ${new Date(A.expires*1e3).toLocaleString()}`:""]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[p&&l.jsx("button",{onClick:()=>C(A),className:"px-3 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl border border-white/10 text-white/70 hover:text-white hover:bg-white/5 transition-all",children:v?"Show Raw":`Decode ${p.kind}`}),l.jsx("button",{onClick:()=>f(A),className:"px-3 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-red-500/5 border border-red-500/10 text-red-400 hover:bg-red-500/10 transition-all",children:"Delete"})]})]}),l.jsx("div",{onClick:()=>g(A),className:"cursor-pointer rounded-xl bg-black/40 border border-white/10 px-3 py-2 font-mono text-[10px] text-blue-200/80 whitespace-pre-wrap break-words",title:"Click to expand/collapse",children:k||"(empty)"})]},w)})}),!r&&u>0&&l.jsxs("div",{className:"pt-2 text-[8px] text-gray-600 uppercase tracking-widest",children:["Origins stored: ",u]})]})},uy=({tab:i,onTabChange:u})=>l.jsxs("div",{className:"flex items-end justify-between mb-8",children:[l.jsx("div",{className:"space-y-2",children:l.jsx("h2",{className:"text-4xl font-bold tracking-tighter text-white",children:"Settings"})}),l.jsx("div",{className:"flex bg-white/5 rounded-xl p-1 border border-white/5",children:["system","data","proxies"].map(r=>l.jsx("button",{onClick:()=>u(r),className:`px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-lg transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${i===r?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:r},r))})]}),dy=({proxies:i,defaultProxyId:u,includeDefaultInRotation:r,rotationMode:c,loading:f,onRefresh:d,onAdd:h,onImport:m,onUpdate:x,onDelete:g,onDeleteMultiple:C,onSetDefault:_,onToggleIncludeDefault:A,onRotationModeChange:w})=>{const[N,p]=R.useState(""),[b,v]=R.useState(""),[j,k]=R.useState(""),[B,D]=R.useState(""),[M,O]=R.useState(!1),[X,$]=R.useState(""),[oe,ce]=R.useState(null),[q,P]=R.useState(""),[E,ne]=R.useState(""),[Q,Z]=R.useState(""),[we,F]=R.useState(""),[he,z]=R.useState(!1),[U,te]=R.useState(""),[ae,Y]=R.useState(""),[me,Ne]=R.useState(new Set),[ke,Ae]=R.useState(null),Ue=R.useRef(null),Ie=()=>{N.trim()&&(h({server:N.trim(),username:b.trim()||void 0,password:j.trim()||void 0,label:B.trim()||void 0,isRotatingPool:M,estimatedPoolSize:X?parseInt(X,10):void 0}),p(""),v(""),k(""),D(""),O(!1),$(""))},He=H=>{ce(H.id),P(H.server),ne(H.username||""),Z(""),F(H.label||""),z(!!H.isRotatingPool),te(H.estimatedPoolSize?String(H.estimatedPoolSize):"")},ct=()=>{ce(null),P(""),ne(""),Z(""),F(""),z(!1),te("")},S=()=>{!oe||!q.trim()||(x(oe,{server:q.trim(),username:E.trim()||void 0,password:Q.trim()||void 0,label:we.trim()||void 0,isRotatingPool:he,estimatedPoolSize:U?parseInt(U,10):void 0}),ct())},pe=H=>{const de=H.trim();if(!de)return null;if(de.includes("://"))return{server:de};const be=de.split(":");if(be.length<2)return null;const fe=be[0]?.trim(),Ee=be[1]?.trim();if(!fe||!Ee)return null;const De=be[2]?be[2].trim():"",Oe=be.length>3?be.slice(3).join(":").trim():"";return{server:`${fe}:${Ee}`,username:De||void 0,password:Oe||void 0}},le=async H=>{const de=Array.from(H.target.files||[]);if(de.length)try{const Ee=(await Promise.all(de.map(De=>De.text()))).join(`
|
|
15
|
-
`).split(/\r?\n/).flatMap(De=>De.split(/[,;]+/)).map(pe).filter(Boolean);if(Ee.length===0){Y("No valid proxies found in file.");return}Y(""),m(Ee)}catch{Y("Failed to read file.")}finally{Ue.current&&(Ue.current.value="")}},V=(H,de)=>{Ne(be=>{const fe=new Set(be);if(de?.shiftKey&&ke){const Ee=i.filter(it=>it.id!=="host"),De=Ee.findIndex(it=>it.id===ke),Oe=Ee.findIndex(it=>it.id===H);if(De!==-1&&Oe!==-1){const it=Math.min(De,Oe),Yt=Math.max(De,Oe);for(let St=it;St<=Yt;St++)fe.add(Ee[St].id);return fe}}return fe.has(H)?fe.delete(H):fe.add(H),fe}),Ae(H)},L=()=>{const H=i.filter(de=>de.id!=="host");me.size>=H.length&&H.length>0?Ne(new Set):Ne(new Set(H.map(de=>de.id)))},W=()=>{me.size>0&&(C(Array.from(me)),Ne(new Set))},K=i.filter(H=>H.id!=="host"),I=K.length>0&&me.size>=K.length;return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"security",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Proxies"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Set defaults and rotate per task"})]}),l.jsx("div",{className:"ml-auto",children:l.jsxs("button",{onClick:d,disabled:f,className:"px-4 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all disabled:opacity-50 inline-flex items-center gap-2",children:[l.jsx(_e,{name:"sync",className:`text-base ${f?"animate-spin":""}`}),"Refresh"]})})]}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[l.jsx("input",{type:"text",placeholder:"Proxy server (host:port or scheme://host:port)",value:N,onChange:H=>p(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy server address"}),l.jsx("input",{type:"text",placeholder:"Label (optional)",value:B,onChange:H=>D(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy label"}),l.jsx("input",{type:"text",placeholder:"Username (optional)",value:b,onChange:H=>v(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy username"}),l.jsx("input",{type:"password",placeholder:"Password (optional)",value:j,onChange:H=>k(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy password"}),l.jsxs("label",{className:"flex items-center gap-3 px-4 py-3 rounded-xl bg-white/[0.05] border border-white/10 group cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:M,onChange:H=>O(H.target.checked),className:"w-4 h-4 rounded border-white/20 bg-transparent"}),l.jsx("span",{className:"text-[10px] text-gray-400 uppercase tracking-widest group-hover:text-white transition-colors",children:"Rotating pool"})]}),M&&l.jsx("input",{type:"number",placeholder:"Estimated size (optional)",value:X,onChange:H=>$(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Estimated pool size",min:"1"})]}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("button",{onClick:Ie,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-white text-black hover:scale-105 transition-all",children:"Add Proxy"}),l.jsx("button",{onClick:()=>Ue.current?.click(),className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest border border-white/10 text-white hover:bg-white/5 transition-all",children:"Import"}),l.jsx("button",{onClick:()=>_("host"),className:`px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest border border-white/10 transition-all ${u?"text-white hover:bg-white/5":"bg-white/10 text-white"}`,children:"Use Host IP"})]}),(me.size>0||K.length>0)&&l.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-2xl bg-white/[0.02] border border-white/5",children:[l.jsxs("label",{className:"flex items-center gap-3 cursor-pointer group",children:[l.jsx("input",{type:"checkbox",checked:I,onChange:L,disabled:K.length===0,className:"w-4 h-4 rounded border-white/20 bg-transparent disabled:opacity-50"}),l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-widest group-hover:text-white transition-colors",children:me.size>0?`${me.size} Selected`:"Select All"})]}),me.size>0&&l.jsxs("button",{onClick:W,className:"px-4 py-2 rounded-xl bg-red-500/10 border border-red-500/20 text-[9px] font-bold uppercase tracking-widest text-red-400 hover:bg-red-500/20 transition-all inline-flex items-center gap-2",children:[l.jsx(_e,{name:"delete",className:"text-base"}),"Delete Selected"]})]}),l.jsx("input",{ref:Ue,type:"file",accept:".txt,text/plain",onChange:le,className:"hidden"}),ae&&l.jsx("div",{className:"text-[9px] text-red-400 uppercase tracking-widest",children:ae}),l.jsxs("label",{className:"flex items-center justify-between gap-3 p-3.5 rounded-2xl bg-white/[0.02] border border-white/5 hover:bg-white/[0.05] transition-all group",children:[l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-widest group-hover:text-white",children:"Rotation mode"}),l.jsxs("select",{value:c,onChange:H=>w(H.target.value==="random"?"random":"round-robin"),className:"bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[10px] text-white uppercase tracking-widest","aria-label":"Rotation mode",children:[l.jsx("option",{value:"round-robin",children:"Round robin"}),l.jsx("option",{value:"random",children:"Random"})]})]}),l.jsxs("label",{className:"flex items-center gap-3 p-3.5 rounded-2xl bg-white/[0.02] border border-white/5 hover:bg-white/[0.05] transition-all cursor-pointer group",children:[l.jsx("input",{type:"checkbox",checked:r,onChange:H=>A(H.target.checked),className:"w-4 h-4 rounded border-white/20 bg-transparent"}),l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-widest group-hover:text-white",children:"Include default IP in rotation pool"})]}),l.jsxs("div",{className:"space-y-3",children:[f&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading proxies..."}),!f&&i.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No proxies saved yet."}),!f&&i.map(H=>{const de=H.id===u,be=H.id===oe;return l.jsx("div",{className:"flex items-center justify-between gap-4 p-4 rounded-2xl border border-white/10 bg-white/[0.02]",children:be?l.jsxs("div",{className:"w-full space-y-3",children:[l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[l.jsx("input",{type:"text",value:q,onChange:fe=>P(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white",placeholder:"Proxy server","aria-label":"Proxy server"}),l.jsx("input",{type:"text",value:we,onChange:fe=>F(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white",placeholder:"Label","aria-label":"Label"}),l.jsx("input",{type:"text",value:E,onChange:fe=>ne(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white",placeholder:"Username","aria-label":"Username"}),l.jsx("input",{type:"password",value:Q,onChange:fe=>Z(fe.target.value),placeholder:"Password (leave blank to keep)",className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white","aria-label":"Password"}),l.jsxs("label",{className:"flex items-center gap-3 px-4 py-2 rounded-xl bg-white/[0.05] border border-white/10 group cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:he,onChange:fe=>z(fe.target.checked),className:"w-3.5 h-3.5 rounded border-white/20 bg-transparent"}),l.jsx("span",{className:"text-[10px] text-gray-400 uppercase tracking-widest group-hover:text-white transition-colors",children:"Rotating pool"})]}),he&&l.jsx("input",{type:"number",placeholder:"Estimated size",value:U,onChange:fe=>te(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white","aria-label":"Estimated pool size",min:"1"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:S,className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all",children:"Save"}),l.jsx("button",{onClick:ct,className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white/70 hover:bg-white/5 transition-all",children:"Cancel"})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex items-center gap-4 border-r border-white/10 pr-4 w-12 justify-center",children:H.id!=="host"?l.jsx("input",{type:"checkbox",checked:me.has(H.id),onChange:()=>{},onClick:fe=>{fe.stopPropagation(),V(H.id,fe)},className:"w-4 h-4 rounded border-white/20 bg-transparent"}):l.jsx("div",{title:"Host IP (Cannot be deleted)",className:"flex items-center justify-center opacity-70",children:l.jsx(_e,{name:"computer",className:"text-lg text-white"})})}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest",children:H.label||H.server}),l.jsxs("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest flex items-center gap-2",children:[l.jsx("span",{children:H.server}),H.isRotatingPool&&l.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-white/10 text-white font-bold inline-flex items-center gap-1",children:[l.jsx(_e,{name:"autorenew",className:"text-[10px]"}),"Pool",H.estimatedPoolSize?`(~${H.estimatedPoolSize})`:""]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{onClick:()=>_(H.id),className:`px-3 py-2 rounded-xl border text-[9px] font-bold uppercase tracking-widest transition-all inline-flex items-center gap-2 ${de?"bg-white text-black border-white":"border-white/10 text-white hover:bg-white/5"}`,children:[de?l.jsx(_e,{name:"star",className:"text-base"}):l.jsx(_e,{name:"star_outline",className:"text-base"}),de?"Default":"Set Default"]}),H.id!=="host"&&l.jsxs(l.Fragment,{children:[l.jsx("button",{onClick:()=>He(H),className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all",children:"Edit"}),l.jsxs("button",{onClick:()=>g(H.id),className:"px-3 py-2 rounded-xl border border-red-500/20 text-[9px] font-bold uppercase tracking-widest text-red-300 hover:bg-red-500/10 transition-all inline-flex items-center gap-2",children:[l.jsx(_e,{name:"delete",className:"text-base"}),"Delete"]})]})]})]})},H.id)})]})]})},fy=({selection:i,options:u,loading:r,onChange:c})=>l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-4",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"User Agent"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Default browser identity"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("select",{value:i,onChange:f=>c(f.target.value),disabled:r,className:"w-full bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white uppercase tracking-widest disabled:opacity-60",children:[l.jsx("option",{value:"system",children:"System user agent (default)"}),u.map(f=>l.jsx("option",{value:f,children:f},f))]}),l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Applies when rotate UA is disabled in tasks."})]})]}),hy=({version:i})=>{const[u,r]=R.useState(!1),c=i?`v${i}`:"Unknown",f=async()=>{const d=i||c;try{if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)await navigator.clipboard.writeText(d);else if(typeof document<"u"){const m=document.createElement("textarea");m.value=d,m.style.position="fixed",m.style.opacity="0",document.body.appendChild(m),m.select(),document.execCommand("copy"),document.body.removeChild(m)}r(!0),setTimeout(()=>r(!1),1500)}catch{r(!1)}};return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"content_copy",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Version"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Package metadata"})]})]}),l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsx("div",{className:"text-[9px] font-bold uppercase tracking-[0.3em] text-white",children:c}),l.jsx("button",{onClick:f,className:"px-4 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all",type:"button",children:u?"Copied":"Copy version"})]})]})},py="0.9.6",my={version:py},Bc=my.version,xy=({onClearStorage:i,onConfirm:u,onNotify:r})=>{const[c,f]=R.useState("system"),[d,h]=R.useState([]),[m,x]=R.useState(!1),[g,C]=R.useState([]),[_,A]=R.useState([]),[w,N]=R.useState([]),[p,b]=R.useState([]),[v,j]=R.useState(!1),[k,B]=R.useState(null),[D,M]=R.useState(!0),[O,X]=R.useState(!1),[$,oe]=R.useState([]),[ce,q]=R.useState(!0),[P,E]=R.useState(!1),[ne,Q]=R.useState([]),[Z,we]=R.useState(!0),[F,he]=R.useState(!1),[z,U]=R.useState([]),[te,ae]=R.useState(!0),[Y,me]=R.useState(!1),[Ne,ke]=R.useState([]),[Ae,Ue]=R.useState(null),[Ie,He]=R.useState(!1),[ct,S]=R.useState("round-robin"),[pe,le]=R.useState(!1),[V,L]=R.useState("system"),[W,K]=R.useState([]),[I,H]=R.useState(!1),de=R.useCallback(async()=>{j(!0);try{const[ge,ve]=await Promise.all([fetch("/api/data/captures"),fetch("/api/data/cookies")]),je=ge.ok?await ge.json():{captures:[]},Ce=ve.ok?await ve.json():{cookies:[],origins:[]};A(Array.isArray(je.captures)?je.captures:[]),N(Array.isArray(Ce.cookies)?Ce.cookies:[]),b(Array.isArray(Ce.origins)?Ce.origins:[])}catch{A([]),N([]),b([])}finally{j(!1)}},[]),be=R.useCallback(async()=>{x(!0);try{const ge=await fetch("/api/credentials");ge.ok&&h(await ge.json())}catch{h([])}finally{x(!1)}},[]),fe=R.useCallback(async ge=>{await fetch(`/api/credentials/${ge}`,{method:"DELETE"}),h(ve=>ve.filter(je=>je.id!==ge))},[]),Ee=R.useCallback(async ge=>{if(!await u(`Delete capture ${ge}?`))return;(await fetch(`/api/data/captures/${encodeURIComponent(ge)}`,{method:"DELETE"})).ok?(r("Capture deleted.","success"),de()):r("Delete failed.","error")},[u,r,de]),De=R.useCallback(async ge=>{if(!await u(`Delete cookie ${ge.name}?`))return;(await fetch("/api/data/cookies/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ge.name,domain:ge.domain,path:ge.path})})).ok?(r("Cookie deleted.","success"),de()):r("Delete failed.","error")},[u,r,de]),Oe=async()=>{M(!0);try{const ge=await fetch("/api/settings/api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),B(null);return}const ve=await ge.json();B(ve.apiKey||null)}catch{B(null)}finally{M(!1)}},it=async()=>{q(!0);try{const ge=await fetch("/api/settings/gemini-api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),oe([]);return}const ve=await ge.json();oe(Array.isArray(ve.geminiApiKeys)?ve.geminiApiKeys:[])}catch{oe([])}finally{q(!1)}},Yt=async()=>{we(!0);try{const ge=await fetch("/api/settings/openai-api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),Q([]);return}const ve=await ge.json();Q(Array.isArray(ve.openAiApiKeys)?ve.openAiApiKeys:[])}catch{Q([])}finally{we(!1)}},St=async()=>{ae(!0);try{const ge=await fetch("/api/settings/claude-api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),U([]);return}const ve=await ge.json();U(Array.isArray(ve.claudeApiKeys)?ve.claudeApiKeys:[])}catch{U([])}finally{ae(!1)}},da=async()=>{le(!0);try{const ge=await fetch("/api/settings/proxies",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),ke([]),Ue(null),S("round-robin");return}const ve=await ge.json();ke(Array.isArray(ve.proxies)?ve.proxies:[]),Ue(ve.defaultProxyId||null),He(!!ve.includeDefaultInRotation),S(ve.rotationMode==="random"?"random":"round-robin")}catch{ke([]),Ue(null),He(!1),S("round-robin")}finally{le(!1)}},Pe=async ge=>{le(!0);try{const ve=await fetch("/api/settings/proxies",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ge)});if(!ve.ok){let Ce="";try{const Xe=await ve.json();Ce=Xe?.error||Xe?.message||""}catch{Ce=""}r(`Failed to add proxy${Ce?`: ${Ce}`:""}.`,"error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Proxy added.","success")}catch{r("Failed to add proxy.","error")}finally{le(!1)}},gt=async()=>{H(!0);try{const ge=await fetch("/api/settings/user-agent",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),L("system"),K([]);return}const ve=await ge.json();L(ve.selection==="system"?"system":String(ve.selection||"system")),K(Array.isArray(ve.userAgents)?ve.userAgents:[])}catch{L("system"),K([])}finally{H(!1)}},Tt=async ge=>{H(!0);try{const ve=await fetch("/api/settings/user-agent",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selection:ge})});if(!ve.ok){r("Failed to update user agent.","error");return}const je=await ve.json();L(je.selection==="system"?"system":String(je.selection||"system")),K(Array.isArray(je.userAgents)?je.userAgents:[]),r("User agent updated.","success")}catch{r("Failed to update user agent.","error")}finally{H(!1)}},st=async ge=>{if(!ge.length){r("No valid proxies found in file.","error");return}le(!0);try{const ve=await fetch("/api/settings/proxies/import",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({proxies:ge})});if(!ve.ok){let Ce="";try{const Xe=await ve.json();Ce=Xe?.error||Xe?.message||""}catch{Ce=""}r(`Failed to import proxies${Ce?`: ${Ce}`:""}.`,"error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Proxies imported.","success")}catch{r("Failed to import proxies.","error")}finally{le(!1)}},Mn=async(ge,ve)=>{le(!0);try{const je=await fetch(`/api/settings/proxies/${encodeURIComponent(ge)}`,{method:"PUT",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ve)});if(!je.ok){let Xe="";try{const Rt=await je.json();Xe=Rt?.error||Rt?.message||""}catch{Xe=""}r(`Failed to update proxy${Xe?`: ${Xe}`:""}.`,"error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r("Proxy updated.","success")}catch{r("Failed to update proxy.","error")}finally{le(!1)}},Sl=async ge=>{if(!(ge==="host"||!await u("Delete this proxy?"))){le(!0);try{const je=await fetch(`/api/settings/proxies/${encodeURIComponent(ge)}`,{method:"DELETE",credentials:"include"});if(!je.ok){r("Delete failed.","error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r("Proxy deleted.","success")}catch{r("Delete failed.","error")}finally{le(!1)}}},jl=async ge=>{if(!(ge.length===0||!await u(`Delete ${ge.length} proxies?`))){le(!0);try{const je=await fetch("/api/settings/proxies",{method:"DELETE",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({ids:ge})});if(!je.ok){r("Bulk delete failed.","error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r(`${ge.length} proxies deleted.`,"success")}catch{r("Bulk delete failed.","error")}finally{le(!1)}}},Va=async ge=>{const ve=ge==="host"?null:ge;le(!0);try{const je=await fetch("/api/settings/proxies/default",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({id:ve})});if(!je.ok){r("Failed to set default.","error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r("Default proxy updated.","success")}catch{r("Failed to set default.","error")}finally{le(!1)}},va=async ge=>{le(!0);try{const ve=await fetch("/api/settings/proxies/rotation",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({includeDefaultInRotation:ge})});if(!ve.ok){r("Failed to update rotation setting.","error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Rotation setting updated.","success")}catch{r("Failed to update rotation setting.","error")}finally{le(!1)}},Qt=async ge=>{le(!0);try{const ve=await fetch("/api/settings/proxies/rotation",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({rotationMode:ge})});if(!ve.ok){r("Failed to update rotation mode.","error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Rotation mode updated.","success")}catch{r("Failed to update rotation mode.","error")}finally{le(!1)}},Dt=async()=>{X(!0);try{const ge=await fetch("/api/settings/api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include"});if(!ge.ok){let je="";try{const Ce=await ge.json();je=Ce?.error||Ce?.message||""}catch{je=""}ge.status===401?r("Session expired. Please log in again.","error"):r(`Failed to generate API key${je?`: ${je}`:""}.`,"error");return}const ve=await ge.json();B(ve.apiKey||null),r("API key generated.","success")}catch{r("Failed to generate API key.","error")}finally{X(!1)}},Ga=async ge=>{E(!0);try{const ve=await fetch("/api/settings/gemini-api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({geminiApiKeys:ge})});if(!ve.ok){ve.status===401?r("Session expired. Please log in again.","error"):r("Failed to save Gemini API keys.","error");return}const je=await ve.json();oe(Array.isArray(je.geminiApiKeys)?je.geminiApiKeys:[]),r("Gemini API keys saved.","success")}catch{r("Failed to save Gemini API keys.","error")}finally{E(!1)}},wa=async ge=>{he(!0);try{const ve=await fetch("/api/settings/openai-api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({openAiApiKeys:ge})});if(!ve.ok){ve.status===401?r("Session expired. Please log in again.","error"):r("Failed to save OpenAI API keys.","error");return}const je=await ve.json();Q(Array.isArray(je.openAiApiKeys)?je.openAiApiKeys:[]),r("OpenAI API keys saved.","success")}catch{r("Failed to save OpenAI API keys.","error")}finally{he(!1)}},_l=async ge=>{me(!0);try{const ve=await fetch("/api/settings/claude-api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({claudeApiKeys:ge})});if(!ve.ok){ve.status===401?r("Session expired. Please log in again.","error"):r("Failed to save Claude API keys.","error");return}const je=await ve.json();U(Array.isArray(je.claudeApiKeys)?je.claudeApiKeys:[]),r("Claude API keys saved.","success")}catch{r("Failed to save Claude API keys.","error")}finally{me(!1)}};R.useEffect(()=>{c==="data"&&de(),c==="system"&&(Oe(),it(),Yt(),St(),gt(),be()),c==="proxies"&&da()},[c]),R.useEffect(()=>{c==="system"&&(Oe(),it(),Yt(),St(),be())},[]);const Ci=[{id:"gemini_api_key",name:"Gemini API Key",iconUrl:"https://www.google.com/s2/favicons?domain=gemini.google.com&sz=128",disabled:!1},{id:"anthropic_api_key",name:"Anthropic API Key",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/claude.svg",disabled:!1},{id:"openai_api_key",name:"OpenAI API Key",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/openai.svg",disabled:!1},{id:"ollama_api_key",name:"Ollama API Key",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/ollama.svg",disabled:!0}],Nl=[{providerKey:"baserow",name:"Baserow",iconUrl:"https://www.google.com/s2/favicons?domain=baserow.io&sz=128"}],xn=async ge=>{try{const ve=await fetch("/api/credentials",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ge)});if(!ve.ok){const Ce=await ve.json().catch(()=>({}));return console.error("[handleAddDbCredential] API error",ve.status,Ce),!1}const je=await ve.json();return h(Ce=>[...Ce,je]),r("Credential saved.","success"),!0}catch(ve){return console.error("[handleAddDbCredential] fetch error:",ve),!1}},fa=[{id:"doppelganger_api_key",name:"Tasks API",description:"Manage task API access via `x-api-key` header",icon:"database",value:k,saving:O,loading:D,showCopyButton:!0,readOnly:!0,onSave:async()=>{},onRegenerate:async()=>{await Dt()}}];$.filter(ge=>ge&&ge.trim()).forEach((ge,ve)=>{fa.push({id:`gemini_api_key_${ve}`,name:"Gemini API Key",description:"Provide an API Key from Google AI Studio for AI features",iconUrl:"https://www.google.com/s2/favicons?domain=gemini.google.com&sz=128",value:ge,saving:P,loading:ce,badge:ve===0?"Primary":"Backup",onSave:async je=>{const Ce=[...$];Ce[ve]=je,await Ga(Ce)},onDelete:async()=>{const je=$.filter((Ce,Xe)=>Xe!==ve);await Ga(je)}})}),ne.filter(ge=>ge&&ge.trim()).forEach((ge,ve)=>{fa.push({id:`openai_api_key_${ve}`,name:"OpenAI API Key",description:"Provide an API Key from OpenAI for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/openai.svg",value:ge,saving:F,loading:Z,badge:ve===0?"Primary":"Backup",onSave:async je=>{const Ce=[...ne];Ce[ve]=je,await wa(Ce)},onDelete:async()=>{const je=ne.filter((Ce,Xe)=>Xe!==ve);await wa(je)}})}),z.filter(ge=>ge&&ge.trim()).forEach((ge,ve)=>{fa.push({id:`anthropic_api_key_${ve}`,name:"Anthropic API Key",description:"Provide an API Key from Anthropic for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/claude.svg",value:ge,saving:Y,loading:te,badge:ve===0?"Primary":"Backup",onSave:async je=>{const Ce=[...z];Ce[ve]=je,await _l(Ce)},onDelete:async()=>{const je=z.filter((Ce,Xe)=>Xe!==ve);await _l(je)}})});const Cl=g.filter(ge=>ge==="gemini_api_key").length;for(let ge=0;ge<Cl;ge++)fa.push({id:`gemini_api_key_unsaved_${ge}`,name:"Gemini API Key",description:"Provide an API Key from Google AI Studio for AI features",iconUrl:"https://www.google.com/s2/favicons?domain=gemini.google.com&sz=128",value:null,saving:P,loading:ce,startEditing:!0,onSave:async ve=>{const je=[...$,ve];await Ga(je),C(Ce=>{const Xe=Ce.indexOf("gemini_api_key");if(Xe!==-1){const Rt=[...Ce];return Rt.splice(Xe,1),Rt}return Ce})},onDelete:async()=>{C(ve=>{const je=ve.indexOf("gemini_api_key");if(je!==-1){const Ce=[...ve];return Ce.splice(je,1),Ce}return ve})}});const El=g.filter(ge=>ge==="openai_api_key").length;for(let ge=0;ge<El;ge++)fa.push({id:`openai_api_key_unsaved_${ge}`,name:"OpenAI API Key",description:"Provide an API Key from OpenAI for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/openai.svg",value:null,saving:F,loading:Z,startEditing:!0,onSave:async ve=>{const je=[...ne,ve];await wa(je),C(Ce=>{const Xe=Ce.indexOf("openai_api_key");if(Xe!==-1){const Rt=[...Ce];return Rt.splice(Xe,1),Rt}return Ce})},onDelete:async()=>{C(ve=>{const je=ve.indexOf("openai_api_key");if(je!==-1){const Ce=[...ve];return Ce.splice(je,1),Ce}return ve})}});const Ei=g.filter(ge=>ge==="anthropic_api_key").length;for(let ge=0;ge<Ei;ge++)fa.push({id:`anthropic_api_key_unsaved_${ge}`,name:"Anthropic API Key",description:"Provide an API Key from Anthropic for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/claude.svg",value:null,saving:Y,loading:te,startEditing:!0,onSave:async ve=>{const je=[...z,ve];await _l(je),C(Ce=>{const Xe=Ce.indexOf("anthropic_api_key");if(Xe!==-1){const Rt=[...Ce];return Rt.splice(Xe,1),Rt}return Ce})},onDelete:async()=>{C(ve=>{const je=ve.indexOf("anthropic_api_key");if(je!==-1){const Ce=[...ve];return Ce.splice(je,1),Ce}return ve})}});return d.forEach(ge=>{fa.push({id:`db_cred_${ge.id}`,name:ge.name,description:`${ge.provider} · ${ge.config.baseUrl}`,iconUrl:"https://www.google.com/s2/favicons?domain=baserow.io&sz=128",value:ge.config.token||null,saving:!1,loading:m,onSave:async()=>{},readOnly:!0,onDelete:async()=>{(u?await u(`Delete credential "${ge.name}"?`):confirm(`Delete credential "${ge.name}"?`))&&await fe(ge.id)}})}),l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-3xl mx-auto space-y-8",children:[l.jsx(uy,{tab:c,onTabChange:f}),c==="system"&&l.jsxs(l.Fragment,{children:[l.jsx(ty,{keys:fa,availableProviders:Ci,onAddProvider:ge=>C(ve=>[...ve,ge]),dbProviders:Nl,onAddDbCredential:xn,onConfirm:u}),l.jsx(fy,{selection:V,options:W,loading:I,onChange:Tt}),l.jsx(hy,{version:Bc}),l.jsx(ay,{onClearStorage:i})]}),c==="data"&&l.jsxs(l.Fragment,{children:[l.jsx(ry,{captures:_,loading:v,onRefresh:de,onDelete:Ee}),l.jsx(cy,{cookies:w,originsCount:p.length,loading:v,onClear:()=>i("cookies"),onDelete:De})]}),c==="proxies"&&l.jsx(dy,{proxies:Ne,defaultProxyId:Ae,includeDefaultInRotation:Ie,rotationMode:ct,loading:pe,onRefresh:da,onAdd:Pe,onImport:st,onUpdate:Mn,onDelete:Sl,onDeleteMultiple:jl,onSetDefault:Va,onToggleIncludeDefault:va,onRotationModeChange:Qt}),l.jsx("div",{className:"pt-8 flex justify-center border-t border-white/5 mt-8",children:l.jsx(Lp,{})})]})})},Lc=({title:i="Loading",subtitle:u})=>l.jsxs("div",{className:"fixed inset-0 z-[80] bg-[#020202] flex items-center justify-center",children:[l.jsx("div",{className:"absolute inset-0 opacity-[0.03] pointer-events-none",style:{backgroundImage:"radial-gradient(#fff 1px, transparent 1px)",backgroundSize:"40px 40px"}}),l.jsxs("div",{className:"glass-card p-10 rounded-[40px] text-center space-y-4",children:[l.jsx("div",{className:"w-12 h-12 mx-auto rounded-full border border-white/10 flex items-center justify-center",children:l.jsx("div",{className:"w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-gray-500",children:i}),u&&l.jsx("p",{className:"text-xs font-mono text-white/80",children:u})]})]})]}),$s=140,gy=6,by=4,yy=({index:i,style:u,data:r})=>{const c=r.items[i];return c?l.jsxs("div",{style:u,onClick:()=>r.navigate(`/executions/${c.id}`),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r.navigate(`/executions/${c.id}`))},role:"button",tabIndex:0,className:"glass-card w-full rounded-2xl p-5 flex items-center gap-4 text-left hover:bg-white/[0.06] transition-all cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:c.source==="api"?l.jsx(_e,{name:"cloud",className:"text-xl"}):l.jsx(_e,{name:"monitor",className:"text-xl"})}),l.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest truncate",children:c.taskName||c.mode}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[new Date(c.timestamp).toLocaleString()," | ",c.source," | ",c.mode," | ",c.status," | ",c.durationMs,"ms"]}),c.url&&l.jsx("div",{className:"text-[9px] text-white/50 truncate font-mono",children:c.url})]}),l.jsx("button",{onClick:f=>{f.stopPropagation(),r.deleteExecution(c.id)},className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-red-500/5 border border-red-500/10 text-red-400 hover:bg-red-500/10 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":`Delete execution ${c.id}`,children:"Delete"})]}):null},vy=({onConfirm:i,onNotify:u})=>{const r=Dn(),[c,f]=R.useState([]),[d,h]=R.useState("all"),[m,x]=R.useState(!1),g=R.useCallback(async()=>{x(!0);try{const N=await fetch("/api/executions");if(!N.ok)throw new Error("Failed to load");const p=await N.json();f(Array.isArray(p.executions)?p.executions:[])}catch{f([])}finally{x(!1)}},[]),C=R.useCallback(async()=>{if(!await i("Clear all executions?"))return;(await fetch("/api/executions/clear",{method:"POST"})).ok?(u("Executions cleared.","success"),g()):u("Clear failed.","error")},[g,i,u]),_=R.useCallback(async N=>{if(!await i("Delete this execution?"))return;(await fetch(`/api/executions/${N}`,{method:"DELETE"})).ok?(u("Execution deleted.","success"),f(v=>v.filter(j=>j.id!==N))):u("Delete failed.","error")},[i,u]);R.useEffect(()=>{g()},[g]);const A=R.useMemo(()=>c.filter(N=>d==="all"?!0:N.source===d),[c,d]),w=R.useMemo(()=>({items:A,deleteExecution:_,navigate:r}),[A,_,r]);return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsx("div",{className:"space-y-2",children:l.jsx("h2",{className:"text-4xl font-bold tracking-tighter text-white",children:"Run History"})}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"flex bg-white/5 rounded-xl p-1 border border-white/5",children:["all","editor","api"].map(N=>l.jsx("button",{onClick:()=>h(N),className:`px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-lg transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${d===N?"bg-white text-black":"text-gray-500 hover:text-white"}`,"aria-pressed":d===N,children:N},N))}),l.jsx("button",{onClick:g,disabled:m,"aria-busy":m,className:"w-10 h-10 rounded-2xl border border-white/10 text-gray-400 hover:text-white hover:bg-white/5 transition-all flex items-center justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 disabled:opacity-50 disabled:cursor-not-allowed",title:"Refresh","aria-label":"Refresh executions",children:l.jsx(_e,{name:"sync",className:`text-xl ${m?"animate-spin":""}`})}),l.jsx("button",{onClick:C,className:"w-10 h-10 rounded-2xl border border-red-500/20 text-red-400 hover:bg-red-500/10 transition-all flex items-center justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"Clear all","aria-label":"Clear all executions",children:l.jsx(_e,{name:"delete",className:"text-xl"})})]})]}),m&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading executions..."}),!m&&A.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No executions found."}),!m&&A.length>0&&l.jsx(nr,{height:Math.min(Math.max($s,A.length*$s),$s*gy),itemCount:A.length,itemSize:$s,width:"100%",overscanCount:by,itemData:w,className:"custom-scrollbar",children:yy})]})})};function Zp(){const[i,u]=R.useState(null);return R.useEffect(()=>{let r=!1;return(async()=>{try{const f=await fetch("/api/headful/status");if(f.ok){const d=await f.json();r||u(!!d.useNovnc)}else r||u(!1)}catch{r||u(!1)}})(),()=>{r=!0}},[]),i}const wy=i=>{if(!i.result)return null;const u=i.result||{};return{url:i.url||u.url||"",finalUrl:u.final_url||u.finalUrl,html:u.html,data:u.data??u.html??"",screenshotUrl:u.screenshot_url||u.screenshotUrl,logs:u.logs||[],timestamp:new Date(i.timestamp).toLocaleTimeString()}},Sy=({onConfirm:i,onNotify:u})=>{const{id:r}=Ap(),c=Dn(),[f,d]=R.useState(null),[h,m]=R.useState(!1),x=Zp();if(R.useEffect(()=>{(async()=>{if(r){m(!0);try{const _=await fetch(`/api/executions/${r}`);if(!_.ok)throw new Error("Failed to load execution");const A=await _.json();d(A.execution||null)}catch{d(null)}finally{m(!1)}}})()},[r]),h)return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsx("div",{className:"max-w-6xl mx-auto text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading execution..."})});if(!f)return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[l.jsx("button",{onClick:()=>c("/executions"),className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Back"}),l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"Execution not found."})]})});const g=wy(f);return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("h2",{className:"text-3xl font-bold tracking-tighter text-white",children:f.taskName||f.mode}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[new Date(f.timestamp).toLocaleString()," | ",f.source," | ",f.mode," | ",f.status," | ",f.durationMs,"ms"]})]}),l.jsx("button",{onClick:()=>c("/executions"),className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Back"})]}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8 flex flex-col min-h-[420px]",children:[l.jsx("div",{className:"flex items-center justify-between border-b border-white/5 pb-4 mb-6",children:l.jsx("span",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:"Output"})}),g?l.jsx(Gp,{results:g,isExecuting:!1,onConfirm:i,onNotify:u,fullWidth:!0,useNovnc:x}):l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"No output captured."})]})]})})},jy=360,Xp=12,Qs=jy+Xp,_y=6,Ny=4,Cy=({index:i,style:u,data:r})=>{const c=r.captures[i];return c?l.jsx("div",{style:{...u,paddingBottom:Xp},children:l.jsx(Yp,{capture:c,onDelete:r.onDelete})}):null},Ey=({onConfirm:i,onNotify:u})=>{const r=Dn(),[c,f]=R.useState([]),[d,h]=R.useState(!1),m=async()=>{h(!0);try{const C=await fetch("/api/data/captures"),_=C.ok?await C.json():{captures:[]};f(Array.isArray(_.captures)?_.captures:[])}catch{f([])}finally{h(!1)}},x=R.useCallback(async C=>{if(!await i(`Delete capture ${C}?`))return;(await fetch(`/api/data/captures/${encodeURIComponent(C)}`,{method:"DELETE"})).ok?(f(w=>w.filter(N=>N.name!==C)),u("Capture deleted.","success")):u("Delete failed.","error")},[i,u]);R.useEffect(()=>{m()},[]);const g=R.useMemo(()=>({captures:c,onDelete:x}),[c,x]);return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("h2",{className:"text-3xl font-bold tracking-tighter text-white",children:"All Captures"}),l.jsx("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:"Recordings and screenshots from every run"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{onClick:m,disabled:d,"aria-busy":d,className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all disabled:opacity-50 inline-flex items-center gap-2",children:[l.jsx(_e,{name:"sync",className:`text-base ${d?"animate-spin":""}`}),"Refresh"]}),l.jsx("button",{onClick:()=>r("/executions"),className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Executions"})]})]}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8",children:[d&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading captures..."}),!d&&c.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No captures found."}),!d&&c.length>0&&l.jsx("div",{className:"space-y-4",children:l.jsx(nr,{height:Math.min(Math.max(Qs,c.length*Qs),Qs*_y),width:"100%",itemCount:c.length,itemSize:Qs,overscanCount:Ny,itemData:g,className:"custom-scrollbar",children:Cy})})]})]})})},$p=({title:i="Not Found",subtitle:u="The page you requested does not exist.",onBack:r})=>l.jsx("div",{className:"h-full flex items-center justify-center px-10",children:l.jsxs("div",{className:"glass-card w-full max-w-2xl rounded-[40px] border border-white/10 p-10 text-center space-y-6",children:[l.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-gray-500",children:"404"}),l.jsx("h2",{className:"text-3xl font-bold tracking-tighter text-white",children:i}),l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.25em] text-gray-500",children:u}),r&&l.jsxs("button",{onClick:r,className:"mt-2 inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-white text-black text-[9px] font-bold uppercase tracking-[0.3em] hover:scale-105 transition-all",children:[l.jsx(_e,{name:"arrow_back",className:"text-base"}),"Back"]})]})}),ky=({message:i,tone:u,onClose:r})=>{const[c,f]=R.useState(!1);return R.useEffect(()=>{const d=setTimeout(()=>{f(!0)},2500);return()=>clearTimeout(d)},[]),R.useEffect(()=>{if(!c)return;const d=setTimeout(()=>r(),240);return()=>clearTimeout(d)},[c,r]),l.jsx("div",{className:`fixed bottom-6 right-6 z-[220] max-w-sm w-full ${c?"animate-out fade-out slide-out-to-bottom-3 duration-200":"animate-in fade-in slide-in-from-bottom-3 duration-300"}`,children:l.jsxs("div",{className:`glass-card rounded-2xl border border-white/10 p-4 shadow-2xl flex items-start gap-3 ${c?"animate-out fade-out zoom-out-95 duration-200":"animate-in fade-in zoom-in-95 duration-300"}`,children:[l.jsx("div",{className:`mt-1 h-2.5 w-2.5 rounded-full ${u==="error"?"bg-red-400":"bg-emerald-400"}`}),l.jsxs("div",{className:"flex-1",children:[l.jsx("p",{className:"text-[8px] font-bold uppercase tracking-[0.35em] text-gray-500",children:"Notification"}),l.jsx("p",{className:"mt-2 font-mono text-[11px] text-white leading-relaxed",children:i})]}),l.jsx("button",{onClick:()=>f(!0),className:"px-2 py-1 text-[8px] font-bold uppercase tracking-[0.2em] text-white/60 hover:text-white",children:"Close"})]})})},Ay=({request:i,onResolve:u})=>l.jsx("div",{className:"fixed inset-0 z-[201] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",children:l.jsxs("div",{className:"glass-card w-full max-w-md rounded-[32px] border border-white/10 p-8 text-center shadow-2xl",children:[l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-gray-500",children:i.title??"Confirm"}),l.jsx("p",{className:"mt-4 font-mono text-sm text-white",children:i.message}),l.jsxs("div",{className:"mt-6 flex gap-4",children:[l.jsx("button",{onClick:()=>u(!1),className:"w-full rounded-2xl px-6 py-3 text-[9px] font-bold uppercase tracking-[0.3em] transition-all bg-white/5 border border-white/10 text-gray-300 hover:bg-white/10",children:i.cancelLabel??"Cancel"}),l.jsx("button",{onClick:()=>u(!0),className:"w-full rounded-2xl px-6 py-3 text-[9px] font-bold uppercase tracking-[0.3em] transition-all bg-white text-black hover:scale-105 shadow-xl shadow-white/10",children:i.confirmLabel??"Confirm"})]})]})}),zy=({tasks:i,loadTasks:u,touchTask:r,currentTask:c,setCurrentTask:f,onTaskLoaded:d,...h})=>{const{id:m}=Ap(),x=Dn(),[g,C]=R.useState(!1),[_,A]=R.useState(!1);return R.useEffect(()=>{(async()=>{if(c?.id===m)return;C(!0),A(!1);let N=i;i.length===0&&(N=await u());const p=N.find(b=>String(b.id)===String(m));if(p){const b={...p};(!b.variables||Array.isArray(b.variables))&&(b.variables={}),b.stealth||(b.stealth={allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1}),b.stealth.cursorGlide===void 0&&(b.stealth.cursorGlide=b.stealth.humanCursor??!1),delete b.stealth.humanCursor,b.stealth.randomizeClicks===void 0&&(b.stealth.randomizeClicks=!1),Array.isArray(b.actions)&&(b.actions=b.actions.map((v,j)=>v&&v.id?v:{...v,id:`act_${Date.now()}_${j}_${Math.floor(Math.random()*1e3)}`})),b.includeShadowDom===void 0&&(b.includeShadowDom=!0),f(b),d?.(b),m&&r(m)}else A(!0);C(!1)})()},[m,i]),_?l.jsx($p,{title:"Task Not Found",subtitle:"This task does not exist or was deleted.",onBack:()=>x("/dashboard")}):g||!c||String(c.id)!==String(m)?l.jsx(Lc,{title:"Loading Mission Data",subtitle:"Syncing task payload"}):l.jsx(Kp,{currentTask:c,setCurrentTask:f,tasks:i,...h})},hp="doppelganger.seenReleaseNotes_0_8";function Ry(){const[i,u]=R.useState(!1),[r,c]=R.useState(""),[f,d]=R.useState(!0);R.useEffect(()=>{Bc.startsWith("0.8.")&&(localStorage.getItem(hp)||(u(!0),h()))},[]);const h=async()=>{try{const x=await fetch("https://api.github.com/repos/figranium/figranium/releases/tags/v0.8.0");if(x.ok){const g=await x.json();c(g.body||"No release notes available.")}else c("Failed to load release notes. Please check our GitHub repository.")}catch{c("Failed to load release notes. Please check our GitHub repository.")}finally{d(!1)}},m=()=>{u(!1),localStorage.setItem(hp,"true")};return i?l.jsx("div",{className:"fixed inset-0 z-[300] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",children:l.jsxs("div",{className:"glass-card w-full max-w-2xl max-h-[80vh] flex flex-col rounded-[32px] border border-white/10 p-8 text-left shadow-2xl overflow-hidden",children:[l.jsxs("div",{className:"flex justify-between items-center mb-6 shrink-0",children:[l.jsx("h2",{className:"text-lg md:text-2xl font-bold text-white tracking-tight",children:"What's new in v0.8.0"}),l.jsxs("span",{className:"bg-white/10 text-white/70 px-3 py-1 rounded-full text-xs font-mono ml-4 shrink-0",children:["v",Bc]})]}),l.jsx("div",{className:"flex-1 overflow-y-auto pr-2 custom-scrollbar text-sm text-gray-300",children:f?l.jsx("div",{className:"flex justify-center items-center h-32",children:l.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-white"})}):l.jsx("div",{className:"whitespace-pre-wrap font-mono text-xs",children:r})}),l.jsx("div",{className:"mt-8 flex justify-end shrink-0",children:l.jsx("button",{onClick:m,className:"rounded-2xl px-8 py-3 text-[10px] font-bold uppercase tracking-[0.3em] transition-all bg-white text-black hover:scale-105 shadow-xl shadow-white/10",children:"Got it"})})]})}):null}const Oy=(i,u)=>{if(typeof i!="string"||!i)return u;switch(i){case"ALREADY_SETUP":return"An account already exists";case"INVALID":return"Invalid credentials";case"SESSION_SAVE_FAILED":return"Unable to persist your session";default:{const r=i.toLowerCase().replace(/_/g," ");return r.charAt(0).toUpperCase()+r.slice(1)}}};function Ty(){const i=Dn(),[u,r]=R.useState(null),[c,f]=R.useState("checking"),[d,h]=R.useState(""),[m,x]=R.useState(!1),g=R.useCallback(async()=>{try{const w=await(await fetch("/api/auth/me",{credentials:"include"})).json();if(w.authenticated)return r(w.user),f("authenticated"),!0;const p=await(await fetch("/api/auth/check-setup",{credentials:"include"})).json();f(p.setupRequired?"setup":"login")}catch{f("login")}return!1},[]);R.useEffect(()=>{g()},[g]);const C=R.useCallback(async(A,w,N,p)=>{if(!A||!w){h("Email and password are required");return}if(c==="setup"&&(!N||w!==p)){h(N?"Passwords do not match":"Name required");return}if(m)return;const b=c==="setup"?"/api/auth/setup":"/api/auth/login",v=c==="setup"?{name:N,email:A,password:w}:{email:A,password:w};x(!0);try{const j=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(v)}),k=await j.json().catch(()=>({}));if(j.ok)h(""),f("checking"),await g()?i("/"):(h("Authentication failed"),f("login"));else{const B=c==="setup"?"Setup failed":"Invalid credentials";h(Oy(k?.error,B))}}catch{h("Network error")}finally{x(!1)}},[c,m,i,g]),_=R.useCallback(async A=>{await A("Are you sure you want to log out?")&&(await fetch("/api/auth/logout",{method:"POST",credentials:"include"}),r(null),f("login"),i("/"))},[i]);return{user:u,setUser:r,authStatus:c,setAuthStatus:f,authError:d,authBusy:m,checkAuth:g,handleAuthSubmit:C,logout:_}}const pp=i=>{if(!i)return"";const u=JSON.parse(JSON.stringify(i));return delete u.last_opened,JSON.stringify(u)},er=i=>{if(typeof i=="boolean")return i;if(i==null)return!1;const u=String(i).toLowerCase();return u==="true"||u==="1"},Dy=i=>i&&i[0].toUpperCase()+i.slice(1),Qp=i=>{if(!i.actions||!Array.isArray(i.actions))return i;let u=!1;const r=i.actions.map((c,f)=>c.id?c:(u=!0,{...c,id:`act_${Date.now()}_${f}_${Math.floor(Math.random()*1e3)}`}));return u?{...i,actions:r}:i},My=()=>({name:"Imported Task",url:"",mode:"scrape",wait:3,selector:"",rotateUserAgents:!1,rotateProxies:!1,rotateViewport:!1,humanTyping:!1,stealth:{allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1},actions:[],variables:{},includeShadowDom:!0,disableRecording:!1,statelessExecution:!1}),Uy=(i,u)=>{if(!i||typeof i!="object")return null;const r=My(),c={...r,...i};return(!c.name||typeof c.name!="string")&&(c.name=`Imported Task ${u+1}`),(!c.mode||!["scrape","agent","headful"].includes(c.mode))&&(c.mode="scrape"),typeof c.wait!="number"&&(c.wait=3),c.stealth||(c.stealth=r.stealth),(!c.variables||Array.isArray(c.variables))&&(c.variables={}),Array.isArray(c.actions)||(c.actions=[]),c.rotateProxies===void 0&&(c.rotateProxies=!1),c.disableRecording===void 0&&(c.disableRecording=!1),c.disableRecording=er(c.disableRecording),c.statelessExecution===void 0&&(c.statelessExecution=!1),c.statelessExecution=er(c.statelessExecution),delete c.versions,delete c.last_opened,c},By=()=>({name:"Task "+Math.floor(Math.random()*100),url:"",mode:"agent",wait:3,selector:"",rotateUserAgents:!1,rotateProxies:!1,rotateViewport:!1,humanTyping:!1,stealth:{allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1},actions:[],variables:{},extractionFormat:"json",includeHtml:!1,includeShadowDom:!0,disableRecording:!1,statelessExecution:!1});function Ly(i,u,r){const[c,f]=R.useState([]),[d,h]=R.useState(null),m=R.useRef(null);R.useEffect(()=>{m.current=d},[d]);const x=R.useCallback(async()=>{try{const j=[...await(await fetch("/api/tasks",{credentials:"include"})).json()].sort((k,B)=>(B.last_opened||0)-(k.last_opened||0));return f(j),j}catch(b){return console.error("Failed to load tasks",b),[]}},[]),g=R.useCallback(async b=>{try{await fetch(`/api/tasks/${b}/touch`,{method:"POST"}),x()}catch(v){console.error("Failed to touch task",v)}},[x]),C=R.useCallback((b,v)=>{const j=By();v(!0),h(j),b(null),i("/tasks/new")},[i]),_=R.useCallback((b,v,j)=>{const k={...b};(!k.variables||Array.isArray(k.variables))&&(k.variables={}),k.stealth||(k.stealth={allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1}),k.stealth.cursorGlide===void 0&&(k.stealth.cursorGlide=k.stealth.humanCursor??!1),delete k.stealth.humanCursor,k.stealth.randomizeClicks===void 0&&(k.stealth.randomizeClicks=!1),k.rotateProxies===void 0&&(k.rotateProxies=!1),k.rotateViewport===void 0&&(k.rotateViewport=!1),k.extractionFormat||(k.extractionFormat="json"),k.includeHtml===void 0&&(k.includeHtml=!1),k.includeShadowDom===void 0&&(k.includeShadowDom=!0),k.disableRecording===void 0&&(k.disableRecording=!1),k.disableRecording=er(k.disableRecording),k.statelessExecution===void 0&&(k.statelessExecution=!1),k.statelessExecution=er(k.statelessExecution);const B=Qp(k);h(B),v(B),j(null),i(`/tasks/${b.id}`),b.id&&g(b.id)},[i,g]),A=R.useCallback(async(b,v)=>{await r("Are you sure you want to delete this task?")&&(await fetch(`/api/tasks/${b}`,{method:"DELETE"}),x(),v.includes(b)&&i("/dashboard"))},[r,x,i]),w=R.useCallback(async(b,v,j,k=!1)=>{const B=j||m.current;if(!B)return;const D={...B,last_opened:Date.now()},X=await(await fetch(`/api/tasks${k?"?version=true":""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)})).json();h(X),b(X),x(),v.includes("new")&&i(`/tasks/${X.id}`,{replace:!0})},[i,x]),N=R.useCallback(b=>{let v=c;if(b&&b.length>0&&(v=c.filter(O=>O.id&&b.includes(O.id))),v.length===0){u("No tasks selected to export.","error");return}const j={exportedAt:new Date().toISOString(),tasks:v},k=new Blob([JSON.stringify(j,null,2)],{type:"application/json"}),B=URL.createObjectURL(k),D=document.createElement("a"),M=new Date().toISOString().slice(0,10);D.href=B,D.download=`doppelganger-tasks-${M}.json`,document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(B),u(`Exported ${v.length} task(s).`,"success")},[c,u]),p=R.useCallback(async b=>{try{const v=await b.text(),j=JSON.parse(v);let k=[];if(Array.isArray(j)?k=j:j&&typeof j=="object"&&(Array.isArray(j.tasks)?k=j.tasks:(j.name||j.actions)&&(k=[j])),k.length===0){u("Invalid import file.","error");return}const B=Date.now(),D=k.map((M,O)=>Uy(M,O)).filter(M=>!!M).map((M,O)=>M.id?M:{...M,id:`task_${B}_${O}`});if(D.length===0){u("No tasks to import.","error");return}await Promise.all(D.map(M=>fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}))),await x(),u(`Imported ${D.length} task(s).`,"success")}catch(v){u(`Import failed: ${v.message||"Unknown error"}`,"error")}},[u,x]);return R.useEffect(()=>{x()},[x]),{tasks:c,setTasks:f,currentTask:d,setCurrentTask:h,loadTasks:x,touchTask:g,createNewTask:C,editTask:_,deleteTask:A,saveTask:w,exportTasks:N,importTasks:p}}const mp=(i,u)=>{const r=String(i||"").trim();if(!r)return"Execution failed.";const c=r.toLowerCase();if(u==="headful"){if(c.includes("missing x server")||c.includes("$display"))return"Headful browser could not start because no display server is available.";if(c.includes("failed to connect to the bus"))return"Headful browser could not start due to missing system services."}let f=r;const d=f.indexOf("--disable-");return d>0&&(f=f.slice(0,d).trim()),f.length>240&&(f=`${f.slice(0,240)}...`),f||"Execution failed."},Hy=i=>{const u=String(i||"").toLowerCase();return u.includes("missing x server")||u.includes("$display")||u.includes("platform failed to initialize")||u.includes("no display server")};function qy(i){const[u,r]=R.useState(!1),[c,f]=R.useState(!1),[d,h]=R.useState(null),[m,x]=R.useState(null),g=Zp(),C=R.useRef(null),_=async()=>{try{await fetch("/headful/stop",{method:"POST"})}catch(p){console.error("Failed to stop headful session",p)}finally{f(!1)}};return{isExecuting:u,isHeadfulOpen:c,results:d,setResults:h,activeRunId:m,useNovnc:g,runTaskWithSnapshot:async(p,b,v)=>{if(!p||!p.url)return;const j=Qp(p);b&&j!==b&&v(j);const k=`run_${Date.now()}_${Math.floor(Math.random()*1e3)}`;if(x(k),u)return;r(!0),h({url:j.url,logs:[],timestamp:"Running..."});let B=null;try{const D={};Object.entries(j.variables).forEach(([P,E])=>{D[P]=E.value});const M=P=>P.replace(/\\{\$(\w+)\\}/g,(E,ne)=>{if(ne==="now")return new Date().toISOString();const Q=D[ne];return Q==null||Q===""?"":String(Q)}),O=P=>typeof P!="string"?P:M(P),X=j.mode!=="agent";B={...{...j,url:X?M(j.url||""):j.url||"",selector:X?O(j.selector):j.selector,actions:X?j.actions.map(P=>({...P,selector:O(P.selector),value:O(P.value),key:O(P.key)})):j.actions},taskVariables:D,variables:D,runSource:"editor",taskId:j.id,taskName:j.name,taskSnapshot:j,runId:k};const oe=async P=>{const E=new AbortController;C.current=E;const ne=await fetch(`/${P}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B),signal:E.signal});if(!ne.ok){let Q=null;try{Q=await ne.json()}catch{Q=null}const Z=new Error(Q?.details||Q?.error||"Request failed");throw Z.code=Q?.error,Z}return ne.json()},ce=j.mode==="headful"?"scrape":j.mode,q=await oe(ce);h({url:j.url,finalUrl:q.final_url,html:q.html,data:q.data??q.html??"No data captured.",screenshotUrl:q.screenshot_url,downloads:q.downloads,logs:q.logs||[],timestamp:new Date().toLocaleTimeString()})}catch(D){if(D?.name==="AbortError"){i("Execution stopped.","success"),r(!1);return}if(j?.mode==="headful"&&B&&(D?.code==="HEADFUL_DISPLAY_UNAVAILABLE"||Hy(D?.message||String(D))))try{const O=await(async()=>{const X=new AbortController;C.current=X;const $=await fetch("/scrape",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B),signal:X.signal});if(!$.ok){const oe=await $.json();throw new Error(oe.details||oe.error||"Request failed")}return $.json()})();O.logs=["Headful display unavailable; ran headless instead.",...O.logs||[]],h({url:j.url,finalUrl:O.final_url,html:O.html,data:O.data??O.html??"No data captured.",screenshotUrl:O.screenshot_url,downloads:O.downloads,logs:O.logs||[],timestamp:new Date().toLocaleTimeString()}),r(!1);return}catch(O){const X=mp(O?.message||String(O),j?.mode);i(`Execution crash: ${X}`,"error"),r(!1);return}const M=mp(D?.message||String(D),j?.mode);i(`Execution crash: ${M}`,"error"),j?.mode==="headful"&&r(!1)}finally{C.current=null,r(!1)}},stopTask:async()=>{if(m)try{await fetch("/api/executions/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({runId:m})})}catch(p){console.error("Failed to request stop",p)}C.current&&C.current.abort(),r(!1)},openHeadful:async(p,b,v,j)=>{if(c){await _();return}f(!0);try{const k=await fetch("/headful",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,targetActionId:b,taskSnapshot:v,variables:j})});if(!k.ok){const B=await k.json().catch(()=>({})),D=B?.details||B?.error||"Failed to start headful session";i(D,"error"),f(!1)}}catch{i("Failed to start headful session","error"),f(!1)}},stopHeadful:_}}function Yy(){const[i,u]=R.useState(null),[r,c]=R.useState(null),f=R.useRef(null),d=R.useCallback((x,g="success")=>{u({message:x,tone:g}),g==="success"&&setTimeout(()=>{u(C=>C&&C.message===x?null:C)},2e3)},[]),h=R.useCallback(x=>new Promise(g=>{f.current=g,c(typeof x=="string"?{message:x}:x)}),[]),m=R.useCallback(x=>{const g=f.current;f.current=null,c(null),g&&g(x)},[]);return{centerAlert:i,setCenterAlert:u,centerConfirm:r,showAlert:d,requestConfirm:h,closeConfirm:m}}function Vy(){const i=Dn(),u=mn(),{centerAlert:r,setCenterAlert:c,centerConfirm:f,showAlert:d,requestConfirm:h,closeConfirm:m}=Yy(),{authStatus:x,authError:g,authBusy:C,handleAuthSubmit:_,logout:A}=Ty(),{tasks:w,currentTask:N,setCurrentTask:p,loadTasks:b,touchTask:v,createNewTask:j,editTask:k,deleteTask:B,saveTask:D,exportTasks:M,importTasks:O}=Ly(i,d,h),{isExecuting:X,isHeadfulOpen:$,results:oe,setResults:ce,activeRunId:q,useNovnc:P,runTaskWithSnapshot:E,stopTask:ne,openHeadful:Q,stopHeadful:Z}=qy(d);R.useEffect(()=>{x==="authenticated"&&b()},[x]);const[we,F]=R.useState(!1),he=R.useRef(""),[z,U]=R.useState("visual"),[te,ae]=R.useState({}),Y="doppelganger.pinnedResults",Ne=(I=>I?.id?String(I.id):"new")(N),ke=N&&te[Ne]||null;R.useEffect(()=>{try{const I=localStorage.getItem(Y);if(I){const H=JSON.parse(I);H&&typeof H=="object"&&ae(H)}}catch{}},[]),R.useEffect(()=>{try{localStorage.setItem(Y,JSON.stringify(te))}catch{}},[te]),R.useEffect(()=>{!u.pathname.startsWith("/tasks")&&z==="history"&&U("visual")},[u.pathname,z]),R.useEffect(()=>{u.pathname==="/tasks/new"&&!N&&j(ce,F)},[u.pathname]),R.useEffect(()=>{if(!N){F(!1);return}const I=pp(N);F(I!==he.current)},[N]),R.useEffect(()=>{if(typeof window>"u")return;const I=H=>{we&&(H.preventDefault(),H.returnValue="")};return window.addEventListener("beforeunload",I),()=>window.removeEventListener("beforeunload",I)},[we]);const Ae=R.useCallback(I=>{he.current=pp(I),F(!1)},[]),Ue=I=>{N&&ae(H=>({...H,[Ne]:I}))},Ie=()=>{N&&ae(I=>{const H={...I};return delete H[Ne],H})},He=async I=>{if(!await h(`Delete all ${I}?`))return;await fetch(I==="screenshots"?"/api/clear-screenshots":"/api/clear-cookies",{method:"POST"}),d(`${Dy(I)} cleared.`,"success")},ct=()=>u.pathname.startsWith("/tasks")?"editor":u.pathname==="/settings"?"settings":u.pathname==="/executions"?"executions":u.pathname==="/captures"?"captures":"dashboard",S=R.useCallback(I=>{I==="dashboard"?i("/dashboard"):I==="settings"?i("/settings"):I==="executions"?i("/executions"):I==="captures"&&i("/captures")},[i]),pe=R.useCallback(()=>{j(ce,F)},[j,ce,F]),le=R.useCallback(I=>{k(I,Ae,ce)},[k,Ae,ce]),V=R.useCallback(I=>{B(I,u.pathname)},[B,u.pathname]),L=R.useCallback((I,H)=>D(Ae,u.pathname,I,H),[D,Ae,u.pathname]),W=R.useCallback(()=>{A(h)},[A,h]);let K;return x==="login"||x==="setup"?K=l.jsx(Jg,{status:x,onSubmit:_,error:g,busy:C}):x==="checking"?K=l.jsx(Lc,{title:"Authenticating",subtitle:"Verifying session state"}):K=l.jsxs("div",{className:"h-full flex flex-row overflow-hidden bg-[#020202]",children:[l.jsx(Ry,{}),l.jsx(Qg,{onNavigate:S,onNewTask:pe,onLogout:W,currentScreen:ct()}),l.jsxs(hg,{children:[l.jsx(ga,{path:"/",element:l.jsx(Wh,{tasks:w,onNewTask:pe,onEditTask:le,onDeleteTask:V,onExportTasks:M,onImportTasks:O})}),l.jsx(ga,{path:"/dashboard",element:l.jsx(Wh,{tasks:w,onNewTask:pe,onEditTask:le,onDeleteTask:V,onExportTasks:M,onImportTasks:O})}),l.jsx(ga,{path:"/tasks/new",element:N?l.jsx(Kp,{currentTask:N,setCurrentTask:p,tasks:w,editorView:z,setEditorView:U,isExecuting:X,onSave:L,onRun:()=>E(N,N,p),onRunSnapshot:I=>E(I||N,N,p),results:oe,pinnedResults:ke,onConfirm:h,onNotify:d,onPinResults:Ue,onUnpinResults:Ie,runId:q,onStop:()=>ne(),isHeadfulOpen:$,onOpenHeadful:(I,H,de,be)=>Q(I,H,de,be),onStopHeadful:Z,useNovnc:P}):l.jsx(Lc,{title:"Initializing",subtitle:"Preparing task workspace"})}),l.jsx(ga,{path:"/tasks/:id",element:l.jsx(zy,{tasks:w,loadTasks:b,touchTask:v,currentTask:N,setCurrentTask:p,editorView:z,setEditorView:U,isExecuting:X,onSave:L,onRun:()=>E(N,N,p),onRunSnapshot:I=>E(I||N,N,p),results:oe,pinnedResults:ke,onConfirm:h,onNotify:d,onPinResults:Ue,onUnpinResults:Ie,runId:q,onStop:()=>ne(),onTaskLoaded:Ae,isHeadfulOpen:$,onOpenHeadful:(I,H,de,be)=>Q(I,H,de,be),onStopHeadful:Z,useNovnc:P})}),l.jsx(ga,{path:"/settings",element:l.jsx(xy,{onClearStorage:He,onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"/executions",element:l.jsx(vy,{onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"/executions/:id",element:l.jsx(Sy,{onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"/captures",element:l.jsx(Ey,{onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"*",element:l.jsx($p,{onBack:()=>i("/dashboard")})})]})]}),l.jsxs("div",{className:"h-full",children:[r&&l.jsx(ky,{message:r.message,tone:r.tone,onClose:()=>c(null)}),f&&l.jsx(Ay,{request:f,onResolve:m}),K]})}x0.createRoot(document.getElementById("root")).render(l.jsx(Fe.StrictMode,{children:l.jsx(Bg,{children:l.jsx(Vy,{})})}));
|
|
14
|
+
`))return null;const r=qb(u).filter(d=>d.some(h=>String(h||"").trim()!==""));if(r.length<2)return null;const c=r[0].map((d,h)=>String(d||"").trim()||`column_${h+1}`),f=r.slice(1);return c.length<2?null:{headers:c,rows:f}}if(Array.isArray(i)){if(i.length===0)return null;if(i.every(u=>u&&typeof u=="object"&&!Array.isArray(u))){const u=[];if(i.forEach(c=>{Object.keys(c).forEach(f=>{u.includes(f)||u.push(f)})}),u.length===0)return null;const r=i.map(c=>u.map(f=>c[f]??""));return{headers:u,rows:r}}if(i.every(u=>Array.isArray(u))){const u=Math.max(...i.map(c=>c.length));return{headers:Array.from({length:u},(c,f)=>`column_${f+1}`),rows:i}}return null}if(i&&typeof i=="object"){const u=Object.keys(i);return u.length===0?null:{headers:u,rows:[u.map(r=>i[r]??"")]}}return null},Vb=(i,u)=>i==null?null:typeof i=="string"?u?{content:i,mime:"text/csv",ext:"csv"}:{content:i,mime:"application/json",ext:"json"}:{content:JSON.stringify(i,null,2),mime:"application/json",ext:"json"},Gb=(i,u,r)=>{const c=new Blob([u],{type:r}),f=URL.createObjectURL(c),d=document.createElement("a");d.href=f,d.download=i,document.body.appendChild(d),d.click(),d.remove(),URL.revokeObjectURL(f)},Kb=({results:i,pinnedResults:u,isExecuting:r,isHeadful:c,runId:f,onConfirm:d,onNotify:h,onPin:m,onUnpin:x,fullWidth:g,useNovnc:C})=>{const[_,A]=R.useState(null),[w,N]=R.useState("raw"),[p,b]=R.useState("data"),[v,j]=R.useState(()=>u&&!i?"pinned":"latest"),k=R.useMemo(()=>C===null?"checking":C?"novnc":"native",[C]),[B,D]=R.useState(!1),[M,O]=R.useState(!1),[X,$]=R.useState([]),oe=R.useRef(null),ce=v==="pinned"&&u?u:i,q=R.useMemo(()=>Yb(ce?.data),[ce?.data]),P=R.useMemo(()=>ce&&ce.data!==void 0&&ce.data!==null&&ce.data!==""?op(ce):null,[ce]),E=R.useMemo(()=>ce?.screenshotUrl?`${ce.screenshotUrl}${v==="latest"?`?t=${Date.now()}`:""}`:null,[ce?.screenshotUrl,v]),ne=F=>{const he=Ub(F);return he!==null?he?l.jsx(_e,{name:"check",className:"text-xs text-blue-400"}):"":F??""},Q=async()=>{O(!0);try{const F=f?`?runId=${encodeURIComponent(f)}`:"",he=await fetch(`/api/data/captures${F}`),z=he.ok?await he.json():{captures:[]};$(Array.isArray(z.captures)?z.captures:[])}catch{$([])}finally{O(!1)}};R.useEffect(()=>{N(q?"table":"raw"),!ce?.downloads||ce.downloads.length===0?b("data"):ce?.data||b("downloads")},[ce]),R.useEffect(()=>{if(i){j("latest");return}u&&j("pinned")},[i,u]),R.useEffect(()=>{!u&&v==="pinned"&&j("latest")},[u,v]);const Z=async(F,he,z)=>{if(!F){h("Nothing to copy.","error");return}let U=F;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(U);else{const te=document.createElement("textarea");te.value=U,te.style.position="fixed",te.style.left="-999999px",te.style.top="-999999px",document.body.appendChild(te),te.focus(),te.select(),document.execCommand("copy"),te.remove()}A(he),setTimeout(()=>A(null),2e3),z?.truncatedNotice?h("Copied truncated data.","success"):U.length!==F.length&&h("Copied a truncated preview.","success")}catch(te){console.error("Copy failed:",te),h("Copy failed.","error")}};if(c&&v==="latest"){const{origin:F,hostname:he}=window.location,z=`${F}/novnc.html?host=${he}&path=websockify`,U=()=>{const te=oe.current;if(te){if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}te.requestFullscreen?.().catch(()=>{})}};return k==="native"?l.jsxs("div",{className:"glass-card rounded-[32px] overflow-hidden h-[80vh] w-full relative flex flex-col items-center justify-center p-8 text-center gap-4",children:[l.jsx("div",{className:"text-[12px] font-bold uppercase tracking-widest text-white",children:"Headful Session Active"}),l.jsx("div",{className:"text-[10px] font-bold uppercase tracking-widest text-amber-500/80 max-w-lg leading-relaxed",children:"Figranium is not optimized for native browser windows. Please install the proper tools for stability (Xvfb, x11vnc, websockify) or simply use the Docker version."})]}):k==="checking"?l.jsx("div",{className:"glass-card rounded-[32px] overflow-hidden h-[80vh] w-full relative flex items-center justify-center",children:l.jsx("div",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Checking headful viewer..."})}):l.jsxs("div",{ref:oe,className:"glass-card rounded-[32px] overflow-hidden h-[80vh] w-full relative",children:[l.jsx("button",{type:"button",onClick:U,className:"absolute top-4 right-4 z-10 px-3 py-2 rounded-xl border border-white/20 bg-black/40 text-[9px] font-bold uppercase tracking-widest text-white/80 hover:bg-black/60 transition-all",title:"Toggle fullscreen",children:"Fullscreen"}),l.jsx("iframe",{src:z,className:"absolute inset-0 w-full h-full",title:"Headful Browser"})]})}if(!ce&&!(r&&v==="latest"))return l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center space-y-4 opacity-20",children:[l.jsx("div",{className:"w-16 h-16 border border-white/10 rounded-full flex items-center justify-center",children:l.jsx(_e,{name:"terminal",className:"text-2xl text-white"})}),l.jsx("p",{className:"text-[9px] font-bold uppercase tracking-[0.3em]",children:"Ready"})]});const we=g?"space-y-12 relative z-10 w-full":"space-y-12 relative z-10 max-w-5xl mx-auto";return l.jsxs("div",{className:we,children:[l.jsxs("div",{className:"flex items-end justify-between border-b border-white/5 pb-10",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.3em]",children:"Preview"}),l.jsx("h2",{className:"text-xl font-mono text-white truncate max-w-xl tracking-tight italic",children:ce?.finalUrl||ce?.url||""})]}),l.jsx("div",{className:`px-4 py-2 rounded-xl text-[9px] font-bold uppercase tracking-[0.2em] ${v==="pinned"?"bg-amber-500/10 text-amber-300":r?"bg-blue-500/10 text-blue-400 animate-pulse":"bg-green-500/10 text-green-400"}`,children:v==="pinned"?"Pinned":r?"Running":"Finished"})]}),l.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[l.jsxs("div",{className:"glass-card rounded-[32px] overflow-hidden flex flex-col min-h-[400px]",children:[l.jsxs("div",{className:"p-6 border-b border-white/5 flex items-center justify-between text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:[l.jsx("span",{children:"Screenshot"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-white/20",children:ce?.timestamp||"--:--:--"}),l.jsx("button",{type:"button",onClick:()=>{D(!0),Q()},className:"px-3 py-2 rounded-xl border border-white/10 text-[8px] font-bold uppercase tracking-widest text-white/70 hover:text-white hover:bg-white/5 transition-all",children:"View All Captures"})]})]}),l.jsx("div",{className:"relative bg-black flex-1 flex items-center justify-center overflow-hidden",children:E?l.jsx("img",{src:E,className:"absolute inset-0 w-full h-full object-contain transition-opacity duration-1000"}):l.jsx("div",{className:"text-[8px] font-bold text-white/5 uppercase tracking-widest",children:"Waiting for Frame..."})})]}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8 flex flex-col h-[400px]",children:[l.jsx("span",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest mb-6 border-b border-white/5 pb-4",children:"Activity Log"}),l.jsxs("div",{className:"flex-1 font-mono text-[10px] text-gray-400 space-y-2 overflow-y-auto custom-scrollbar pr-2",children:[ce?.logs?.map((F,he)=>l.jsxs("div",{className:"flex gap-2",children:[l.jsx("span",{className:"text-white/10 shrink-0",children:"›"})," ",l.jsx("span",{children:F})]},he)),r&&v==="latest"&&(!ce?.logs||ce?.logs.length===0)&&l.jsx("div",{className:"animate-pulse",children:"Connecting to kernel..."})]})]})]}),B&&l.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-6",children:l.jsxs("div",{className:"glass-card rounded-[32px] w-full max-w-5xl max-h-[85vh] overflow-hidden flex flex-col",children:[l.jsxs("div",{className:"p-6 border-b border-white/10 flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-widest",children:"Captures"}),l.jsx("div",{className:"text-sm font-bold text-white",children:"Recordings and Screenshots"})]}),l.jsx("button",{onClick:()=>D(!1),className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all bg-white/5 border-white/10 text-white hover:bg-white/10",children:"Close"})]}),l.jsxs("div",{className:"p-6 overflow-y-auto custom-scrollbar",children:[M&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading captures..."}),!M&&X.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No captures found."}),!M&&X.length>0&&l.jsx(nr,{height:Math.min(Math.max(Ks,X.length*Ks),Ks*Ob),width:"100%",itemCount:X.length,itemSize:Ks,overscanCount:Tb,itemData:X,className:"custom-scrollbar",children:Db})]})]})}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8 flex flex-col relative",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-white/5 pb-4 mb-6",children:[l.jsx("span",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:p==="downloads"?"Downloads":"Data"}),l.jsxs("div",{className:"flex items-center gap-2",children:[ce?.downloads&&ce.downloads.length>0&&l.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 border border-white/10",children:["data","downloads"].map(F=>l.jsx("button",{onClick:()=>b(F),className:`px-3 py-1 rounded text-[8px] font-bold uppercase tracking-widest transition-all ${p===F?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:F},F))}),u&&l.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 border border-white/10",children:["latest","pinned"].map(F=>l.jsx("button",{onClick:()=>j(F),className:`px-3 py-1 rounded text-[8px] font-bold uppercase tracking-widest transition-all ${v===F?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:F},F))}),q&&p==="data"&&l.jsx("div",{className:"flex bg-white/5 rounded-lg p-0.5 border border-white/10",children:["table","raw"].map(F=>l.jsx("button",{onClick:()=>N(F),className:`px-3 py-1 rounded text-[8px] font-bold uppercase tracking-widest transition-all ${w===F?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:F},F))}),v==="pinned"?l.jsx("button",{onClick:()=>{x?.(),j("latest")},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-amber-200 hover:bg-white/10",title:"Unpin data",children:"Unpin"}):l.jsx("button",{onClick:()=>{if(!ce){h("No data to pin.","error");return}m?.(ce),j("pinned")},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-white hover:bg-white/10",title:"Pin data",children:u?"Update Pin":"Pin"}),p==="data"&&l.jsx("button",{onClick:()=>{const F=Vb(ce?.data,q);if(!F){h("No data to export.","error");return}const he=`doppelganger-data-${new Date().toISOString().replace(/[:.]/g,"-")}.${F.ext}`;Gb(he,F.content,F.mime),h(`Exported ${F.ext.toUpperCase()}.`,"success")},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-white hover:bg-white/10",title:"Export extracted data",children:"Export"}),p==="downloads"&&l.jsxs("button",{onClick:async()=>{if(!(!ce?.downloads||ce.downloads.length===0)){if(ce.downloads.length===1){const F=ce.downloads[0],he=document.createElement("a");he.href=F.path,he.download=F.name,document.body.appendChild(he),he.click(),he.remove(),h(`Downloading ${F.name}`,"success");return}h("Generating ZIP...","success");try{const F=new Ab;for(const te of ce.downloads){const Y=await(await fetch(te.path)).blob();F.file(te.name,Y)}const he=await F.generateAsync({type:"blob"}),z=URL.createObjectURL(he),U=document.createElement("a");U.href=z,U.download=`doppelganger-downloads-${new Date().toISOString().replace(/[:.]/g,"-")}.zip`,document.body.appendChild(U),U.click(),U.remove(),URL.revokeObjectURL(z)}catch(F){console.error("Failed to zip files:",F),h("Failed to zip files.","error")}}},className:"px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 bg-white/5 border-white/10 text-white hover:bg-white/10",title:ce?.downloads?.length===1?"Download File":"Download ZIP",children:[l.jsx(_e,{name:"folder_zip",className:"text-[14px]"}),ce?.downloads?.length===1?"Download":"Download ZIP"]}),p==="data"&&l.jsxs("button",{onClick:async()=>{const F=Bb(ce);if(F.reason){h(F.reason||"Data too large to copy safely.","error");return}const he=op(ce);let U=Hb(F.raw),te=!1;he.truncated&&(await d({message:"Preview is truncated for performance.",confirmLabel:"Copy full",cancelLabel:"Copy preview"})||(U=he.text||"",te=!0)),U.length>vi&&(await d({message:`Copying ${Mb(U.length)} may freeze your browser.`,confirmLabel:"Copy full",cancelLabel:te?"Copy preview":"Copy truncated"})||(U=Lb(F.raw).text,te=!0)),Z(U,"data",{skipSizeConfirm:!0,truncatedNotice:te})},className:`px-3 py-2 border text-[9px] font-bold rounded-xl uppercase transition-all flex items-center gap-2 ${_==="data"?"bg-green-500/10 border-green-500/20 text-green-400":"bg-white/5 border-white/10 text-white hover:bg-white/10"}`,title:"Copy extracted data",children:[_==="data"?l.jsx(_e,{name:"check",className:"text-sm"}):l.jsx(_e,{name:"content_copy",className:"text-sm"}),_==="data"?"Copied":"Copy"]})]})]}),P?.truncated&&l.jsx("button",{type:"button",onClick:()=>h("Preview truncated for performance.","error"),className:"absolute top-5 right-5 h-2.5 w-2.5 rounded-full bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.6)]",title:"Preview truncated","aria-label":"Preview truncated"}),l.jsx("div",{className:"max-h-[70vh] overflow-y-auto custom-scrollbar pr-2 relative",children:(()=>{const F=ce&&ce.data!==void 0&&ce.data!==null&&ce.data!=="",he=ce&&ce.downloads&&ce.downloads.length>0;return r&&v==="latest"&&(!ce||!F&&!he)?l.jsx("pre",{className:"font-mono text-[10px] text-blue-300/60 whitespace-pre-wrap leading-relaxed",children:"Buffering data stream..."}):!ce||!F&&!he?l.jsx("pre",{className:"font-mono text-[10px] text-blue-300/60 whitespace-pre-wrap leading-relaxed",children:"No data available."}):l.jsx("div",{className:"h-full",children:p==="downloads"?l.jsx("div",{className:"space-y-2",children:ce.downloads.map((z,U)=>l.jsxs("div",{className:"flex items-center justify-between bg-white/[0.02] border border-white/5 rounded-xl p-4 hover:bg-white/[0.04] transition-colors",children:[l.jsxs("div",{className:"flex items-center gap-4 overflow-hidden pr-4",children:[l.jsx("div",{className:"p-3 bg-white/5 rounded-lg border border-white/10 shrink-0",children:l.jsx(_e,{name:zb(z.name),className:"text-2xl text-white/70"})}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("h4",{className:"text-sm font-bold text-white truncate",children:z.name}),l.jsx("p",{className:"text-[10px] text-gray-500 truncate mt-1",children:z.url})]})]}),l.jsx("a",{href:z.path,download:z.name,className:"shrink-0 p-3 rounded-lg border border-white/10 bg-white/5 text-white/80 hover:bg-white/10 hover:text-white transition-all flex items-center justify-center",title:"Download file","aria-label":"Download file",children:l.jsx(_e,{name:"download",className:"text-[18px]"})})]},U))}):q&&w==="table"?l.jsx("div",{className:"overflow-auto custom-scrollbar rounded-2xl border border-white/10",children:l.jsxs("table",{className:"min-w-full table-auto text-[10px] text-left text-white/80 font-mono",children:[l.jsx("thead",{className:"bg-white/5 text-[9px] uppercase tracking-widest text-white/50",children:l.jsx("tr",{children:q.headers.map(z=>l.jsx("th",{className:"px-3 py-2 border-b border-white/10 whitespace-nowrap",children:z},z))})}),l.jsx("tbody",{children:q.rows.map((z,U)=>l.jsx("tr",{className:"odd:bg-white/[0.02]",children:q.headers.map((te,ae)=>l.jsx("td",{className:"px-3 py-2 border-b border-white/5 align-top whitespace-normal break-words",children:ne(z[ae])},`${U}-${ae}`))},U))})]})}):l.jsx(Si,{readOnly:!0,value:P?.text||"",language:P?.language||"plain"})})})()})]})]})},Gp=R.memo(Kb),Ib=({isOpen:i,onToggle:u,results:r,pinnedResults:c,isExecuting:f,isHeadfulOpen:d,runId:h,onConfirm:m,onNotify:x,onPinResults:g,onUnpinResults:C,useNovnc:_})=>l.jsxs("div",{className:`fixed top-0 right-0 h-full w-[600px] max-w-[90vw] bg-[#080808] border-l border-white/10 shadow-2xl transition-transform duration-500 ease-in-out z-40 transform ${i?"translate-x-0":"translate-x-full"}`,children:[l.jsx("button",{onClick:u,className:"absolute top-1/2 -left-8 -translate-y-1/2 w-8 h-24 bg-[#111] border border-r-0 border-white/10 rounded-l-xl flex items-center justify-center cursor-pointer shadow-[-8px_0_15px_rgba(0,0,0,0.5)] transition-all hover:bg-white/5 hover:w-10 hover:-left-10 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":i?"Close Results Drawer":"Open Results Drawer",title:i?"Close Results Drawer":"Open Results Drawer",children:l.jsx(_e,{name:"drag_indicator",className:`text-white/30 text-xl transition-transform duration-500 ${i?"rotate-180":""}`})}),l.jsx("div",{className:"h-full w-full overflow-y-auto custom-scrollbar p-6",children:l.jsx(Gp,{results:r,pinnedResults:c,isExecuting:f,isHeadful:d,runId:h,onConfirm:m,onNotify:x,onPin:g,onUnpin:C,fullWidth:!0,useNovnc:_})})]}),Zb=({versionPreview:i,onClose:u,onRunSnapshot:r})=>i?l.jsx("div",{className:"fixed inset-0 z-[210] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",children:l.jsxs("div",{className:"glass-card w-full max-w-6xl rounded-[32px] border border-white/10 p-8 shadow-2xl flex flex-col max-h-[90vh]",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-white/5 pb-4 mb-6",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.3em]",children:"Task Snapshot"}),l.jsx("div",{className:"text-lg font-bold text-white",children:i.snapshot.name}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[new Date(i.timestamp).toLocaleString()," | ",i.snapshot.mode]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:u,className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Close"}),l.jsx("button",{onClick:()=>{r(i.snapshot),u()},className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white text-black hover:bg-white/90 transition-all",children:"Run Version"})]})]}),l.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 overflow-y-auto custom-scrollbar pr-2 flex-1 min-h-0",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:"Snapshot JSON"}),l.jsx(Si,{readOnly:!0,value:JSON.stringify(i.snapshot,null,2),language:"json",className:"min-h-[320px]"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:"Output"}),l.jsx("div",{className:"glass-card rounded-2xl p-6 border border-white/10 text-[10px] text-gray-500",children:"No output captured for this snapshot yet. Run this version to see results."})]})]})]})}):null,Xb=({isHeadfulOpen:i,isInspectMode:u,isInspectLoading:r,isExecuting:c,useNovnc:f,onToggleInspect:d,onStopHeadful:h})=>{const m=R.useRef(null);if(!i)return null;const{origin:x,hostname:g}=window.location,C=`${x}/novnc.html?host=${g}&path=websockify`,_=()=>{const A=m.current;if(A){if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}A.requestFullscreen?.().catch(()=>{})}};return l.jsx("div",{className:"fixed inset-0 z-[100] bg-black/40 backdrop-blur-md flex items-center justify-center p-8 pointer-events-auto",children:l.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[800px] bg-black/60 backdrop-blur-3xl border border-white/20 rounded-[32px] shadow-2xl overflow-hidden flex flex-col",children:[l.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between px-6 py-4 border-b border-white/10 bg-black/20 gap-4",children:[l.jsx("div",{className:"flex flex-col gap-1",children:l.jsx("div",{className:"flex items-center gap-3",children:l.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-white",children:"Active Browser Session"})})}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("button",{type:"button",onClick:d,disabled:r||c,className:`px-3 py-1.5 rounded-xl border text-[9px] font-bold uppercase tracking-widest transition-all flex items-center gap-2 disabled:opacity-30 disabled:cursor-not-allowed ${u?"border-green-500/30 bg-green-500/20 text-green-400 hover:bg-green-500/30":"border-white/10 text-white/60 hover:text-white hover:bg-white/10"}`,title:u?"Stop inspecting elements":"Highlight elements on hover",children:[r?l.jsx("div",{className:"w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"}):l.jsx(_e,{name:u?"visibility_off":"center_focus_strong",className:"text-[14px]"}),u?"Stop Inspect":"Inspect UI"]}),l.jsx("button",{type:"button",onClick:_,className:"p-2 text-white/60 hover:text-white transition-colors",title:"Toggle fullscreen",children:l.jsx(_e,{name:"fullscreen",className:"text-[16px]"})}),l.jsx("button",{type:"button",onClick:h,className:"p-2 text-white/60 hover:text-white transition-colors",title:"Close Browser",children:l.jsx(_e,{name:"close",className:"text-[16px]"})})]})]}),l.jsx("div",{ref:m,className:"flex-1 relative bg-black flex items-center justify-center",children:f===!1?l.jsxs("div",{className:"text-center p-8",children:[l.jsx(_e,{name:"open_in_new",className:"text-6xl text-white/20 mb-4 block"}),l.jsx("h3",{className:"text-white text-lg font-bold mb-2",children:"Browser Opened Natively"}),l.jsx("p",{className:"text-white/60 text-sm max-w-md mx-auto leading-relaxed mb-6",children:"The headful browser has been launched in a separate window on your desktop. Use that window to pick selectors. It will automatically sync back here."}),l.jsxs("div",{className:"text-[11px] text-amber-500/80 max-w-md mx-auto bg-amber-500/10 p-4 rounded-xl border border-amber-500/20 text-left",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-2 font-bold uppercase tracking-widest text-amber-500",children:[l.jsx(_e,{name:"warning",className:"text-base"}),l.jsx("span",{children:"Warning"})]}),"Figranium is not optimized for native browser windows. On ",l.jsx("strong",{children:"Wayland displays"}),", you ",l.jsx("strong",{children:"HAVE TO use Docker"}),", or you will have to deal with the problems of a physical browser losing focus or failing to capture clicks.",l.jsx("br",{}),l.jsx("br",{}),"For maximum stability, please install the proper tools (Xvfb, x11vnc, websockify) or use the official Docker image."]})]}):l.jsx("iframe",{src:C,className:"absolute inset-0 w-full h-full border-0",title:"Headful Browser"})})]})})},sa=({value:i,onChange:u,onBlur:r,placeholder:c,variables:f,className:d,syntax:h="plain"})=>{const m=R.useRef(null);return R.useEffect(()=>{if(m.current){const x=m.current.innerHTML,g=qp(i,h,f);if(x!==g){const C=window.getSelection();let _=0;if(C&&C.rangeCount>0){const A=C.getRangeAt(0),w=A.cloneRange();w.selectNodeContents(m.current),w.setEnd(A.endContainer,A.endOffset),_=w.toString().length}if(m.current.innerHTML=g,_>0){const A=document.createTreeWalker(m.current,NodeFilter.SHOW_TEXT);let w=0,N=A.nextNode();for(;N;){const p=N.textContent?.length||0;if(w+p>=_){const b=document.createRange();b.setStart(N,_-w),b.collapse(!0),C?.removeAllRanges(),C?.addRange(b);break}w+=p,N=A.nextNode()}}}}},[i,f]),l.jsx("div",{ref:m,contentEditable:!0,className:`rich-input-content w-full bg-transparent focus:outline-none text-white min-h-[1.5rem] ${d}`,"data-placeholder":c,onInput:x=>u(x.currentTarget.textContent||""),onBlur:x=>{const g=x.currentTarget.textContent||"";u(g),r?.(g)}})},$b=[{value:"Control",label:"Ctrl"},{value:"Shift",label:"Shift"},{value:"Alt",label:"Alt"},{value:"Meta",label:"Meta"}],Qb=["Enter","Tab","Escape","Space","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","F1","F2","F3","F4","F5"].concat([...Array(10)].map((i,u)=>`${u}`)).concat(Array.from({length:26},(i,u)=>String.fromCharCode(65+u))),Jb=[{value:"replace",label:"Replace Text"},{value:"append",label:"Append Text"}],Fb=i=>{if(!i)return{modifiers:[],baseKey:""};const u=i.split("+"),r=u.pop()||"";return{modifiers:u,baseKey:r}},cp=(i,u)=>[...i.filter(Boolean),u].filter(Boolean).join("+"),up=i=>{const u=(i||"").trim(),r=u.match(/^\{\$([\w.]+)\}$/);return r?r[1]:u},Pb=i=>{let u="";return i.type==="click"||i.type==="hover"||i.type==="scroll"||i.type==="wait_selector"?u=i.selector||"":i.type==="type"||i.type==="navigate"||i.type==="wait"||i.type==="javascript"||i.type==="repeat"||i.type==="start"||i.type==="screenshot"||i.type==="wait_downloads"||i.type==="stop"?u=i.value||"":i.type==="set"||i.type==="foreach"||i.type==="merge"?u=i.varName||"":i.type==="press"?u=i.key||"":(i.type==="if"||i.type==="while")&&(u=i.conditionVar||""),u.trim()},pn={string:[{value:"equals",label:"Equals"},{value:"not_equals",label:"Not equal"},{value:"contains",label:"Contains"},{value:"starts_with",label:"Starts with"},{value:"ends_with",label:"Ends with"},{value:"matches",label:"Matches regex"}],number:[{value:"equals",label:"Equals"},{value:"not_equals",label:"Not equal"},{value:"gt",label:"Greater than"},{value:"gte",label:"Greater or equal"},{value:"lt",label:"Less than"},{value:"lte",label:"Less or equal"}],boolean:[{value:"is_true",label:"Is true"},{value:"is_false",label:"Is false"}]},dp=R.memo(({action:i,index:u,status:r,isDragging:c,isDragOver:f,translateY:d,variables:h,availableTasks:m,onUpdate:x,onAutoSave:g,onOpenPalette:C,onOpenContextMenu:_,onPointerDown:A,dragTransformY:w,onStartInspect:N,isSelected:p,selectorOptions:b})=>{const[v,j]=R.useState(!1),k=r==="running"?"border-yellow-400/60":r==="success"?"border-green-400/60":r==="error"?"border-red-400/70":r==="skipped"?"border-gray-500/40":"",B=O=>{const X="text-[12px]";return O==="if"||O==="else"?l.jsx(_e,{name:"call_split",className:`${X} text-white`}):O==="end"?l.jsx(_e,{name:"subdirectory_arrow_right",className:`${X} text-gray-500`}):O==="while"||O==="repeat"?l.jsx(_e,{name:"repeat",className:`${X} text-white`}):O==="foreach"?l.jsx(_e,{name:"list",className:`${X} text-white`}):O==="on_error"?l.jsx(_e,{name:"warning",className:`${X} text-red-400`}):O==="set"?l.jsx(_e,{name:"data_object",className:`${X} text-white`}):O==="stop"?l.jsx(_e,{name:"stop",className:`${X} text-white`}):O==="click"?l.jsx(_e,{name:"ads_click",className:`${X} text-white`}):O==="type"?l.jsx(_e,{name:"text_format",className:`${X} text-white`}):O==="hover"?l.jsx(_e,{name:"my_location",className:`${X} text-white`}):O==="press"?l.jsx(_e,{name:"keyboard",className:`${X} text-white`}):O==="wait"?l.jsx(_e,{name:"schedule",className:`${X} text-white`}):O==="wait_selector"?l.jsx(_e,{name:"schedule",className:`${X} text-white`}):O==="scroll"?l.jsx(_e,{name:"swap_vert",className:`${X} text-white`}):O==="javascript"?l.jsx(_e,{name:"code",className:`${X} text-white`}):O==="csv"?l.jsx(_e,{name:"table_chart",className:`${X} text-white`}):O==="merge"?l.jsx(_e,{name:"layers",className:`${X} text-white`}):O==="screenshot"?l.jsx(_e,{name:"photo_camera",className:`${X} text-white`}):O==="start"?l.jsx(_e,{name:"play_circle",className:`${X} text-white`}):O==="navigate"?l.jsx(_e,{name:"navigation",className:`${X} text-white`}):l.jsx("span",{className:"text-[9px] text-white/20",children:"|"})},D=O=>!O||!(O instanceof HTMLElement)?!1:!!O.closest('input, textarea, select, button, a, [contenteditable="true"], [data-no-drag="true"]'),M=c?`translateY(${w||0}px)`:d?`translateY(${d}px)`:void 0;return l.jsxs("div",{id:`action-${i.id}`,"data-action-id":i.id,onPointerDown:O=>{D(O.target)||O.button===0&&(O.preventDefault(),A(O,i.id,u))},onContextMenu:O=>_(O,i.id),className:`bg-black min-w-[280px] w-full max-w-sm mx-auto border p-5 rounded-2xl space-y-4 group/item relative transition-[transform,box-shadow,opacity,filter,background-color,border-color] duration-150 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-transform select-none touch-none ${k||(p?"border-blue-500 ring-2 ring-blue-500/50":"border-white/20")} ${c?"ring-2 ring-white/40 scale-[1.02] shadow-[0_30px_80px_rgba(0,0,0,0.45)] opacity-85 z-20 mx-auto":""} ${f&&!c?"ring-2 ring-blue-400/60 bg-blue-500/5":""} ${i.disabled?"opacity-40 grayscale":""}`,style:{transform:M},children:[l.jsxs("div",{className:"flex items-center justify-between cursor-pointer",onClick:()=>j(!v),children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"text-[8px] font-bold text-white/20 font-mono tracking-tighter",children:(u+1).toString().padStart(2,"0")}),l.jsx("div",{className:"w-4 h-4 flex items-center justify-center",children:B(i.type)}),l.jsx("button",{onClick:O=>{O.stopPropagation(),C(i.id)},className:"action-type-select text-[10px] font-bold uppercase tracking-[0.2em] text-white focus:outline-none cursor-pointer rounded focus-visible:ring-2 focus-visible:ring-white/50","aria-label":`Change action type: ${i.type}`,children:Dc.find(O=>O.type===i.type)?.label||i.type}),!v&&l.jsx("span",{className:"ml-2 text-white/40 text-[9px] font-mono truncate max-w-[150px] pointer-events-none",children:Pb(i)})]}),l.jsx("div",{className:"flex items-center gap-2",children:l.jsx(_e,{name:v?"expand_less":"expand_more",className:"text-base text-gray-600"})})]}),v&&l.jsxs(l.Fragment,{children:[(i.type==="click"||i.type==="type"||i.type==="hover"||i.type==="wait_selector"||i.type==="scroll")&&l.jsxs("div",{className:"space-y-1.5 relative",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1 block",children:i.type==="scroll"?"Selector (Optional)":"Selector"}),l.jsxs("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all flex items-center gap-2 relative",children:[l.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[l.jsx(sa,{value:i.selector||"",onChange:O=>x(i.id,{selector:O}),onBlur:()=>g(),variables:h,placeholder:i.type==="scroll"?".scroll-container or leave empty":".btn-primary"}),b&&b.length>1&&l.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:b.map((O,X)=>l.jsx("button",{onClick:$=>{$.stopPropagation(),x(i.id,{selector:O},!0)},className:`text-[9px] px-1.5 py-0.5 rounded border transition-colors ${i.selector===O?"bg-blue-500/20 border-blue-500/50 text-blue-300":"bg-white/[0.02] border-white/10 text-white/40 hover:text-white/80 hover:bg-white/[0.05]"}`,title:"Use this alternative selector",children:O},X))})]}),l.jsx("button",{onClick:()=>{N&&N(i.id)},disabled:i.disabled,className:"text-white transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 flex items-center justify-center opacity-50 hover:opacity-100 shrink-0 disabled:opacity-20 disabled:hover:opacity-20 disabled:cursor-not-allowed rounded",title:"Pick Selector in Browser","aria-label":"Pick Selector in Browser",children:l.jsx(_e,{name:"my_location",className:"text-lg"})})]})]}),i.type==="scroll"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Scroll Speed (ms)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.key||"",onChange:O=>x(i.id,{key:O}),onBlur:()=>g(),variables:h,placeholder:"500"})})]}),(i.type==="navigate"||i.type==="type"||i.type==="wait"||i.type==="wait_selector"||i.type==="javascript"||i.type==="csv")&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:i.type==="navigate"?"URL":i.type==="type"?"Content":i.type==="wait"?"Seconds":i.type==="wait_selector"?"Timeout (Sec)":i.type==="csv"?"CSV Input":"Script"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:i.type==="javascript"?l.jsx(Si,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),language:"javascript",variables:h,className:"min-h-[120px]",placeholder:"return document.title"}):i.type==="csv"?l.jsx(Si,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),language:"plain",variables:h,className:"min-h-[120px]",placeholder:"name,age\\nAda,31"}):l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),variables:h,placeholder:i.type==="navigate"?"https://example.com":i.type==="type"?"Search keywords":i.type==="wait"?"3":i.type==="wait_selector"?"10":"400"})}),i.type==="type"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Mode"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx("select",{value:i.typeMode||"replace",onChange:O=>{x(i.id,{typeMode:O.target.value},!0)},className:"custom-select w-full bg-transparent border-none px-0 py-0 text-[11px] text-white",children:Jb.map(O=>l.jsx("option",{value:O.value,children:O.label},O.value))})})]})]}),i.type==="screenshot"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Label (Optional)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),onBlur:()=>g(),variables:h,placeholder:"checkout-step"})})]}),i.type==="press"&&(()=>{const{modifiers:O,baseKey:X}=Fb(i.key);return l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Key"}),l.jsx("div",{className:"grid grid-cols-2 gap-1 text-[10px] text-white",children:$b.map($=>l.jsxs("label",{className:"inline-flex items-center space-x-1",children:[l.jsx("input",{type:"checkbox",checked:O.includes($.value),onChange:oe=>{const ce=oe.target.checked?[...O,$.value]:O.filter(q=>q!==$.value);x(i.id,{key:cp(ce,X)},!0)},className:"h-3 w-3 rounded border border-white/30 bg-black/80"}),l.jsx("span",{className:"uppercase text-[9px] text-white/70",children:$.label})]},$.value))}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsxs("select",{value:X,onChange:$=>x(i.id,{key:cp(O,$.target.value)},!0),className:"custom-select w-full bg-transparent border-none px-0 py-0 text-[11px] text-white",children:[l.jsx("option",{value:"",children:"Select key"}),Qb.map($=>l.jsx("option",{value:$,children:$},$))]})})]})})(),i.type==="if"&&(()=>{const O=Object.keys(h||{}),X=up(i.conditionVar||""),$=X&&h?.[X]?.type,oe=i.conditionVarType||$||"string",ce=pn[oe]||pn.string,q=i.conditionOp||ce[0].value;return l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Condition"}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Variable"}),l.jsx("input",{type:"text",list:`if-var-${i.id}`,value:i.conditionVar||"",onChange:P=>x(i.id,{conditionVar:P.target.value}),onBlur:()=>g(),placeholder:"variable name",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"}),O.length>0&&l.jsx("datalist",{id:`if-var-${i.id}`,children:O.map(P=>l.jsx("option",{value:P},P))})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Type"}),l.jsxs("select",{value:oe,onChange:P=>{const E=P.target.value,ne=pn[E]||pn.string;x(i.id,{conditionVarType:E,conditionOp:ne[0].value,conditionValue:E==="boolean"?"":i.conditionValue||""},!0)},className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:[l.jsx("option",{value:"string",children:"String"}),l.jsx("option",{value:"number",children:"Number"}),l.jsx("option",{value:"boolean",children:"Boolean"})]})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Relation"}),l.jsx("select",{value:q,onChange:P=>x(i.id,{conditionOp:P.target.value},!0),className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:ce.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))})]})]}),oe!=="boolean"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Value"}),l.jsx("input",{type:oe==="number"?"number":"text",value:i.conditionValue||"",onChange:P=>x(i.id,{conditionValue:P.target.value}),onBlur:()=>g(),placeholder:oe==="number"?"0":"value",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"})]})]})})(),i.type==="while"&&(()=>{const O=Object.keys(h||{}),X=up(i.conditionVar||""),$=X&&h?.[X]?.type,oe=i.conditionVarType||$||"string",ce=pn[oe]||pn.string,q=i.conditionOp||ce[0].value;return l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Condition"}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Variable"}),l.jsx("input",{type:"text",list:`while-var-${i.id}`,value:i.conditionVar||"",onChange:P=>x(i.id,{conditionVar:P.target.value}),onBlur:()=>g(),placeholder:"variable name",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"}),O.length>0&&l.jsx("datalist",{id:`while-var-${i.id}`,children:O.map(P=>l.jsx("option",{value:P},P))})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Type"}),l.jsxs("select",{value:oe,onChange:P=>{const E=P.target.value,ne=pn[E]||pn.string;x(i.id,{conditionVarType:E,conditionOp:ne[0].value,conditionValue:E==="boolean"?"":i.conditionValue||""},!0)},className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:[l.jsx("option",{value:"string",children:"String"}),l.jsx("option",{value:"number",children:"Number"}),l.jsx("option",{value:"boolean",children:"Boolean"})]})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Relation"}),l.jsx("select",{value:q,onChange:P=>x(i.id,{conditionOp:P.target.value},!0),className:"custom-select w-full bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[8px] font-bold uppercase text-white/60",children:ce.map(P=>l.jsx("option",{value:P.value,children:P.label},P.value))})]})]}),oe!=="boolean"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"text-[7px] font-bold text-gray-500 uppercase tracking-widest pl-1",children:"Value"}),l.jsx("input",{type:oe==="number"?"number":"text",value:i.conditionValue||"",onChange:P=>x(i.id,{conditionValue:P.target.value}),onBlur:()=>g(),placeholder:oe==="number"?"0":"value",className:"w-full bg-white/[0.05] border border-white/10 rounded-lg px-3 py-2 text-[10px] text-white"})]})]})})(),i.type==="repeat"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Times"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),variables:h,placeholder:"3"})})]}),i.type==="foreach"&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Selector (Optional)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.selector||"",onChange:O=>x(i.id,{selector:O}),variables:h,placeholder:".list-item"})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Variable (Array Name)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.varName||"",onChange:O=>x(i.id,{varName:O}),variables:h,placeholder:"items"})})]})]}),i.type==="set"&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Variable Name"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.varName||"",onChange:O=>x(i.id,{varName:O}),variables:h,placeholder:"status"})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Value"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),variables:h,placeholder:"ready"})})]})]}),i.type==="merge"&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Sources"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.value||"",onChange:O=>x(i.id,{value:O}),variables:h,placeholder:"items, extraItems, {$block.output}"})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Target Variable (Optional)"}),l.jsx("div",{className:"bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[11px] focus-within:border-white/20 transition-all",children:l.jsx(sa,{value:i.varName||"",onChange:O=>x(i.id,{varName:O}),variables:h,placeholder:"allItems"})})]})]}),i.type==="stop"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Outcome"}),l.jsxs("select",{value:i.value||"success",onChange:O=>x(i.id,{value:O.target.value},!0),className:"custom-select w-full bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[9px] font-bold uppercase tracking-[0.2em] text-white/70 focus:outline-none",children:[l.jsx("option",{value:"success",children:"Success"}),l.jsx("option",{value:"error",children:"Error"})]})]}),i.type==="on_error"&&l.jsx("div",{className:"text-[8px] text-gray-600 uppercase tracking-widest",children:"Runs if any action fails."}),i.type==="start"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[7px] font-bold text-gray-600 uppercase tracking-widest pl-1",children:"Task"}),l.jsxs("select",{value:i.value||"",onChange:O=>x(i.id,{value:O.target.value},!0),className:"custom-select w-full bg-white/[0.03] border border-white/5 rounded-xl px-3 py-2 text-[9px] font-bold uppercase tracking-[0.2em] text-white/70 focus:outline-none",children:[l.jsx("option",{value:"",disabled:!0,children:"Select task"}),m.length===0&&l.jsx("option",{value:"",disabled:!0,children:"No other tasks"}),m.map(O=>l.jsx("option",{value:O.id,children:O.name||O.id},O.id))]})]})]})]})}),Wb=({currentTask:i,setCurrentTask:u,canvasOffset:r,canvasScale:c,canvasViewportRef:f,triggerExpanded:d,setTriggerExpanded:h,onOpenCabinet:m,handleAutoSave:x,dragState:g,dragOverIndex:C,selectedActionIds:_,actionStatusById:A,availableTasks:w,selectorOptionsById:N,updateAction:p,openActionPalette:b,openContextMenu:v,handleActionPointerDown:j,onOpenHeadful:k,isHeadfulOpen:B,onPointerDown:D,onPointerMove:M,onPointerUp:O,onPointerCancel:X,selectionBox:$})=>{const oe=(ce,q,P=0)=>{const E=[];let ne=ce;for(;ne<q;){const Q=ne,Z=i.actions[Q];if(!Z){ne++;continue}if(Z.type==="if"||Z.type==="while"){const we=ne;let F=1,he=ne+1,z=-1;for(;he<q&&F>0;){const Ne=i.actions[he];if((Ne.type==="if"||Ne.type==="while")&&F++,Ne.type==="end"&&(F--,F===0))break;Ne.type==="else"&&F===1&&Z.type==="if"&&(z=he),he++}const U=he,te=we+1,ae=z!==-1?z:U,Y=z!==-1?z+1:-1,me=z!==-1?U:-1;E.push(l.jsxs("div",{className:"flex flex-col items-center w-full",children:[l.jsx("div",{className:"w-[360px]",children:l.jsx(dp,{action:Z,index:Q,isDragOver:C===Q&&g?.id!==Z.id,isDragging:g?.id===Z.id,dragTransformY:g?.id===Z.id?g.currentY-g.startY:void 0,isSelected:_.has(Z.id),status:A[Z.id],translateY:0,variables:i.variables,availableTasks:w,selectorOptions:N[Z.id],onUpdate:p,onAutoSave:x,onOpenPalette:b,onOpenContextMenu:v,onPointerDown:j,onStartInspect:Ne=>{B||k?.(i.url||"https://www.google.com",Ne,i,i.variables)}})}),l.jsxs("div",{className:"flex gap-16 mt-4 relative",children:[l.jsxs("div",{className:"flex flex-col items-center min-w-[200px]",children:[l.jsx("div",{className:"text-[8px] font-bold text-white/60 uppercase tracking-widest mb-2",children:Z.type==="while"?"Loop":"True"}),l.jsx("div",{className:"w-px h-6 bg-white/25"}),l.jsx("div",{className:"flex flex-col items-center gap-3",children:oe(te,ae,P+1)}),l.jsxs("div",{className:"mt-2 flex flex-col items-center",children:[l.jsx("div",{className:"w-px h-4 bg-white/20"}),l.jsx("button",{onClick:()=>b(void 0,ae),className:"w-12 h-12 border border-dashed border-white/15 rounded-xl hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-lg text-gray-500 group-hover:text-white transition-colors"})})]})]}),Z.type==="if"&&l.jsxs("div",{className:"flex flex-col items-center min-w-[200px]",children:[l.jsx("div",{className:"text-[8px] font-bold text-white/60 uppercase tracking-widest mb-2",children:"Otherwise"}),l.jsx("div",{className:"w-px h-6 bg-white/25"}),l.jsx("div",{className:"flex flex-col items-center gap-3",children:Y!==-1?oe(Y,me,P+1):null}),l.jsxs("div",{className:"mt-2 flex flex-col items-center",children:[l.jsx("div",{className:"w-px h-4 bg-white/20"}),l.jsx("button",{onClick:()=>{if(Y!==-1)b(void 0,me);else{const Ne={id:"act_"+Date.now()+"_else",type:"else",selector:"",value:""},ke=[...i.actions];ke.splice(U,0,Ne),u({...i,actions:ke}),x({...i,actions:ke}),setTimeout(()=>b(void 0,U+1),50)}},className:"w-12 h-12 border border-dashed border-white/15 rounded-xl hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-lg text-gray-500 group-hover:text-white transition-colors"})})]})]})]}),l.jsxs("div",{className:"flex flex-col items-center mt-3",children:[l.jsx("div",{className:"w-px h-2 bg-white/25"}),l.jsx("button",{onClick:()=>b(void 0,U+1),className:"w-8 h-8 border border-dashed border-white/10 rounded-lg hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-sm text-gray-600 group-hover:text-white transition-colors"})}),l.jsx("div",{className:"w-px h-2 bg-white/25"})]})]},Z.id)),ne=U+1}else Z.type==="end"||Z.type==="else"||E.push(l.jsxs("div",{className:"flex flex-col items-center",children:[l.jsx("div",{className:"w-[360px]",children:l.jsx(dp,{action:Z,index:Q,isDragOver:C===Q&&g?.id!==Z.id,isDragging:g?.id===Z.id,dragTransformY:g?.id===Z.id?g.currentY-g.startY:void 0,isSelected:_.has(Z.id),status:A[Z.id],translateY:0,variables:i.variables,availableTasks:w,selectorOptions:N[Z.id],onUpdate:p,onAutoSave:x,onOpenPalette:b,onOpenContextMenu:v,onPointerDown:j,onStartInspect:we=>{B||k?.(i.url||"https://www.google.com",we,i,i.variables)}})}),ne<q-1&&i.actions[ne+1]?.type!=="end"&&l.jsxs("div",{className:"flex flex-col items-center my-1",children:[l.jsx("div",{className:"w-px h-2 bg-white/25"}),l.jsx("button",{onClick:()=>b(void 0,Q+1),className:"w-8 h-8 border border-dashed border-white/10 rounded-lg hover:border-white/30 hover:bg-white/5 transition-all flex items-center justify-center group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":"Add action",children:l.jsx(_e,{name:"add",className:"text-sm text-gray-600 group-hover:text-white transition-colors"})}),l.jsx("div",{className:"w-px h-2 bg-white/25"})]})]},Z.id)),ne++}return E};return l.jsxs("div",{ref:f,className:"flex-1 overflow-hidden relative cursor-grab active:cursor-grabbing select-none",style:{touchAction:"none"},onPointerDown:D,onPointerMove:M,onPointerUp:O,onPointerCancel:X,children:[l.jsxs("div",{className:"absolute origin-top-left",style:{transform:`translate(${r.x}px, ${r.y}px) scale(${c})`},children:[l.jsx("div",{className:"absolute pointer-events-none z-0",style:{inset:"-1000vw -1000vh",backgroundImage:`radial-gradient(circle, rgba(255,255,255,0.3) ${.8/c}px, transparent 0)`,backgroundSize:"20px 20px"}}),l.jsxs("div",{className:"flex flex-col items-center",style:{paddingTop:"60px",minWidth:"500px"},children:[l.jsxs("div",{className:"w-[360px] bg-black border border-white/15 p-5 rounded-2xl shadow-2xl shadow-black/50 select-text cursor-auto relative z-10",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3 cursor-pointer",onClick:()=>h(!d),children:[l.jsx(_e,{name:"bolt",className:"text-white/40 text-base"}),l.jsx("h3",{className:"text-white/60 font-bold tracking-widest uppercase text-[10px]",children:"On Execution"}),l.jsx(_e,{name:d?"expand_less":"expand_more",className:"text-xs text-gray-600"})]}),l.jsx("button",{onClick:()=>m("mode"),className:"p-2 rounded-lg hover:bg-white/10 text-white/30 hover:text-white transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"Task Settings","aria-label":"Task Settings",children:l.jsx(_e,{name:"settings",className:"text-lg"})})]}),d&&l.jsxs("div",{className:"space-y-4 mt-4 pt-3 border-t border-white/10",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"URL"}),l.jsx("div",{className:"w-full bg-[#111] border border-white/10 rounded-lg px-3 py-2 text-sm focus-within:border-white/30 transition-all",children:l.jsx(sa,{value:i.url,onChange:ce=>u({...i,url:ce}),onBlur:()=>x(),variables:i.variables,placeholder:"https://..."})})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Wait (sec)"}),l.jsx("input",{type:"number",value:i.wait,onChange:ce=>u({...i,wait:parseFloat(ce.target.value)||0}),onBlur:()=>x(),className:"w-full bg-[#111] border border-white/10 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/30 transition-all text-white"})]})]})]}),i.mode==="agent"&&l.jsx("div",{className:"w-px h-10 bg-white/25"}),i.mode==="agent"&&l.jsx("div",{className:"flex flex-col items-center w-full select-text cursor-auto",children:l.jsxs("div",{className:"space-y-6 w-full flex flex-col items-center relative",children:[oe(0,i.actions.length),l.jsxs("div",{className:"pt-2 flex flex-col items-center",children:[l.jsx("div",{className:"w-px h-6 bg-white/10"}),l.jsxs("button",{onClick:()=>b(),className:"w-[360px] bg-[#0a0a0a] border border-dashed border-white/15 rounded-2xl p-6 hover:border-white/30 hover:bg-white/[0.03] transition-all flex flex-col items-center justify-center gap-2 group cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/5 group-hover:bg-white/10 transition-all flex items-center justify-center",children:l.jsx(_e,{name:"add",className:"text-2xl text-gray-500 group-hover:text-white transition-colors"})}),l.jsx("span",{className:"text-[9px] font-bold uppercase tracking-[0.2em] text-gray-500 group-hover:text-gray-300 transition-colors",children:"Add Action"})]})]})]})})]})]}),$&&l.jsx("div",{className:"fixed inset-0 pointer-events-none z-20 overflow-hidden",children:l.jsx("div",{className:"absolute bg-blue-500/10 border border-blue-400",style:{left:Math.min($.startX,$.currentX),top:Math.min($.startY,$.currentY),width:Math.abs($.currentX-$.startX),height:Math.abs($.currentY-$.startY)}})})]})},Kp=({currentTask:i,setCurrentTask:u,tasks:r=[],isExecuting:c,onSave:f,onRun:d,results:h,pinnedResults:m,onConfirm:x,onNotify:g,onPinResults:C,onUnpinResults:_,onRunSnapshot:A,runId:w,onStop:N,isHeadfulOpen:p,onOpenHeadful:b,onStopHeadful:v,useNovnc:j})=>{const k=ob();cb(i,K=>u(K),(K,I)=>f(K,I));const B=ub(i,u,(K,I)=>f(K,I)),D=db(i,g,x,K=>u(K)),M=fb(i,p,B.updateAction,g,v),{proxyList:O,proxyListLoaded:X}=hb(),[$,oe]=R.useState(null),[,ce]=R.useState(null),[q,P]=R.useState(!1),[E,ne]=R.useState(!1),[Q,Z]=R.useState("mode"),[we,F]=R.useState(null),[he,z]=R.useState(""),[U,te]=R.useState(null),[ae,Y]=R.useState(null),[me,Ne]=R.useState({}),[ke,Ae]=R.useState(!1),[Ue,Ie]=R.useState(!1);R.useEffect(()=>{if(!w||i.mode!=="agent")return;Ne({});const K=new EventSource(`/api/executions/stream?runId=${encodeURIComponent(w)}`,{withCredentials:!0});return K.onmessage=I=>{if(I.data)try{const H=JSON.parse(I.data);H&&H.actionId&&H.status&&Ne(de=>({...de,[H.actionId]:H.status}))}catch{}},()=>K.close()},[w,i.mode]);const He=R.useCallback(K=>{f(K||i,!1)},[f,i]),ct=(K="mode")=>{Z(K),K==="history"&&D.loadVersions(),ne(!0)},S=R.useCallback((K,I)=>{P(!0),z(""),te(K||null),Y(I!==void 0?I:null)},[]),pe=K=>{const I=K.tagName.toLowerCase();return I==="input"||I==="textarea"||K.isContentEditable||K.closest('[data-interactive-target="true"]')};R.useEffect(()=>{const K=I=>{if(!pe(I.target))if(I.key==="Backspace"||I.key==="Delete"){if(B.selectedActionIds.size>0){I.preventDefault();let H=[...i.actions];B.selectedActionIds.forEach(be=>{const fe=H.findIndex(Ee=>Ee.id===be);if(fe!==-1){const Ee=H[fe];if(Ee.type==="if"||Ee.type==="while"){let De=1;for(let Oe=fe+1;Oe<H.length;Oe++)if((H[Oe].type==="if"||H[Oe].type==="while")&&De++,H[Oe].type==="end"&&De--,De===0){H.splice(Oe,1);break}}H.splice(fe,1)}});const de={...i,actions:H};u(de),He(de),B.setSelectedActionIds(new Set)}}else(I.ctrlKey||I.metaKey)&&I.key==="a"?(I.preventDefault(),B.setSelectedActionIds(new Set(i.actions.map(H=>H.id)))):(I.metaKey||I.ctrlKey)&&I.key==="k"&&(I.preventDefault(),q||S())};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[B,i,He,q,S,u]);const le=R.useCallback((K,I)=>{K.preventDefault();const H=8,de=200,be=190,fe=Math.min(Math.max(K.clientX+12,H),window.innerWidth-de-H),Ee=Math.min(Math.max(K.clientY+12,H),window.innerHeight-be-H);oe({id:I,x:fe,y:Ee})},[]),V=K=>({...K,id:"act_"+Date.now()+"_"+Math.floor(Math.random()*1e3)}),L=K=>{const I={id:"act_"+Date.now(),type:K,selector:"",value:""};if((K==="set"||K==="merge")&&(I.varName=""),K==="start"&&(I.value=""),K==="type"&&(I.typeMode="replace"),K==="if"||K==="while"){I.conditionVar="",I.conditionVarType="string",I.conditionOp="equals",I.conditionValue="";const H={id:"act_"+Date.now()+"_end",type:"end",selector:"",value:""},de={...i,actions:[...i.actions,I,H]};u(de),He(de)}else{K==="wait_downloads"&&(I.value="30");const H={...i,actions:[...i.actions,I]};u(H),He(H)}},W=R.useMemo(()=>r.filter(K=>String(K.id||"")!==String(i.id||"")),[r,i.id]);return l.jsxs("div",{className:"flex-1 flex overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500 bg-black relative",children:[l.jsx(pb,{currentTask:i,onUpdateTaskName:K=>u({...i,name:K}),onAutoSave:He,onOpenHistory:()=>ct("history")}),l.jsx(Wb,{currentTask:i,setCurrentTask:u,canvasOffset:k.canvasOffset,canvasScale:k.canvasScale,canvasViewportRef:k.canvasViewportRef,triggerExpanded:Ue,setTriggerExpanded:Ie,onOpenCabinet:ct,handleAutoSave:He,dragState:B.dragState,dragOverIndex:B.dragOverIndex,selectedActionIds:B.selectedActionIds,setSelectedActionIds:B.setSelectedActionIds,actionStatusById:me,availableTasks:W,selectorOptionsById:M.selectorOptionsById,updateAction:B.updateAction,openActionPalette:S,openContextMenu:le,handleActionPointerDown:B.handleActionPointerDown,onOpenHeadful:(K,I)=>{M.setActiveInspectActionId(I||null),b?.(K,I,i,i.variables)},isHeadfulOpen:p,onPointerDown:K=>{if(K.button===1||K.button===0&&k.spaceHeldRef.current)k.startPanning(K);else if(K.button===0&&!pe(K.target)){if(K.target.closest("[data-action-id]"))return;F({startX:K.clientX,startY:K.clientY,currentX:K.clientX,currentY:K.clientY}),!K.shiftKey&&!K.ctrlKey&&!K.metaKey&&B.setSelectedActionIds(new Set),K.target.setPointerCapture?.(K.pointerId)}},onPointerMove:K=>{if(k.isPanning.current)k.handlePanning(K.nativeEvent);else if(we){F(be=>be?{...be,currentX:K.clientX,currentY:K.clientY}:null);const I={left:Math.min(we.startX,K.clientX),right:Math.max(we.startX,K.clientX),top:Math.min(we.startY,K.clientY),bottom:Math.max(we.startY,K.clientY)},H=document.querySelectorAll("[data-action-id]"),de=new Set(K.shiftKey||K.ctrlKey||K.metaKey?Array.from(B.selectedActionIds):[]);H.forEach(be=>{const fe=be.getBoundingClientRect();!(fe.right<I.left||fe.left>I.right||fe.bottom<I.top||fe.top>I.bottom)&&de.add(be.getAttribute("data-action-id"))}),B.setSelectedActionIds(de)}},onPointerUp:()=>{k.stopPanning(),F(null)},onPointerCancel:()=>{k.stopPanning(),F(null)},selectionBox:we}),l.jsxs("div",{className:"absolute bottom-24 left-6 z-30 flex flex-col gap-1 bg-[#111] border border-white/10 rounded-xl p-1 shadow-xl",children:[l.jsx("button",{onClick:()=>k.setCanvasScale(Math.min(2,k.canvasScale*1.2)),className:"w-8 h-8 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center text-sm font-bold",children:"+"}),l.jsxs("div",{className:"text-[8px] text-center text-gray-500 font-bold select-none",children:[Math.round(k.canvasScale*100),"%"]}),l.jsx("button",{onClick:()=>k.setCanvasScale(Math.max(.25,k.canvasScale*.8)),className:"w-8 h-8 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center text-sm font-bold",children:"−"}),l.jsx("button",{onClick:()=>{k.setCanvasScale(1);const K=k.canvasViewportRef.current;k.setCanvasOffset({x:((K?K.clientWidth:1e3)-400)/2,y:20})},className:"w-8 h-8 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all flex items-center justify-center",children:l.jsx(_e,{name:"fit_screen",className:"text-sm"})})]}),$&&(()=>{const K=i.actions.findIndex(be=>be.id===$.id),I=i.actions[K];if(!I)return null;const H=B.selectedActionIds.has(I.id)&&B.selectedActionIds.size>1,de=H?Array.from(B.selectedActionIds):[I.id];return l.jsxs("div",{className:"action-context-menu fixed z-50 w-[200px] bg-[#0b0b0b] border border-white/10 rounded-xl shadow-2xl p-2 text-[10px] font-bold uppercase tracking-widest text-white/80",style:{left:$.x,top:$.y},children:[l.jsxs("button",{onClick:()=>{const be=!I.disabled,fe=i.actions.map(De=>de.includes(De.id)?{...De,disabled:be}:De),Ee={...i,actions:fe};u(Ee),He(Ee),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:[I.disabled?"Enable":"Disable"," ",H?"All":""]}),l.jsxs("button",{onClick:()=>{const be=i.actions.filter(Ee=>!de.includes(Ee.id)),fe={...i,actions:be};u(fe),He(fe),oe(null),B.setSelectedActionIds(new Set)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors text-red-400",children:["Delete ",H?"All":""]}),l.jsx("button",{onClick:()=>{ce(V(I)),B.removeAction(I.id),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:"Cut"}),l.jsx("button",{onClick:()=>{ce(V(I)),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:"Copy"}),l.jsxs("button",{onClick:()=>{const fe=i.actions.filter(Oe=>de.includes(Oe.id)).map(Oe=>V(Oe)),Ee=[...i.actions];Ee.splice(K+1,0,...fe);const De={...i,actions:Ee};u(De),He(De),oe(null)},className:"w-full text-left px-3 py-2 rounded-lg hover:bg-white/5 transition-colors",children:["Duplicate ",H?"All":""]})]})})(),l.jsx(eb,{open:q,query:he,onQueryChange:z,onClose:()=>P(!1),onSelect:K=>{if(U)B.updateAction(U,{type:K},!0);else if(ae!==null){const I={id:"act_"+Date.now(),type:K,selector:"",value:""};(K==="set"||K==="merge")&&(I.varName=""),K==="start"&&(I.value=""),K==="type"&&(I.typeMode="replace"),(K==="if"||K==="while")&&(I.conditionVar="",I.conditionVarType="string",I.conditionOp="equals",I.conditionValue=""),K==="wait_downloads"&&(I.value="30");const H=[...i.actions];if(K==="if"||K==="while"){const be={id:"act_"+Date.now()+"_end",type:"end",selector:"",value:""};H.splice(ae,0,I,be)}else H.splice(ae,0,I);const de={...i,actions:H};u(de),He(de)}else L(K);P(!1),Y(null)}}),l.jsx(Ib,{isOpen:ke,onToggle:()=>Ae(!ke),results:h,pinnedResults:m,isExecuting:c,isHeadfulOpen:p||!1,runId:w,onConfirm:x,onNotify:g,onPinResults:C,onUnpinResults:_,useNovnc:j}),l.jsx(Zb,{versionPreview:D.versionPreview,onClose:()=>D.setVersionPreview(null),onRunSnapshot:A}),l.jsx(Xb,{isHeadfulOpen:p||!1,isInspectMode:M.isInspectMode,isInspectLoading:M.isInspectLoading,isExecuting:c,useNovnc:j,onToggleInspect:M.handleToggleInspect,onStopHeadful:()=>v?.()}),l.jsx(mb,{isExecuting:c,isHeadfulOpen:p||!1,onRun:()=>{Ae(!0),d()},onStop:N,onOpenHeadful:()=>b?.(i.url||"https://www.google.com",void 0,i,i.variables),onStopHeadful:v}),l.jsx(rb,{isOpen:E,onClose:()=>ne(!1),currentTask:i,onUpdateTask:K=>{const I={...i,...K};u(I),He(I)},proxyListLoaded:X,proxyList:O,initialTab:Q,versions:D.versions,versionsLoading:D.versionsLoading,onRollback:D.rollbackToVersion,onPreview:D.openVersionPreview})]})},ey=({config:i,onConfirm:u})=>{const[r,c]=R.useState(i.startEditing||!1),[f,d]=R.useState(i.startEditing&&i.value||""),[h,m]=R.useState(!1),x=()=>{d(i.value||""),m(!1),c(!0)},g=()=>{c(!1),d(""),m(!1)},C=async()=>{const w=f.trim();await i.onSave(w),c(!1)},_=async()=>{i.onRegenerate&&await i.onRegenerate()},A=i.loading?"Loading...":i.value?"••••••••••••••••••••••••••••••••••••••••":"No key set";return l.jsxs("div",{className:"flex flex-col gap-4 py-4 border-b border-white/5 last:border-0",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-blue-400 overflow-hidden",children:i.iconUrl?l.jsx("img",{src:i.iconUrl,alt:i.name,className:"w-6 h-6 object-contain"}):i.iconComponent?l.jsx(i.iconComponent,{className:"w-5 h-5"}):l.jsx(_e,{name:i.icon||"key",className:"text-xl"})}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"text-sm font-bold text-white uppercase tracking-widest",children:i.name}),i.badge&&l.jsx("span",{className:`text-[8px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full ${i.badge==="Primary"?"bg-blue-500/20 text-blue-400 border border-blue-500/30":"bg-white/10 text-white/50 border border-white/10"}`,children:i.badge})]}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:i.description})]})]}),r?l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"flex-1 flex items-center gap-3 rounded-2xl bg-black/40 border border-white/30 focus-within:border-white px-4 py-2 transition-all",children:[l.jsx("input",{type:h?"text":"password",value:f,onChange:w=>d(w.target.value),disabled:i.saving,placeholder:"Enter new API key...",className:"flex-1 bg-transparent text-[10px] text-white font-mono focus:outline-none",autoFocus:!0}),l.jsx("button",{onClick:()=>m(!h),type:"button",className:"p-2 rounded-xl text-white/50 hover:text-white hover:bg-white/10 transition-all",title:h?"Hide value":"Show value","aria-label":h?"Hide value":"Show value",children:l.jsx(_e,{name:h?"visibility_off":"visibility",className:"text-base"})})]}),l.jsx("button",{onClick:g,disabled:i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-transparent border border-white/20 text-white hover:bg-white/10 transition-all disabled:opacity-50",children:"Cancel"}),l.jsxs("button",{onClick:C,disabled:i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-blue-500 text-white hover:bg-blue-400 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[l.jsx(_e,{name:"save",className:"text-base"}),i.saving?"Saving...":"Save"]})]}):l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"flex-1 rounded-2xl bg-black/40 border border-white/10 px-4 py-3 font-mono text-[10px] text-blue-200/80 break-all min-h-[44px] flex items-center",children:l.jsx("span",{className:"opacity-80 select-none",children:A})}),!i.readOnly&&l.jsxs("button",{onClick:x,disabled:i.loading||i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-white/10 text-white hover:bg-white/20 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[l.jsx(_e,{name:"edit",className:"text-base"}),"Edit"]}),i.onRegenerate&&l.jsxs("button",{onClick:_,disabled:i.loading||i.saving,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-white text-black hover:scale-105 transition-all disabled:opacity-50 disabled:hover:scale-100 disabled:cursor-not-allowed flex items-center gap-2",children:[l.jsx(_e,{name:"autorenew",className:"text-base"}),i.saving?"Generating...":"Regenerate"]}),i.showCopyButton&&i.value&&l.jsx(Ws,{text:i.value,className:"p-3 rounded-2xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",iconClassName:"text-base"}),i.onDelete&&l.jsx("button",{onClick:async()=>{(u?await u(`Are you sure you want to delete the ${i.name}?`):confirm(`Are you sure you want to delete the ${i.name}?`))&&await i.onDelete?.()},disabled:i.loading||i.saving,className:"p-3 rounded-2xl bg-white/5 border border-white/10 text-red-400 hover:bg-red-500/20 hover:border-red-500/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed",title:"Delete Key","aria-label":"Delete Key",children:l.jsx(_e,{name:"delete",className:"text-base"})})]})]})},ty=({keys:i,availableProviders:u,onAddProvider:r,dbProviders:c,onAddDbCredential:f,onConfirm:d})=>{const[h,m]=R.useState(!1),[x,g]=R.useState("list"),[C,_]=R.useState(null),[A,w]=R.useState({name:"",baseUrl:"https://api.baserow.io",token:""}),[N,p]=R.useState(!1),[b,v]=R.useState(null),j=u&&u.length>0&&r||c&&c.length>0&&f,k=()=>{m(!1),g("list"),_(null),w({name:"",baseUrl:"https://api.baserow.io",token:""}),v(null)},B=M=>{_(M),g("db-form"),v(null)},D=async()=>{if(!(!C||!A.name||!A.token||!f)){p(!0),v(null);try{await f({name:A.name,provider:C.providerKey,config:{baseUrl:A.baseUrl,token:A.token}})?k():v("Failed to save credential. Check the server console for details.")}catch(M){console.error("[ApiKeysPanel] handleDbSave error:",M),v("An unexpected error occurred.")}finally{p(!1)}}};return R.useEffect(()=>{if(h){document.body.style.overflow="hidden";const M=document.querySelector("main");M&&(M.style.overflow="hidden")}else{document.body.style.overflow="";const M=document.querySelector("main");M&&(M.style.overflow="")}return()=>{document.body.style.overflow="";const M=document.querySelector("main");M&&(M.style.overflow="")}},[h]),l.jsxs("div",{className:"glass-card p-8 rounded-[40px]",children:[l.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-bold text-white uppercase tracking-widest",children:"API Keys"}),l.jsx("p",{className:"text-[10px] text-gray-400 uppercase tracking-widest mt-1",children:"Manage external integrations and API access"})]}),j&&l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>m(!0),className:"px-6 py-3 rounded-2xl text-[10px] font-bold uppercase tracking-widest bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-all flex items-center gap-2 border border-blue-500/10",children:[l.jsx(_e,{name:"add",className:"text-base"}),"Add API Key"]}),h&&Xg.createPortal(l.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/80 backdrop-blur-md animate-in fade-in duration-200",style:{position:"fixed",top:0,left:0,right:0,bottom:0},onClick:M=>{M.target===M.currentTarget&&k()},children:l.jsxs("div",{className:"glass-card max-w-2xl w-full p-10 rounded-[40px] shadow-2xl relative border border-white/10 animate-in zoom-in-95 duration-300 bg-gray-900/80",children:[l.jsx("button",{onClick:k,className:"absolute top-6 right-6 p-3 rounded-2xl text-white/50 hover:text-white hover:bg-white/10 transition-all","aria-label":"Close",children:l.jsx(_e,{name:"close",className:"text-2xl"})}),x==="list"&&l.jsxs(l.Fragment,{children:[l.jsx("h3",{className:"text-2xl font-bold text-white tracking-wide mb-2",children:"Add Key"}),l.jsx("p",{className:"text-sm text-white/50 mb-8",children:"Choose what you'd like to add."}),u&&u.length>0&&r&&l.jsxs("div",{className:"mb-8",children:[l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em] mb-4",children:"AI Providers"}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:u.map(M=>l.jsxs("button",{onClick:()=>{M.disabled||(r(M.id),k())},disabled:M.disabled,className:`flex items-start gap-4 p-5 rounded-3xl border transition-all text-left ${M.disabled?"border-white/5 bg-white/5 opacity-40 cursor-not-allowed grayscale":"border-white/10 hover:border-blue-400/30 hover:bg-blue-500/5 cursor-pointer group"}`,children:[l.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 overflow-hidden ${M.disabled?"bg-black/20":"bg-white/5 group-hover:scale-110 transition-transform"}`,children:M.iconUrl?l.jsx("img",{src:M.iconUrl,alt:M.name,className:"w-8 h-8 object-contain drop-shadow-md"}):M.iconComponent?l.jsx(M.iconComponent,{className:"w-6 h-6 text-white"}):l.jsx(_e,{name:"api",className:"text-xl text-white"})}),l.jsxs("div",{className:"flex-1",children:[l.jsx("div",{className:"text-base font-bold text-white mb-1",children:M.name}),l.jsx("div",{className:"text-[10px] text-white/50 uppercase tracking-widest",children:M.disabled?"Coming Soon":"Available"})]})]},M.id))})]}),c&&c.length>0&&f&&l.jsxs("div",{children:[l.jsx("p",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em] mb-4",children:"Database / Output"}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:c.map(M=>l.jsxs("button",{onClick:()=>!M.disabled&&B(M),disabled:M.disabled,className:`flex items-start gap-4 p-5 rounded-3xl border transition-all text-left ${M.disabled?"border-white/5 bg-white/5 opacity-40 cursor-not-allowed grayscale":"border-white/10 hover:border-emerald-400/30 hover:bg-emerald-500/5 cursor-pointer group"}`,children:[l.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 overflow-hidden ${M.disabled?"bg-black/20":"bg-white/5 group-hover:scale-110 transition-transform"}`,children:M.iconUrl?l.jsx("img",{src:M.iconUrl,alt:M.name,className:"w-8 h-8 object-contain drop-shadow-md"}):l.jsx(_e,{name:"database",className:"text-xl text-white"})}),l.jsxs("div",{className:"flex-1",children:[l.jsx("div",{className:"text-base font-bold text-white mb-1",children:M.name}),l.jsx("div",{className:"text-[10px] text-white/50 uppercase tracking-widest",children:M.disabled?"Coming Soon":"Available"})]})]},M.providerKey))})]})]}),x==="db-form"&&C&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{onClick:()=>g("list"),className:"flex items-center gap-2 text-[10px] font-bold text-gray-500 hover:text-white uppercase tracking-widest mb-6 transition-colors",children:[l.jsx(_e,{name:"arrow_back",className:"text-sm"}),"Back"]}),l.jsxs("h3",{className:"text-2xl font-bold text-white tracking-wide mb-2",children:["Add ",C.name]}),l.jsxs("p",{className:"text-sm text-white/50 mb-8",children:["Enter your ",C.name," credentials."]}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("label",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Name"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/10 rounded-2xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-white/30 transition-colors",placeholder:"e.g. My Baserow",value:A.name,onChange:M=>w(O=>({...O,name:M.target.value})),autoFocus:!0})]}),C.providerKey==="baserow"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("label",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"Base URL"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/10 rounded-2xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-white/30 transition-colors",placeholder:"https://api.baserow.io",value:A.baseUrl,onChange:M=>w(O=>({...O,baseUrl:M.target.value}))})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("label",{className:"text-[9px] font-bold text-gray-500 uppercase tracking-[0.2em]",children:"API Token"}),l.jsx("input",{className:"w-full bg-black/40 border border-white/10 rounded-2xl px-4 py-3 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-white/30 transition-colors font-mono",placeholder:"Token",type:"password",value:A.token,onChange:M=>w(O=>({...O,token:M.target.value}))})]})]}),b&&l.jsx("p",{className:"mt-4 text-[10px] text-red-400 bg-red-500/10 border border-red-500/20 rounded-xl px-3 py-2",children:b}),l.jsxs("div",{className:"flex gap-3 mt-4",children:[l.jsx("button",{onClick:k,className:"px-6 py-3 rounded-2xl text-[10px] font-bold uppercase tracking-widest bg-transparent border border-white/10 text-gray-400 hover:text-white hover:border-white/20 transition-all",children:"Cancel"}),l.jsx("button",{onClick:D,disabled:N||!A.name||!A.token,className:"flex-1 py-3 rounded-2xl text-[10px] font-bold uppercase tracking-widest bg-white text-black hover:bg-white/90 transition-all disabled:opacity-40 disabled:cursor-not-allowed",children:N?"Saving…":"Save Credential"})]})]})]})}),document.body)]})]}),l.jsx("div",{className:"flex flex-col",children:i.map(M=>l.jsx(ey,{config:M,onConfirm:d},M.id))})]})},ay=({onClearStorage:i})=>l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"delete",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Storage"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Manage stored data"})]})]}),l.jsxs("div",{className:"flex gap-4",children:[l.jsx("button",{onClick:()=>i("screenshots"),className:"flex-1 px-6 py-4 bg-red-500/5 border border-red-500/10 text-red-400 rounded-2xl text-[9px] font-bold uppercase tracking-widest hover:bg-red-500/10 transition-all",children:"Clear Captures"}),l.jsx("button",{onClick:()=>i("cookies"),className:"flex-1 px-6 py-4 bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 rounded-2xl text-[9px] font-bold uppercase tracking-widest hover:bg-yellow-500/10 transition-all",children:"Reset Cookies"})]})]}),ny=72,Ip=6,Xs=ny+Ip,ly=5,iy=2,sy=({index:i,style:u,data:r})=>{const c=r.captures[i];return c?l.jsx("div",{style:{...u,paddingBottom:Ip},children:l.jsxs("div",{className:"flex items-center justify-between gap-4 p-4 rounded-2xl border border-white/10 bg-white/[0.02]",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest",children:c.type==="recording"?"Recording":"Screenshot"}),l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:c.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("a",{href:c.url,target:"_blank",rel:"noreferrer",className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all","aria-label":`Open ${c.name}`,children:"Open"}),l.jsx("button",{onClick:()=>r.onDelete(c.name),className:"px-3 py-2 rounded-xl border border-red-500/20 text-[9px] font-bold uppercase tracking-widest text-red-300 hover:bg-red-500/10 transition-all",children:"Delete"})]})]})}):null},ry=({captures:i,loading:u,onRefresh:r,onDelete:c})=>{const f=Math.min(Math.max(Xs,i.length*Xs),Xs*ly),d=R.useMemo(()=>({captures:i,onDelete:c}),[i,c]);return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Captures"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Recordings and screenshots"})]}),l.jsx("button",{onClick:r,disabled:u,className:"px-4 py-2 border border-white/10 text-[9px] font-bold rounded-xl uppercase tracking-widest text-white/70 hover:text-white hover:bg-white/5 transition-all disabled:opacity-50",children:"Refresh"})]}),u&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading captures..."}),!u&&i.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No captures found."}),!u&&i.length>0&&l.jsx(nr,{height:f,width:"100%",itemCount:i.length,itemSize:Xs,overscanCount:iy,itemData:d,children:sy})]})},Rc=i=>`${i.name}|${i.domain||""}|${i.path||""}|${i.expires||""}`,fp=i=>{if(!i)return!1;let u=0;for(let r=0;r<i.length;r+=1){const c=i.charCodeAt(r);(c===9||c===10||c===13||c>=32&&c<=126)&&(u+=1)}return u/i.length>=.85},oy=i=>{if(!i)return null;if(/%[0-9A-Fa-f]{2}/.test(i))try{const u=decodeURIComponent(i);if(u!==i&&fp(u))return{value:u,kind:"URL"}}catch{}if(/^[A-Za-z0-9+/=]+$/.test(i)&&i.length>=12&&i.length%4===0)try{const u=atob(i);if(u&&fp(u))return{value:u,kind:"Base64"}}catch{}return null},cy=({cookies:i,originsCount:u,loading:r,onClear:c,onDelete:f})=>{const[d,h]=R.useState({}),[m,x]=R.useState({}),g=A=>{const w=Rc(A);h(N=>({...N,[w]:!N[w]}))},C=A=>{const w=Rc(A);x(N=>({...N,[w]:!N[w]}))},_=R.useMemo(()=>i.map(A=>{const w=Rc(A),N=A.value||"";return{cookie:A,key:w,value:N,decodedCandidate:oy(N)}}),[i]);return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"database",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Cookies"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Browser storage state"})]})]}),l.jsx("button",{onClick:c,className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 hover:bg-yellow-500/10 transition-all",children:"Clear Cookies"})]}),r&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading data..."}),!r&&i.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No cookies found."}),l.jsx("div",{className:"space-y-3",children:_.map(({cookie:A,key:w,value:N,decodedCandidate:p})=>{const b=!!d[w],v=!!p&&!!m[w],j=v&&p?p.value:N,k=b||j.length<=120?j:`${j.slice(0,120)}...`;return l.jsxs("div",{className:"bg-white/5 border border-white/10 rounded-2xl p-4 space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest truncate",children:A.name}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[A.domain||"local"," | ",A.path||"/",A.expires?` | ${new Date(A.expires*1e3).toLocaleString()}`:""]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[p&&l.jsx("button",{onClick:()=>C(A),className:"px-3 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl border border-white/10 text-white/70 hover:text-white hover:bg-white/5 transition-all",children:v?"Show Raw":`Decode ${p.kind}`}),l.jsx("button",{onClick:()=>f(A),className:"px-3 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-red-500/5 border border-red-500/10 text-red-400 hover:bg-red-500/10 transition-all",children:"Delete"})]})]}),l.jsx("div",{onClick:()=>g(A),className:"cursor-pointer rounded-xl bg-black/40 border border-white/10 px-3 py-2 font-mono text-[10px] text-blue-200/80 whitespace-pre-wrap break-words",title:"Click to expand/collapse",children:k||"(empty)"})]},w)})}),!r&&u>0&&l.jsxs("div",{className:"pt-2 text-[8px] text-gray-600 uppercase tracking-widest",children:["Origins stored: ",u]})]})},uy=({tab:i,onTabChange:u})=>l.jsxs("div",{className:"flex items-end justify-between mb-8",children:[l.jsx("div",{className:"space-y-2",children:l.jsx("h2",{className:"text-4xl font-bold tracking-tighter text-white",children:"Settings"})}),l.jsx("div",{className:"flex bg-white/5 rounded-xl p-1 border border-white/5",children:["system","data","proxies"].map(r=>l.jsx("button",{onClick:()=>u(r),className:`px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-lg transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${i===r?"bg-white text-black":"text-gray-500 hover:text-white"}`,children:r},r))})]}),dy=({proxies:i,defaultProxyId:u,includeDefaultInRotation:r,rotationMode:c,loading:f,onRefresh:d,onAdd:h,onImport:m,onUpdate:x,onDelete:g,onDeleteMultiple:C,onSetDefault:_,onToggleIncludeDefault:A,onRotationModeChange:w})=>{const[N,p]=R.useState(""),[b,v]=R.useState(""),[j,k]=R.useState(""),[B,D]=R.useState(""),[M,O]=R.useState(!1),[X,$]=R.useState(""),[oe,ce]=R.useState(null),[q,P]=R.useState(""),[E,ne]=R.useState(""),[Q,Z]=R.useState(""),[we,F]=R.useState(""),[he,z]=R.useState(!1),[U,te]=R.useState(""),[ae,Y]=R.useState(""),[me,Ne]=R.useState(new Set),[ke,Ae]=R.useState(null),Ue=R.useRef(null),Ie=()=>{N.trim()&&(h({server:N.trim(),username:b.trim()||void 0,password:j.trim()||void 0,label:B.trim()||void 0,isRotatingPool:M,estimatedPoolSize:X?parseInt(X,10):void 0}),p(""),v(""),k(""),D(""),O(!1),$(""))},He=H=>{ce(H.id),P(H.server),ne(H.username||""),Z(""),F(H.label||""),z(!!H.isRotatingPool),te(H.estimatedPoolSize?String(H.estimatedPoolSize):"")},ct=()=>{ce(null),P(""),ne(""),Z(""),F(""),z(!1),te("")},S=()=>{!oe||!q.trim()||(x(oe,{server:q.trim(),username:E.trim()||void 0,password:Q.trim()||void 0,label:we.trim()||void 0,isRotatingPool:he,estimatedPoolSize:U?parseInt(U,10):void 0}),ct())},pe=H=>{const de=H.trim();if(!de)return null;if(de.includes("://"))return{server:de};const be=de.split(":");if(be.length<2)return null;const fe=be[0]?.trim(),Ee=be[1]?.trim();if(!fe||!Ee)return null;const De=be[2]?be[2].trim():"",Oe=be.length>3?be.slice(3).join(":").trim():"";return{server:`${fe}:${Ee}`,username:De||void 0,password:Oe||void 0}},le=async H=>{const de=Array.from(H.target.files||[]);if(de.length)try{const Ee=(await Promise.all(de.map(De=>De.text()))).join(`
|
|
15
|
+
`).split(/\r?\n/).flatMap(De=>De.split(/[,;]+/)).map(pe).filter(Boolean);if(Ee.length===0){Y("No valid proxies found in file.");return}Y(""),m(Ee)}catch{Y("Failed to read file.")}finally{Ue.current&&(Ue.current.value="")}},V=(H,de)=>{Ne(be=>{const fe=new Set(be);if(de?.shiftKey&&ke){const Ee=i.filter(it=>it.id!=="host"),De=Ee.findIndex(it=>it.id===ke),Oe=Ee.findIndex(it=>it.id===H);if(De!==-1&&Oe!==-1){const it=Math.min(De,Oe),Yt=Math.max(De,Oe);for(let St=it;St<=Yt;St++)fe.add(Ee[St].id);return fe}}return fe.has(H)?fe.delete(H):fe.add(H),fe}),Ae(H)},L=()=>{const H=i.filter(de=>de.id!=="host");me.size>=H.length&&H.length>0?Ne(new Set):Ne(new Set(H.map(de=>de.id)))},W=()=>{me.size>0&&(C(Array.from(me)),Ne(new Set))},K=i.filter(H=>H.id!=="host"),I=K.length>0&&me.size>=K.length;return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"security",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Proxies"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Set defaults and rotate per task"})]}),l.jsx("div",{className:"ml-auto",children:l.jsxs("button",{onClick:d,disabled:f,className:"px-4 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all disabled:opacity-50 inline-flex items-center gap-2",children:[l.jsx(_e,{name:"sync",className:`text-base ${f?"animate-spin":""}`}),"Refresh"]})})]}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[l.jsx("input",{type:"text",placeholder:"Proxy server (host:port or scheme://host:port)",value:N,onChange:H=>p(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy server address"}),l.jsx("input",{type:"text",placeholder:"Label (optional)",value:B,onChange:H=>D(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy label"}),l.jsx("input",{type:"text",placeholder:"Username (optional)",value:b,onChange:H=>v(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy username"}),l.jsx("input",{type:"password",placeholder:"Password (optional)",value:j,onChange:H=>k(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Proxy password"}),l.jsxs("label",{className:"flex items-center gap-3 px-4 py-3 rounded-xl bg-white/[0.05] border border-white/10 group cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:M,onChange:H=>O(H.target.checked),className:"w-4 h-4 rounded border-white/20 bg-transparent"}),l.jsx("span",{className:"text-[10px] text-gray-400 uppercase tracking-widest group-hover:text-white transition-colors",children:"Rotating pool"})]}),M&&l.jsx("input",{type:"number",placeholder:"Estimated size (optional)",value:X,onChange:H=>$(H.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white","aria-label":"Estimated pool size",min:"1"})]}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("button",{onClick:Ie,className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest bg-white text-black hover:scale-105 transition-all",children:"Add Proxy"}),l.jsx("button",{onClick:()=>Ue.current?.click(),className:"px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest border border-white/10 text-white hover:bg-white/5 transition-all",children:"Import"}),l.jsx("button",{onClick:()=>_("host"),className:`px-6 py-3 rounded-2xl text-[9px] font-bold uppercase tracking-widest border border-white/10 transition-all ${u?"text-white hover:bg-white/5":"bg-white/10 text-white"}`,children:"Use Host IP"})]}),(me.size>0||K.length>0)&&l.jsxs("div",{className:"flex items-center justify-between p-3.5 rounded-2xl bg-white/[0.02] border border-white/5",children:[l.jsxs("label",{className:"flex items-center gap-3 cursor-pointer group",children:[l.jsx("input",{type:"checkbox",checked:I,onChange:L,disabled:K.length===0,className:"w-4 h-4 rounded border-white/20 bg-transparent disabled:opacity-50"}),l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-widest group-hover:text-white transition-colors",children:me.size>0?`${me.size} Selected`:"Select All"})]}),me.size>0&&l.jsxs("button",{onClick:W,className:"px-4 py-2 rounded-xl bg-red-500/10 border border-red-500/20 text-[9px] font-bold uppercase tracking-widest text-red-400 hover:bg-red-500/20 transition-all inline-flex items-center gap-2",children:[l.jsx(_e,{name:"delete",className:"text-base"}),"Delete Selected"]})]}),l.jsx("input",{ref:Ue,type:"file",accept:".txt,text/plain",onChange:le,className:"hidden"}),ae&&l.jsx("div",{className:"text-[9px] text-red-400 uppercase tracking-widest",children:ae}),l.jsxs("label",{className:"flex items-center justify-between gap-3 p-3.5 rounded-2xl bg-white/[0.02] border border-white/5 hover:bg-white/[0.05] transition-all group",children:[l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-widest group-hover:text-white",children:"Rotation mode"}),l.jsxs("select",{value:c,onChange:H=>w(H.target.value==="random"?"random":"round-robin"),className:"bg-white/[0.05] border border-white/10 rounded-xl px-3 py-2 text-[10px] text-white uppercase tracking-widest","aria-label":"Rotation mode",children:[l.jsx("option",{value:"round-robin",children:"Round robin"}),l.jsx("option",{value:"random",children:"Random"})]})]}),l.jsxs("label",{className:"flex items-center gap-3 p-3.5 rounded-2xl bg-white/[0.02] border border-white/5 hover:bg-white/[0.05] transition-all cursor-pointer group",children:[l.jsx("input",{type:"checkbox",checked:r,onChange:H=>A(H.target.checked),className:"w-4 h-4 rounded border-white/20 bg-transparent"}),l.jsx("span",{className:"text-[10px] font-bold text-gray-500 uppercase tracking-widest group-hover:text-white",children:"Include default IP in rotation pool"})]}),l.jsxs("div",{className:"space-y-3",children:[f&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading proxies..."}),!f&&i.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No proxies saved yet."}),!f&&i.map(H=>{const de=H.id===u,be=H.id===oe;return l.jsx("div",{className:"flex items-center justify-between gap-4 p-4 rounded-2xl border border-white/10 bg-white/[0.02]",children:be?l.jsxs("div",{className:"w-full space-y-3",children:[l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[l.jsx("input",{type:"text",value:q,onChange:fe=>P(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white",placeholder:"Proxy server","aria-label":"Proxy server"}),l.jsx("input",{type:"text",value:we,onChange:fe=>F(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white",placeholder:"Label","aria-label":"Label"}),l.jsx("input",{type:"text",value:E,onChange:fe=>ne(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white",placeholder:"Username","aria-label":"Username"}),l.jsx("input",{type:"password",value:Q,onChange:fe=>Z(fe.target.value),placeholder:"Password (leave blank to keep)",className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white","aria-label":"Password"}),l.jsxs("label",{className:"flex items-center gap-3 px-4 py-2 rounded-xl bg-white/[0.05] border border-white/10 group cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:he,onChange:fe=>z(fe.target.checked),className:"w-3.5 h-3.5 rounded border-white/20 bg-transparent"}),l.jsx("span",{className:"text-[10px] text-gray-400 uppercase tracking-widest group-hover:text-white transition-colors",children:"Rotating pool"})]}),he&&l.jsx("input",{type:"number",placeholder:"Estimated size",value:U,onChange:fe=>te(fe.target.value),className:"bg-white/[0.05] border border-white/10 rounded-xl px-4 py-2 text-[10px] text-white","aria-label":"Estimated pool size",min:"1"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:S,className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all",children:"Save"}),l.jsx("button",{onClick:ct,className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white/70 hover:bg-white/5 transition-all",children:"Cancel"})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex items-center gap-4 border-r border-white/10 pr-4 w-12 justify-center",children:H.id!=="host"?l.jsx("input",{type:"checkbox",checked:me.has(H.id),onChange:()=>{},onClick:fe=>{fe.stopPropagation(),V(H.id,fe)},className:"w-4 h-4 rounded border-white/20 bg-transparent"}):l.jsx("div",{title:"Host IP (Cannot be deleted)",className:"flex items-center justify-center opacity-70",children:l.jsx(_e,{name:"computer",className:"text-lg text-white"})})}),l.jsxs("div",{className:"flex-1 space-y-1",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest",children:H.label||H.server}),l.jsxs("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest flex items-center gap-2",children:[l.jsx("span",{children:H.server}),H.isRotatingPool&&l.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-white/10 text-white font-bold inline-flex items-center gap-1",children:[l.jsx(_e,{name:"autorenew",className:"text-[10px]"}),"Pool",H.estimatedPoolSize?`(~${H.estimatedPoolSize})`:""]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{onClick:()=>_(H.id),className:`px-3 py-2 rounded-xl border text-[9px] font-bold uppercase tracking-widest transition-all inline-flex items-center gap-2 ${de?"bg-white text-black border-white":"border-white/10 text-white hover:bg-white/5"}`,children:[de?l.jsx(_e,{name:"star",className:"text-base"}):l.jsx(_e,{name:"star_outline",className:"text-base"}),de?"Default":"Set Default"]}),H.id!=="host"&&l.jsxs(l.Fragment,{children:[l.jsx("button",{onClick:()=>He(H),className:"px-3 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all",children:"Edit"}),l.jsxs("button",{onClick:()=>g(H.id),className:"px-3 py-2 rounded-xl border border-red-500/20 text-[9px] font-bold uppercase tracking-widest text-red-300 hover:bg-red-500/10 transition-all inline-flex items-center gap-2",children:[l.jsx(_e,{name:"delete",className:"text-base"}),"Delete"]})]})]})]})},H.id)})]})]})},fy=({selection:i,options:u,loading:r,onChange:c})=>l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-4",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"User Agent"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Default browser identity"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("select",{value:i,onChange:f=>c(f.target.value),disabled:r,className:"w-full bg-white/[0.05] border border-white/10 rounded-xl px-4 py-3 text-[10px] text-white uppercase tracking-widest disabled:opacity-60",children:[l.jsx("option",{value:"system",children:"System user agent (default)"}),u.map(f=>l.jsx("option",{value:f,children:f},f))]}),l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Applies when rotate UA is disabled in tasks."})]})]}),hy=({version:i})=>{const[u,r]=R.useState(!1),c=i?`v${i}`:"Unknown",f=async()=>{const d=i||c;try{if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)await navigator.clipboard.writeText(d);else if(typeof document<"u"){const m=document.createElement("textarea");m.value=d,m.style.position="fixed",m.style.opacity="0",document.body.appendChild(m),m.select(),document.execCommand("copy"),document.body.removeChild(m)}r(!0),setTimeout(()=>r(!1),1500)}catch{r(!1)}};return l.jsxs("div",{className:"glass-card p-8 rounded-[40px] space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:l.jsx(_e,{name:"content_copy",className:"text-xl"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-bold text-white uppercase tracking-widest",children:"Version"}),l.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-widest mt-1",children:"Package metadata"})]})]}),l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsx("div",{className:"text-[9px] font-bold uppercase tracking-[0.3em] text-white",children:c}),l.jsx("button",{onClick:f,className:"px-4 py-2 rounded-xl border border-white/10 text-[9px] font-bold uppercase tracking-widest text-white hover:bg-white/5 transition-all",type:"button",children:u?"Copied":"Copy version"})]})]})},py="0.10.0",my={version:py},Bc=my.version,xy=({onClearStorage:i,onConfirm:u,onNotify:r})=>{const[c,f]=R.useState("system"),[d,h]=R.useState([]),[m,x]=R.useState(!1),[g,C]=R.useState([]),[_,A]=R.useState([]),[w,N]=R.useState([]),[p,b]=R.useState([]),[v,j]=R.useState(!1),[k,B]=R.useState(null),[D,M]=R.useState(!0),[O,X]=R.useState(!1),[$,oe]=R.useState([]),[ce,q]=R.useState(!0),[P,E]=R.useState(!1),[ne,Q]=R.useState([]),[Z,we]=R.useState(!0),[F,he]=R.useState(!1),[z,U]=R.useState([]),[te,ae]=R.useState(!0),[Y,me]=R.useState(!1),[Ne,ke]=R.useState([]),[Ae,Ue]=R.useState(null),[Ie,He]=R.useState(!1),[ct,S]=R.useState("round-robin"),[pe,le]=R.useState(!1),[V,L]=R.useState("system"),[W,K]=R.useState([]),[I,H]=R.useState(!1),de=R.useCallback(async()=>{j(!0);try{const[ge,ve]=await Promise.all([fetch("/api/data/captures"),fetch("/api/data/cookies")]),je=ge.ok?await ge.json():{captures:[]},Ce=ve.ok?await ve.json():{cookies:[],origins:[]};A(Array.isArray(je.captures)?je.captures:[]),N(Array.isArray(Ce.cookies)?Ce.cookies:[]),b(Array.isArray(Ce.origins)?Ce.origins:[])}catch{A([]),N([]),b([])}finally{j(!1)}},[]),be=R.useCallback(async()=>{x(!0);try{const ge=await fetch("/api/credentials");ge.ok&&h(await ge.json())}catch{h([])}finally{x(!1)}},[]),fe=R.useCallback(async ge=>{await fetch(`/api/credentials/${ge}`,{method:"DELETE"}),h(ve=>ve.filter(je=>je.id!==ge))},[]),Ee=R.useCallback(async ge=>{if(!await u(`Delete capture ${ge}?`))return;(await fetch(`/api/data/captures/${encodeURIComponent(ge)}`,{method:"DELETE"})).ok?(r("Capture deleted.","success"),de()):r("Delete failed.","error")},[u,r,de]),De=R.useCallback(async ge=>{if(!await u(`Delete cookie ${ge.name}?`))return;(await fetch("/api/data/cookies/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ge.name,domain:ge.domain,path:ge.path})})).ok?(r("Cookie deleted.","success"),de()):r("Delete failed.","error")},[u,r,de]),Oe=async()=>{M(!0);try{const ge=await fetch("/api/settings/api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),B(null);return}const ve=await ge.json();B(ve.apiKey||null)}catch{B(null)}finally{M(!1)}},it=async()=>{q(!0);try{const ge=await fetch("/api/settings/gemini-api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),oe([]);return}const ve=await ge.json();oe(Array.isArray(ve.geminiApiKeys)?ve.geminiApiKeys:[])}catch{oe([])}finally{q(!1)}},Yt=async()=>{we(!0);try{const ge=await fetch("/api/settings/openai-api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),Q([]);return}const ve=await ge.json();Q(Array.isArray(ve.openAiApiKeys)?ve.openAiApiKeys:[])}catch{Q([])}finally{we(!1)}},St=async()=>{ae(!0);try{const ge=await fetch("/api/settings/claude-api-key",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),U([]);return}const ve=await ge.json();U(Array.isArray(ve.claudeApiKeys)?ve.claudeApiKeys:[])}catch{U([])}finally{ae(!1)}},da=async()=>{le(!0);try{const ge=await fetch("/api/settings/proxies",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),ke([]),Ue(null),S("round-robin");return}const ve=await ge.json();ke(Array.isArray(ve.proxies)?ve.proxies:[]),Ue(ve.defaultProxyId||null),He(!!ve.includeDefaultInRotation),S(ve.rotationMode==="random"?"random":"round-robin")}catch{ke([]),Ue(null),He(!1),S("round-robin")}finally{le(!1)}},Pe=async ge=>{le(!0);try{const ve=await fetch("/api/settings/proxies",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ge)});if(!ve.ok){let Ce="";try{const Xe=await ve.json();Ce=Xe?.error||Xe?.message||""}catch{Ce=""}r(`Failed to add proxy${Ce?`: ${Ce}`:""}.`,"error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Proxy added.","success")}catch{r("Failed to add proxy.","error")}finally{le(!1)}},gt=async()=>{H(!0);try{const ge=await fetch("/api/settings/user-agent",{credentials:"include"});if(!ge.ok){ge.status===401&&r("Session expired. Please log in again.","error"),L("system"),K([]);return}const ve=await ge.json();L(ve.selection==="system"?"system":String(ve.selection||"system")),K(Array.isArray(ve.userAgents)?ve.userAgents:[])}catch{L("system"),K([])}finally{H(!1)}},Tt=async ge=>{H(!0);try{const ve=await fetch("/api/settings/user-agent",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selection:ge})});if(!ve.ok){r("Failed to update user agent.","error");return}const je=await ve.json();L(je.selection==="system"?"system":String(je.selection||"system")),K(Array.isArray(je.userAgents)?je.userAgents:[]),r("User agent updated.","success")}catch{r("Failed to update user agent.","error")}finally{H(!1)}},st=async ge=>{if(!ge.length){r("No valid proxies found in file.","error");return}le(!0);try{const ve=await fetch("/api/settings/proxies/import",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({proxies:ge})});if(!ve.ok){let Ce="";try{const Xe=await ve.json();Ce=Xe?.error||Xe?.message||""}catch{Ce=""}r(`Failed to import proxies${Ce?`: ${Ce}`:""}.`,"error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Proxies imported.","success")}catch{r("Failed to import proxies.","error")}finally{le(!1)}},Mn=async(ge,ve)=>{le(!0);try{const je=await fetch(`/api/settings/proxies/${encodeURIComponent(ge)}`,{method:"PUT",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ve)});if(!je.ok){let Xe="";try{const Rt=await je.json();Xe=Rt?.error||Rt?.message||""}catch{Xe=""}r(`Failed to update proxy${Xe?`: ${Xe}`:""}.`,"error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r("Proxy updated.","success")}catch{r("Failed to update proxy.","error")}finally{le(!1)}},Sl=async ge=>{if(!(ge==="host"||!await u("Delete this proxy?"))){le(!0);try{const je=await fetch(`/api/settings/proxies/${encodeURIComponent(ge)}`,{method:"DELETE",credentials:"include"});if(!je.ok){r("Delete failed.","error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r("Proxy deleted.","success")}catch{r("Delete failed.","error")}finally{le(!1)}}},jl=async ge=>{if(!(ge.length===0||!await u(`Delete ${ge.length} proxies?`))){le(!0);try{const je=await fetch("/api/settings/proxies",{method:"DELETE",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({ids:ge})});if(!je.ok){r("Bulk delete failed.","error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r(`${ge.length} proxies deleted.`,"success")}catch{r("Bulk delete failed.","error")}finally{le(!1)}}},Va=async ge=>{const ve=ge==="host"?null:ge;le(!0);try{const je=await fetch("/api/settings/proxies/default",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({id:ve})});if(!je.ok){r("Failed to set default.","error");return}const Ce=await je.json();ke(Array.isArray(Ce.proxies)?Ce.proxies:[]),Ue(Ce.defaultProxyId||null),He(!!Ce.includeDefaultInRotation),S(Ce.rotationMode==="random"?"random":"round-robin"),r("Default proxy updated.","success")}catch{r("Failed to set default.","error")}finally{le(!1)}},va=async ge=>{le(!0);try{const ve=await fetch("/api/settings/proxies/rotation",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({includeDefaultInRotation:ge})});if(!ve.ok){r("Failed to update rotation setting.","error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Rotation setting updated.","success")}catch{r("Failed to update rotation setting.","error")}finally{le(!1)}},Qt=async ge=>{le(!0);try{const ve=await fetch("/api/settings/proxies/rotation",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({rotationMode:ge})});if(!ve.ok){r("Failed to update rotation mode.","error");return}const je=await ve.json();ke(Array.isArray(je.proxies)?je.proxies:[]),Ue(je.defaultProxyId||null),He(!!je.includeDefaultInRotation),S(je.rotationMode==="random"?"random":"round-robin"),r("Rotation mode updated.","success")}catch{r("Failed to update rotation mode.","error")}finally{le(!1)}},Dt=async()=>{X(!0);try{const ge=await fetch("/api/settings/api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include"});if(!ge.ok){let je="";try{const Ce=await ge.json();je=Ce?.error||Ce?.message||""}catch{je=""}ge.status===401?r("Session expired. Please log in again.","error"):r(`Failed to generate API key${je?`: ${je}`:""}.`,"error");return}const ve=await ge.json();B(ve.apiKey||null),r("API key generated.","success")}catch{r("Failed to generate API key.","error")}finally{X(!1)}},Ga=async ge=>{E(!0);try{const ve=await fetch("/api/settings/gemini-api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({geminiApiKeys:ge})});if(!ve.ok){ve.status===401?r("Session expired. Please log in again.","error"):r("Failed to save Gemini API keys.","error");return}const je=await ve.json();oe(Array.isArray(je.geminiApiKeys)?je.geminiApiKeys:[]),r("Gemini API keys saved.","success")}catch{r("Failed to save Gemini API keys.","error")}finally{E(!1)}},wa=async ge=>{he(!0);try{const ve=await fetch("/api/settings/openai-api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({openAiApiKeys:ge})});if(!ve.ok){ve.status===401?r("Session expired. Please log in again.","error"):r("Failed to save OpenAI API keys.","error");return}const je=await ve.json();Q(Array.isArray(je.openAiApiKeys)?je.openAiApiKeys:[]),r("OpenAI API keys saved.","success")}catch{r("Failed to save OpenAI API keys.","error")}finally{he(!1)}},_l=async ge=>{me(!0);try{const ve=await fetch("/api/settings/claude-api-key",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({claudeApiKeys:ge})});if(!ve.ok){ve.status===401?r("Session expired. Please log in again.","error"):r("Failed to save Claude API keys.","error");return}const je=await ve.json();U(Array.isArray(je.claudeApiKeys)?je.claudeApiKeys:[]),r("Claude API keys saved.","success")}catch{r("Failed to save Claude API keys.","error")}finally{me(!1)}};R.useEffect(()=>{c==="data"&&de(),c==="system"&&(Oe(),it(),Yt(),St(),gt(),be()),c==="proxies"&&da()},[c]),R.useEffect(()=>{c==="system"&&(Oe(),it(),Yt(),St(),be())},[]);const Ci=[{id:"gemini_api_key",name:"Gemini API Key",iconUrl:"https://www.google.com/s2/favicons?domain=gemini.google.com&sz=128",disabled:!1},{id:"anthropic_api_key",name:"Anthropic API Key",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/claude.svg",disabled:!1},{id:"openai_api_key",name:"OpenAI API Key",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/openai.svg",disabled:!1},{id:"ollama_api_key",name:"Ollama API Key",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/ollama.svg",disabled:!0}],Nl=[{providerKey:"baserow",name:"Baserow",iconUrl:"https://www.google.com/s2/favicons?domain=baserow.io&sz=128"}],xn=async ge=>{try{const ve=await fetch("/api/credentials",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(ge)});if(!ve.ok){const Ce=await ve.json().catch(()=>({}));return console.error("[handleAddDbCredential] API error",ve.status,Ce),!1}const je=await ve.json();return h(Ce=>[...Ce,je]),r("Credential saved.","success"),!0}catch(ve){return console.error("[handleAddDbCredential] fetch error:",ve),!1}},fa=[{id:"doppelganger_api_key",name:"Tasks API",description:"Manage task API access via `x-api-key` header",icon:"database",value:k,saving:O,loading:D,showCopyButton:!0,readOnly:!0,onSave:async()=>{},onRegenerate:async()=>{await Dt()}}];$.filter(ge=>ge&&ge.trim()).forEach((ge,ve)=>{fa.push({id:`gemini_api_key_${ve}`,name:"Gemini API Key",description:"Provide an API Key from Google AI Studio for AI features",iconUrl:"https://www.google.com/s2/favicons?domain=gemini.google.com&sz=128",value:ge,saving:P,loading:ce,badge:ve===0?"Primary":"Backup",onSave:async je=>{const Ce=[...$];Ce[ve]=je,await Ga(Ce)},onDelete:async()=>{const je=$.filter((Ce,Xe)=>Xe!==ve);await Ga(je)}})}),ne.filter(ge=>ge&&ge.trim()).forEach((ge,ve)=>{fa.push({id:`openai_api_key_${ve}`,name:"OpenAI API Key",description:"Provide an API Key from OpenAI for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/openai.svg",value:ge,saving:F,loading:Z,badge:ve===0?"Primary":"Backup",onSave:async je=>{const Ce=[...ne];Ce[ve]=je,await wa(Ce)},onDelete:async()=>{const je=ne.filter((Ce,Xe)=>Xe!==ve);await wa(je)}})}),z.filter(ge=>ge&&ge.trim()).forEach((ge,ve)=>{fa.push({id:`anthropic_api_key_${ve}`,name:"Anthropic API Key",description:"Provide an API Key from Anthropic for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/claude.svg",value:ge,saving:Y,loading:te,badge:ve===0?"Primary":"Backup",onSave:async je=>{const Ce=[...z];Ce[ve]=je,await _l(Ce)},onDelete:async()=>{const je=z.filter((Ce,Xe)=>Xe!==ve);await _l(je)}})});const Cl=g.filter(ge=>ge==="gemini_api_key").length;for(let ge=0;ge<Cl;ge++)fa.push({id:`gemini_api_key_unsaved_${ge}`,name:"Gemini API Key",description:"Provide an API Key from Google AI Studio for AI features",iconUrl:"https://www.google.com/s2/favicons?domain=gemini.google.com&sz=128",value:null,saving:P,loading:ce,startEditing:!0,onSave:async ve=>{const je=[...$,ve];await Ga(je),C(Ce=>{const Xe=Ce.indexOf("gemini_api_key");if(Xe!==-1){const Rt=[...Ce];return Rt.splice(Xe,1),Rt}return Ce})},onDelete:async()=>{C(ve=>{const je=ve.indexOf("gemini_api_key");if(je!==-1){const Ce=[...ve];return Ce.splice(je,1),Ce}return ve})}});const El=g.filter(ge=>ge==="openai_api_key").length;for(let ge=0;ge<El;ge++)fa.push({id:`openai_api_key_unsaved_${ge}`,name:"OpenAI API Key",description:"Provide an API Key from OpenAI for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/openai.svg",value:null,saving:F,loading:Z,startEditing:!0,onSave:async ve=>{const je=[...ne,ve];await wa(je),C(Ce=>{const Xe=Ce.indexOf("openai_api_key");if(Xe!==-1){const Rt=[...Ce];return Rt.splice(Xe,1),Rt}return Ce})},onDelete:async()=>{C(ve=>{const je=ve.indexOf("openai_api_key");if(je!==-1){const Ce=[...ve];return Ce.splice(je,1),Ce}return ve})}});const Ei=g.filter(ge=>ge==="anthropic_api_key").length;for(let ge=0;ge<Ei;ge++)fa.push({id:`anthropic_api_key_unsaved_${ge}`,name:"Anthropic API Key",description:"Provide an API Key from Anthropic for AI features",iconUrl:"https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/claude.svg",value:null,saving:Y,loading:te,startEditing:!0,onSave:async ve=>{const je=[...z,ve];await _l(je),C(Ce=>{const Xe=Ce.indexOf("anthropic_api_key");if(Xe!==-1){const Rt=[...Ce];return Rt.splice(Xe,1),Rt}return Ce})},onDelete:async()=>{C(ve=>{const je=ve.indexOf("anthropic_api_key");if(je!==-1){const Ce=[...ve];return Ce.splice(je,1),Ce}return ve})}});return d.forEach(ge=>{fa.push({id:`db_cred_${ge.id}`,name:ge.name,description:`${ge.provider} · ${ge.config.baseUrl}`,iconUrl:"https://www.google.com/s2/favicons?domain=baserow.io&sz=128",value:ge.config.token||null,saving:!1,loading:m,onSave:async()=>{},readOnly:!0,onDelete:async()=>{(u?await u(`Delete credential "${ge.name}"?`):confirm(`Delete credential "${ge.name}"?`))&&await fe(ge.id)}})}),l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-3xl mx-auto space-y-8",children:[l.jsx(uy,{tab:c,onTabChange:f}),c==="system"&&l.jsxs(l.Fragment,{children:[l.jsx(ty,{keys:fa,availableProviders:Ci,onAddProvider:ge=>C(ve=>[...ve,ge]),dbProviders:Nl,onAddDbCredential:xn,onConfirm:u}),l.jsx(fy,{selection:V,options:W,loading:I,onChange:Tt}),l.jsx(hy,{version:Bc}),l.jsx(ay,{onClearStorage:i})]}),c==="data"&&l.jsxs(l.Fragment,{children:[l.jsx(ry,{captures:_,loading:v,onRefresh:de,onDelete:Ee}),l.jsx(cy,{cookies:w,originsCount:p.length,loading:v,onClear:()=>i("cookies"),onDelete:De})]}),c==="proxies"&&l.jsx(dy,{proxies:Ne,defaultProxyId:Ae,includeDefaultInRotation:Ie,rotationMode:ct,loading:pe,onRefresh:da,onAdd:Pe,onImport:st,onUpdate:Mn,onDelete:Sl,onDeleteMultiple:jl,onSetDefault:Va,onToggleIncludeDefault:va,onRotationModeChange:Qt}),l.jsx("div",{className:"pt-8 flex justify-center border-t border-white/5 mt-8",children:l.jsx(Lp,{})})]})})},Lc=({title:i="Loading",subtitle:u})=>l.jsxs("div",{className:"fixed inset-0 z-[80] bg-[#020202] flex items-center justify-center",children:[l.jsx("div",{className:"absolute inset-0 opacity-[0.03] pointer-events-none",style:{backgroundImage:"radial-gradient(#fff 1px, transparent 1px)",backgroundSize:"40px 40px"}}),l.jsxs("div",{className:"glass-card p-10 rounded-[40px] text-center space-y-4",children:[l.jsx("div",{className:"w-12 h-12 mx-auto rounded-full border border-white/10 flex items-center justify-center",children:l.jsx("div",{className:"w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-gray-500",children:i}),u&&l.jsx("p",{className:"text-xs font-mono text-white/80",children:u})]})]})]}),$s=140,gy=6,by=4,yy=({index:i,style:u,data:r})=>{const c=r.items[i];return c?l.jsxs("div",{style:u,onClick:()=>r.navigate(`/executions/${c.id}`),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r.navigate(`/executions/${c.id}`))},role:"button",tabIndex:0,className:"glass-card w-full rounded-2xl p-5 flex items-center gap-4 text-left hover:bg-white/[0.06] transition-all cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-gray-400",children:c.source==="api"?l.jsx(_e,{name:"cloud",className:"text-xl"}):l.jsx(_e,{name:"monitor",className:"text-xl"})}),l.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[l.jsx("div",{className:"text-[10px] font-bold text-white uppercase tracking-widest truncate",children:c.taskName||c.mode}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[new Date(c.timestamp).toLocaleString()," | ",c.source," | ",c.mode," | ",c.status," | ",c.durationMs,"ms"]}),c.url&&l.jsx("div",{className:"text-[9px] text-white/50 truncate font-mono",children:c.url})]}),l.jsx("button",{onClick:f=>{f.stopPropagation(),r.deleteExecution(c.id)},className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-red-500/5 border border-red-500/10 text-red-400 hover:bg-red-500/10 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50","aria-label":`Delete execution ${c.id}`,children:"Delete"})]}):null},vy=({onConfirm:i,onNotify:u})=>{const r=Dn(),[c,f]=R.useState([]),[d,h]=R.useState("all"),[m,x]=R.useState(!1),g=R.useCallback(async()=>{x(!0);try{const N=await fetch("/api/executions");if(!N.ok)throw new Error("Failed to load");const p=await N.json();f(Array.isArray(p.executions)?p.executions:[])}catch{f([])}finally{x(!1)}},[]),C=R.useCallback(async()=>{if(!await i("Clear all executions?"))return;(await fetch("/api/executions/clear",{method:"POST"})).ok?(u("Executions cleared.","success"),g()):u("Clear failed.","error")},[g,i,u]),_=R.useCallback(async N=>{if(!await i("Delete this execution?"))return;(await fetch(`/api/executions/${N}`,{method:"DELETE"})).ok?(u("Execution deleted.","success"),f(v=>v.filter(j=>j.id!==N))):u("Delete failed.","error")},[i,u]);R.useEffect(()=>{g()},[g]);const A=R.useMemo(()=>c.filter(N=>d==="all"?!0:N.source===d),[c,d]),w=R.useMemo(()=>({items:A,deleteExecution:_,navigate:r}),[A,_,r]);return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsx("div",{className:"space-y-2",children:l.jsx("h2",{className:"text-4xl font-bold tracking-tighter text-white",children:"Run History"})}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"flex bg-white/5 rounded-xl p-1 border border-white/5",children:["all","editor","api"].map(N=>l.jsx("button",{onClick:()=>h(N),className:`px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-lg transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 ${d===N?"bg-white text-black":"text-gray-500 hover:text-white"}`,"aria-pressed":d===N,children:N},N))}),l.jsx("button",{onClick:g,disabled:m,"aria-busy":m,className:"w-10 h-10 rounded-2xl border border-white/10 text-gray-400 hover:text-white hover:bg-white/5 transition-all flex items-center justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50 disabled:opacity-50 disabled:cursor-not-allowed",title:"Refresh","aria-label":"Refresh executions",children:l.jsx(_e,{name:"sync",className:`text-xl ${m?"animate-spin":""}`})}),l.jsx("button",{onClick:C,className:"w-10 h-10 rounded-2xl border border-red-500/20 text-red-400 hover:bg-red-500/10 transition-all flex items-center justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-white/50",title:"Clear all","aria-label":"Clear all executions",children:l.jsx(_e,{name:"delete",className:"text-xl"})})]})]}),m&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading executions..."}),!m&&A.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No executions found."}),!m&&A.length>0&&l.jsx(nr,{height:Math.min(Math.max($s,A.length*$s),$s*gy),itemCount:A.length,itemSize:$s,width:"100%",overscanCount:by,itemData:w,className:"custom-scrollbar",children:yy})]})})};function Zp(){const[i,u]=R.useState(null);return R.useEffect(()=>{let r=!1;return(async()=>{try{const f=await fetch("/api/headful/status");if(f.ok){const d=await f.json();r||u(!!d.useNovnc)}else r||u(!1)}catch{r||u(!1)}})(),()=>{r=!0}},[]),i}const wy=i=>{if(!i.result)return null;const u=i.result||{};return{url:i.url||u.url||"",finalUrl:u.final_url||u.finalUrl,html:u.html,data:u.data??u.html??"",screenshotUrl:u.screenshot_url||u.screenshotUrl,logs:u.logs||[],timestamp:new Date(i.timestamp).toLocaleTimeString()}},Sy=({onConfirm:i,onNotify:u})=>{const{id:r}=Ap(),c=Dn(),[f,d]=R.useState(null),[h,m]=R.useState(!1),x=Zp();if(R.useEffect(()=>{(async()=>{if(r){m(!0);try{const _=await fetch(`/api/executions/${r}`);if(!_.ok)throw new Error("Failed to load execution");const A=await _.json();d(A.execution||null)}catch{d(null)}finally{m(!1)}}})()},[r]),h)return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsx("div",{className:"max-w-6xl mx-auto text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading execution..."})});if(!f)return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[l.jsx("button",{onClick:()=>c("/executions"),className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Back"}),l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"Execution not found."})]})});const g=wy(f);return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("h2",{className:"text-3xl font-bold tracking-tighter text-white",children:f.taskName||f.mode}),l.jsxs("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:[new Date(f.timestamp).toLocaleString()," | ",f.source," | ",f.mode," | ",f.status," | ",f.durationMs,"ms"]})]}),l.jsx("button",{onClick:()=>c("/executions"),className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Back"})]}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8 flex flex-col min-h-[420px]",children:[l.jsx("div",{className:"flex items-center justify-between border-b border-white/5 pb-4 mb-6",children:l.jsx("span",{className:"text-[8px] font-bold text-gray-500 uppercase tracking-widest",children:"Output"})}),g?l.jsx(Gp,{results:g,isExecuting:!1,onConfirm:i,onNotify:u,fullWidth:!0,useNovnc:x}):l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"No output captured."})]})]})})},jy=360,Xp=12,Qs=jy+Xp,_y=6,Ny=4,Cy=({index:i,style:u,data:r})=>{const c=r.captures[i];return c?l.jsx("div",{style:{...u,paddingBottom:Xp},children:l.jsx(Yp,{capture:c,onDelete:r.onDelete})}):null},Ey=({onConfirm:i,onNotify:u})=>{const r=Dn(),[c,f]=R.useState([]),[d,h]=R.useState(!1),m=async()=>{h(!0);try{const C=await fetch("/api/data/captures"),_=C.ok?await C.json():{captures:[]};f(Array.isArray(_.captures)?_.captures:[])}catch{f([])}finally{h(!1)}},x=R.useCallback(async C=>{if(!await i(`Delete capture ${C}?`))return;(await fetch(`/api/data/captures/${encodeURIComponent(C)}`,{method:"DELETE"})).ok?(f(w=>w.filter(N=>N.name!==C)),u("Capture deleted.","success")):u("Delete failed.","error")},[i,u]);R.useEffect(()=>{m()},[]);const g=R.useMemo(()=>({captures:c,onDelete:x}),[c,x]);return l.jsx("main",{className:"flex-1 p-12 overflow-y-auto custom-scrollbar animate-in fade-in duration-500",children:l.jsxs("div",{className:"max-w-6xl mx-auto space-y-8",children:[l.jsxs("div",{className:"flex items-end justify-between",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("h2",{className:"text-3xl font-bold tracking-tighter text-white",children:"All Captures"}),l.jsx("div",{className:"text-[8px] text-gray-500 uppercase tracking-[0.2em]",children:"Recordings and screenshots from every run"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{onClick:m,disabled:d,"aria-busy":d,className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all disabled:opacity-50 inline-flex items-center gap-2",children:[l.jsx(_e,{name:"sync",className:`text-base ${d?"animate-spin":""}`}),"Refresh"]}),l.jsx("button",{onClick:()=>r("/executions"),className:"px-4 py-2 text-[9px] font-bold uppercase tracking-widest rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all",children:"Executions"})]})]}),l.jsxs("div",{className:"glass-card rounded-[32px] p-8",children:[d&&l.jsx("div",{className:"text-[9px] text-gray-500 uppercase tracking-widest",children:"Loading captures..."}),!d&&c.length===0&&l.jsx("div",{className:"text-[9px] text-gray-600 uppercase tracking-widest",children:"No captures found."}),!d&&c.length>0&&l.jsx("div",{className:"space-y-4",children:l.jsx(nr,{height:Math.min(Math.max(Qs,c.length*Qs),Qs*_y),width:"100%",itemCount:c.length,itemSize:Qs,overscanCount:Ny,itemData:g,className:"custom-scrollbar",children:Cy})})]})]})})},$p=({title:i="Not Found",subtitle:u="The page you requested does not exist.",onBack:r})=>l.jsx("div",{className:"h-full flex items-center justify-center px-10",children:l.jsxs("div",{className:"glass-card w-full max-w-2xl rounded-[40px] border border-white/10 p-10 text-center space-y-6",children:[l.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-gray-500",children:"404"}),l.jsx("h2",{className:"text-3xl font-bold tracking-tighter text-white",children:i}),l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.25em] text-gray-500",children:u}),r&&l.jsxs("button",{onClick:r,className:"mt-2 inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-white text-black text-[9px] font-bold uppercase tracking-[0.3em] hover:scale-105 transition-all",children:[l.jsx(_e,{name:"arrow_back",className:"text-base"}),"Back"]})]})}),ky=({message:i,tone:u,onClose:r})=>{const[c,f]=R.useState(!1);return R.useEffect(()=>{const d=setTimeout(()=>{f(!0)},2500);return()=>clearTimeout(d)},[]),R.useEffect(()=>{if(!c)return;const d=setTimeout(()=>r(),240);return()=>clearTimeout(d)},[c,r]),l.jsx("div",{className:`fixed bottom-6 right-6 z-[220] max-w-sm w-full ${c?"animate-out fade-out slide-out-to-bottom-3 duration-200":"animate-in fade-in slide-in-from-bottom-3 duration-300"}`,children:l.jsxs("div",{className:`glass-card rounded-2xl border border-white/10 p-4 shadow-2xl flex items-start gap-3 ${c?"animate-out fade-out zoom-out-95 duration-200":"animate-in fade-in zoom-in-95 duration-300"}`,children:[l.jsx("div",{className:`mt-1 h-2.5 w-2.5 rounded-full ${u==="error"?"bg-red-400":"bg-emerald-400"}`}),l.jsxs("div",{className:"flex-1",children:[l.jsx("p",{className:"text-[8px] font-bold uppercase tracking-[0.35em] text-gray-500",children:"Notification"}),l.jsx("p",{className:"mt-2 font-mono text-[11px] text-white leading-relaxed",children:i})]}),l.jsx("button",{onClick:()=>f(!0),className:"px-2 py-1 text-[8px] font-bold uppercase tracking-[0.2em] text-white/60 hover:text-white",children:"Close"})]})})},Ay=({request:i,onResolve:u})=>l.jsx("div",{className:"fixed inset-0 z-[201] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",children:l.jsxs("div",{className:"glass-card w-full max-w-md rounded-[32px] border border-white/10 p-8 text-center shadow-2xl",children:[l.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-gray-500",children:i.title??"Confirm"}),l.jsx("p",{className:"mt-4 font-mono text-sm text-white",children:i.message}),l.jsxs("div",{className:"mt-6 flex gap-4",children:[l.jsx("button",{onClick:()=>u(!1),className:"w-full rounded-2xl px-6 py-3 text-[9px] font-bold uppercase tracking-[0.3em] transition-all bg-white/5 border border-white/10 text-gray-300 hover:bg-white/10",children:i.cancelLabel??"Cancel"}),l.jsx("button",{onClick:()=>u(!0),className:"w-full rounded-2xl px-6 py-3 text-[9px] font-bold uppercase tracking-[0.3em] transition-all bg-white text-black hover:scale-105 shadow-xl shadow-white/10",children:i.confirmLabel??"Confirm"})]})]})}),zy=({tasks:i,loadTasks:u,touchTask:r,currentTask:c,setCurrentTask:f,onTaskLoaded:d,...h})=>{const{id:m}=Ap(),x=Dn(),[g,C]=R.useState(!1),[_,A]=R.useState(!1);return R.useEffect(()=>{(async()=>{if(c?.id===m)return;C(!0),A(!1);let N=i;i.length===0&&(N=await u());const p=N.find(b=>String(b.id)===String(m));if(p){const b={...p};(!b.variables||Array.isArray(b.variables))&&(b.variables={}),b.stealth||(b.stealth={allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1}),b.stealth.cursorGlide===void 0&&(b.stealth.cursorGlide=b.stealth.humanCursor??!1),delete b.stealth.humanCursor,b.stealth.randomizeClicks===void 0&&(b.stealth.randomizeClicks=!1),Array.isArray(b.actions)&&(b.actions=b.actions.map((v,j)=>v&&v.id?v:{...v,id:`act_${Date.now()}_${j}_${Math.floor(Math.random()*1e3)}`})),b.includeShadowDom===void 0&&(b.includeShadowDom=!0),f(b),d?.(b),m&&r(m)}else A(!0);C(!1)})()},[m,i]),_?l.jsx($p,{title:"Task Not Found",subtitle:"This task does not exist or was deleted.",onBack:()=>x("/dashboard")}):g||!c||String(c.id)!==String(m)?l.jsx(Lc,{title:"Loading Mission Data",subtitle:"Syncing task payload"}):l.jsx(Kp,{currentTask:c,setCurrentTask:f,tasks:i,...h})},hp="doppelganger.seenReleaseNotes_0_8";function Ry(){const[i,u]=R.useState(!1),[r,c]=R.useState(""),[f,d]=R.useState(!0);R.useEffect(()=>{Bc.startsWith("0.8.")&&(localStorage.getItem(hp)||(u(!0),h()))},[]);const h=async()=>{try{const x=await fetch("https://api.github.com/repos/figranium/figranium/releases/tags/v0.8.0");if(x.ok){const g=await x.json();c(g.body||"No release notes available.")}else c("Failed to load release notes. Please check our GitHub repository.")}catch{c("Failed to load release notes. Please check our GitHub repository.")}finally{d(!1)}},m=()=>{u(!1),localStorage.setItem(hp,"true")};return i?l.jsx("div",{className:"fixed inset-0 z-[300] flex items-center justify-center bg-black/70 backdrop-blur-sm px-6",children:l.jsxs("div",{className:"glass-card w-full max-w-2xl max-h-[80vh] flex flex-col rounded-[32px] border border-white/10 p-8 text-left shadow-2xl overflow-hidden",children:[l.jsxs("div",{className:"flex justify-between items-center mb-6 shrink-0",children:[l.jsx("h2",{className:"text-lg md:text-2xl font-bold text-white tracking-tight",children:"What's new in v0.8.0"}),l.jsxs("span",{className:"bg-white/10 text-white/70 px-3 py-1 rounded-full text-xs font-mono ml-4 shrink-0",children:["v",Bc]})]}),l.jsx("div",{className:"flex-1 overflow-y-auto pr-2 custom-scrollbar text-sm text-gray-300",children:f?l.jsx("div",{className:"flex justify-center items-center h-32",children:l.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-white"})}):l.jsx("div",{className:"whitespace-pre-wrap font-mono text-xs",children:r})}),l.jsx("div",{className:"mt-8 flex justify-end shrink-0",children:l.jsx("button",{onClick:m,className:"rounded-2xl px-8 py-3 text-[10px] font-bold uppercase tracking-[0.3em] transition-all bg-white text-black hover:scale-105 shadow-xl shadow-white/10",children:"Got it"})})]})}):null}const Oy=(i,u)=>{if(typeof i!="string"||!i)return u;switch(i){case"ALREADY_SETUP":return"An account already exists";case"INVALID":return"Invalid credentials";case"SESSION_SAVE_FAILED":return"Unable to persist your session";default:{const r=i.toLowerCase().replace(/_/g," ");return r.charAt(0).toUpperCase()+r.slice(1)}}};function Ty(){const i=Dn(),[u,r]=R.useState(null),[c,f]=R.useState("checking"),[d,h]=R.useState(""),[m,x]=R.useState(!1),g=R.useCallback(async()=>{try{const w=await(await fetch("/api/auth/me",{credentials:"include"})).json();if(w.authenticated)return r(w.user),f("authenticated"),!0;const p=await(await fetch("/api/auth/check-setup",{credentials:"include"})).json();f(p.setupRequired?"setup":"login")}catch{f("login")}return!1},[]);R.useEffect(()=>{g()},[g]);const C=R.useCallback(async(A,w,N,p)=>{if(!A||!w){h("Email and password are required");return}if(c==="setup"&&(!N||w!==p)){h(N?"Passwords do not match":"Name required");return}if(m)return;const b=c==="setup"?"/api/auth/setup":"/api/auth/login",v=c==="setup"?{name:N,email:A,password:w}:{email:A,password:w};x(!0);try{const j=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(v)}),k=await j.json().catch(()=>({}));if(j.ok)h(""),f("checking"),await g()?i("/"):(h("Authentication failed"),f("login"));else{const B=c==="setup"?"Setup failed":"Invalid credentials";h(Oy(k?.error,B))}}catch{h("Network error")}finally{x(!1)}},[c,m,i,g]),_=R.useCallback(async A=>{await A("Are you sure you want to log out?")&&(await fetch("/api/auth/logout",{method:"POST",credentials:"include"}),r(null),f("login"),i("/"))},[i]);return{user:u,setUser:r,authStatus:c,setAuthStatus:f,authError:d,authBusy:m,checkAuth:g,handleAuthSubmit:C,logout:_}}const pp=i=>{if(!i)return"";const u=JSON.parse(JSON.stringify(i));return delete u.last_opened,JSON.stringify(u)},er=i=>{if(typeof i=="boolean")return i;if(i==null)return!1;const u=String(i).toLowerCase();return u==="true"||u==="1"},Dy=i=>i&&i[0].toUpperCase()+i.slice(1),Qp=i=>{if(!i.actions||!Array.isArray(i.actions))return i;let u=!1;const r=i.actions.map((c,f)=>c.id?c:(u=!0,{...c,id:`act_${Date.now()}_${f}_${Math.floor(Math.random()*1e3)}`}));return u?{...i,actions:r}:i},My=()=>({name:"Imported Task",url:"",mode:"scrape",wait:3,selector:"",rotateUserAgents:!1,rotateProxies:!1,rotateViewport:!1,humanTyping:!1,stealth:{allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1},actions:[],variables:{},includeShadowDom:!0,disableRecording:!1,statelessExecution:!1}),Uy=(i,u)=>{if(!i||typeof i!="object")return null;const r=My(),c={...r,...i};return(!c.name||typeof c.name!="string")&&(c.name=`Imported Task ${u+1}`),(!c.mode||!["scrape","agent","headful"].includes(c.mode))&&(c.mode="scrape"),typeof c.wait!="number"&&(c.wait=3),c.stealth||(c.stealth=r.stealth),(!c.variables||Array.isArray(c.variables))&&(c.variables={}),Array.isArray(c.actions)||(c.actions=[]),c.rotateProxies===void 0&&(c.rotateProxies=!1),c.disableRecording===void 0&&(c.disableRecording=!1),c.disableRecording=er(c.disableRecording),c.statelessExecution===void 0&&(c.statelessExecution=!1),c.statelessExecution=er(c.statelessExecution),delete c.versions,delete c.last_opened,c},By=()=>({name:"Task "+Math.floor(Math.random()*100),url:"",mode:"agent",wait:3,selector:"",rotateUserAgents:!1,rotateProxies:!1,rotateViewport:!1,humanTyping:!1,stealth:{allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1},actions:[],variables:{},extractionFormat:"json",includeHtml:!1,includeShadowDom:!0,disableRecording:!1,statelessExecution:!1});function Ly(i,u,r){const[c,f]=R.useState([]),[d,h]=R.useState(null),m=R.useRef(null);R.useEffect(()=>{m.current=d},[d]);const x=R.useCallback(async()=>{try{const j=[...await(await fetch("/api/tasks",{credentials:"include"})).json()].sort((k,B)=>(B.last_opened||0)-(k.last_opened||0));return f(j),j}catch(b){return console.error("Failed to load tasks",b),[]}},[]),g=R.useCallback(async b=>{try{await fetch(`/api/tasks/${b}/touch`,{method:"POST"}),x()}catch(v){console.error("Failed to touch task",v)}},[x]),C=R.useCallback((b,v)=>{const j=By();v(!0),h(j),b(null),i("/tasks/new")},[i]),_=R.useCallback((b,v,j)=>{const k={...b};(!k.variables||Array.isArray(k.variables))&&(k.variables={}),k.stealth||(k.stealth={allowTypos:!1,idleMovements:!1,overscroll:!1,deadClicks:!1,fatigue:!1,naturalTyping:!1,cursorGlide:!1,randomizeClicks:!1}),k.stealth.cursorGlide===void 0&&(k.stealth.cursorGlide=k.stealth.humanCursor??!1),delete k.stealth.humanCursor,k.stealth.randomizeClicks===void 0&&(k.stealth.randomizeClicks=!1),k.rotateProxies===void 0&&(k.rotateProxies=!1),k.rotateViewport===void 0&&(k.rotateViewport=!1),k.extractionFormat||(k.extractionFormat="json"),k.includeHtml===void 0&&(k.includeHtml=!1),k.includeShadowDom===void 0&&(k.includeShadowDom=!0),k.disableRecording===void 0&&(k.disableRecording=!1),k.disableRecording=er(k.disableRecording),k.statelessExecution===void 0&&(k.statelessExecution=!1),k.statelessExecution=er(k.statelessExecution);const B=Qp(k);h(B),v(B),j(null),i(`/tasks/${b.id}`),b.id&&g(b.id)},[i,g]),A=R.useCallback(async(b,v)=>{await r("Are you sure you want to delete this task?")&&(await fetch(`/api/tasks/${b}`,{method:"DELETE"}),x(),v.includes(b)&&i("/dashboard"))},[r,x,i]),w=R.useCallback(async(b,v,j,k=!1)=>{const B=j||m.current;if(!B)return;const D={...B,last_opened:Date.now()},X=await(await fetch(`/api/tasks${k?"?version=true":""}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)})).json();h(X),b(X),x(),v.includes("new")&&i(`/tasks/${X.id}`,{replace:!0})},[i,x]),N=R.useCallback(b=>{let v=c;if(b&&b.length>0&&(v=c.filter(O=>O.id&&b.includes(O.id))),v.length===0){u("No tasks selected to export.","error");return}const j={exportedAt:new Date().toISOString(),tasks:v},k=new Blob([JSON.stringify(j,null,2)],{type:"application/json"}),B=URL.createObjectURL(k),D=document.createElement("a"),M=new Date().toISOString().slice(0,10);D.href=B,D.download=`doppelganger-tasks-${M}.json`,document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(B),u(`Exported ${v.length} task(s).`,"success")},[c,u]),p=R.useCallback(async b=>{try{const v=await b.text(),j=JSON.parse(v);let k=[];if(Array.isArray(j)?k=j:j&&typeof j=="object"&&(Array.isArray(j.tasks)?k=j.tasks:(j.name||j.actions)&&(k=[j])),k.length===0){u("Invalid import file.","error");return}const B=Date.now(),D=k.map((M,O)=>Uy(M,O)).filter(M=>!!M).map((M,O)=>M.id?M:{...M,id:`task_${B}_${O}`});if(D.length===0){u("No tasks to import.","error");return}await Promise.all(D.map(M=>fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}))),await x(),u(`Imported ${D.length} task(s).`,"success")}catch(v){u(`Import failed: ${v.message||"Unknown error"}`,"error")}},[u,x]);return R.useEffect(()=>{x()},[x]),{tasks:c,setTasks:f,currentTask:d,setCurrentTask:h,loadTasks:x,touchTask:g,createNewTask:C,editTask:_,deleteTask:A,saveTask:w,exportTasks:N,importTasks:p}}const mp=(i,u)=>{const r=String(i||"").trim();if(!r)return"Execution failed.";const c=r.toLowerCase();if(u==="headful"){if(c.includes("missing x server")||c.includes("$display"))return"Headful browser could not start because no display server is available.";if(c.includes("failed to connect to the bus"))return"Headful browser could not start due to missing system services."}let f=r;const d=f.indexOf("--disable-");return d>0&&(f=f.slice(0,d).trim()),f.length>240&&(f=`${f.slice(0,240)}...`),f||"Execution failed."},Hy=i=>{const u=String(i||"").toLowerCase();return u.includes("missing x server")||u.includes("$display")||u.includes("platform failed to initialize")||u.includes("no display server")};function qy(i){const[u,r]=R.useState(!1),[c,f]=R.useState(!1),[d,h]=R.useState(null),[m,x]=R.useState(null),g=Zp(),C=R.useRef(null),_=async()=>{try{await fetch("/headful/stop",{method:"POST"})}catch(p){console.error("Failed to stop headful session",p)}finally{f(!1)}};return{isExecuting:u,isHeadfulOpen:c,results:d,setResults:h,activeRunId:m,useNovnc:g,runTaskWithSnapshot:async(p,b,v)=>{if(!p||!p.url)return;const j=Qp(p);b&&j!==b&&v(j);const k=`run_${Date.now()}_${Math.floor(Math.random()*1e3)}`;if(x(k),u)return;r(!0),h({url:j.url,logs:[],timestamp:"Running..."});let B=null;try{const D={};Object.entries(j.variables).forEach(([P,E])=>{D[P]=E.value});const M=P=>P.replace(/\\{\$(\w+)\\}/g,(E,ne)=>{if(ne==="now")return new Date().toISOString();const Q=D[ne];return Q==null||Q===""?"":String(Q)}),O=P=>typeof P!="string"?P:M(P),X=j.mode!=="agent";B={...{...j,url:X?M(j.url||""):j.url||"",selector:X?O(j.selector):j.selector,actions:X?j.actions.map(P=>({...P,selector:O(P.selector),value:O(P.value),key:O(P.key)})):j.actions},taskVariables:D,variables:D,runSource:"editor",taskId:j.id,taskName:j.name,taskSnapshot:j,runId:k};const oe=async P=>{const E=new AbortController;C.current=E;const ne=await fetch(`/${P}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B),signal:E.signal});if(!ne.ok){let Q=null;try{Q=await ne.json()}catch{Q=null}const Z=new Error(Q?.details||Q?.error||"Request failed");throw Z.code=Q?.error,Z}return ne.json()},ce=j.mode==="headful"?"scrape":j.mode,q=await oe(ce);h({url:j.url,finalUrl:q.final_url,html:q.html,data:q.data??q.html??"No data captured.",screenshotUrl:q.screenshot_url,downloads:q.downloads,logs:q.logs||[],timestamp:new Date().toLocaleTimeString()})}catch(D){if(D?.name==="AbortError"){i("Execution stopped.","success"),r(!1);return}if(j?.mode==="headful"&&B&&(D?.code==="HEADFUL_DISPLAY_UNAVAILABLE"||Hy(D?.message||String(D))))try{const O=await(async()=>{const X=new AbortController;C.current=X;const $=await fetch("/scrape",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B),signal:X.signal});if(!$.ok){const oe=await $.json();throw new Error(oe.details||oe.error||"Request failed")}return $.json()})();O.logs=["Headful display unavailable; ran headless instead.",...O.logs||[]],h({url:j.url,finalUrl:O.final_url,html:O.html,data:O.data??O.html??"No data captured.",screenshotUrl:O.screenshot_url,downloads:O.downloads,logs:O.logs||[],timestamp:new Date().toLocaleTimeString()}),r(!1);return}catch(O){const X=mp(O?.message||String(O),j?.mode);i(`Execution crash: ${X}`,"error"),r(!1);return}const M=mp(D?.message||String(D),j?.mode);i(`Execution crash: ${M}`,"error"),j?.mode==="headful"&&r(!1)}finally{C.current=null,r(!1)}},stopTask:async()=>{if(m)try{await fetch("/api/executions/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({runId:m})})}catch(p){console.error("Failed to request stop",p)}C.current&&C.current.abort(),r(!1)},openHeadful:async(p,b,v,j)=>{if(c){await _();return}f(!0);try{const k=await fetch("/headful",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,targetActionId:b,taskSnapshot:v,variables:j})});if(!k.ok){const B=await k.json().catch(()=>({})),D=B?.details||B?.error||"Failed to start headful session";i(D,"error"),f(!1)}}catch{i("Failed to start headful session","error"),f(!1)}},stopHeadful:_}}function Yy(){const[i,u]=R.useState(null),[r,c]=R.useState(null),f=R.useRef(null),d=R.useCallback((x,g="success")=>{u({message:x,tone:g}),g==="success"&&setTimeout(()=>{u(C=>C&&C.message===x?null:C)},2e3)},[]),h=R.useCallback(x=>new Promise(g=>{f.current=g,c(typeof x=="string"?{message:x}:x)}),[]),m=R.useCallback(x=>{const g=f.current;f.current=null,c(null),g&&g(x)},[]);return{centerAlert:i,setCenterAlert:u,centerConfirm:r,showAlert:d,requestConfirm:h,closeConfirm:m}}function Vy(){const i=Dn(),u=mn(),{centerAlert:r,setCenterAlert:c,centerConfirm:f,showAlert:d,requestConfirm:h,closeConfirm:m}=Yy(),{authStatus:x,authError:g,authBusy:C,handleAuthSubmit:_,logout:A}=Ty(),{tasks:w,currentTask:N,setCurrentTask:p,loadTasks:b,touchTask:v,createNewTask:j,editTask:k,deleteTask:B,saveTask:D,exportTasks:M,importTasks:O}=Ly(i,d,h),{isExecuting:X,isHeadfulOpen:$,results:oe,setResults:ce,activeRunId:q,useNovnc:P,runTaskWithSnapshot:E,stopTask:ne,openHeadful:Q,stopHeadful:Z}=qy(d);R.useEffect(()=>{x==="authenticated"&&b()},[x]);const[we,F]=R.useState(!1),he=R.useRef(""),[z,U]=R.useState("visual"),[te,ae]=R.useState({}),Y="doppelganger.pinnedResults",Ne=(I=>I?.id?String(I.id):"new")(N),ke=N&&te[Ne]||null;R.useEffect(()=>{try{const I=localStorage.getItem(Y);if(I){const H=JSON.parse(I);H&&typeof H=="object"&&ae(H)}}catch{}},[]),R.useEffect(()=>{try{localStorage.setItem(Y,JSON.stringify(te))}catch{}},[te]),R.useEffect(()=>{!u.pathname.startsWith("/tasks")&&z==="history"&&U("visual")},[u.pathname,z]),R.useEffect(()=>{u.pathname==="/tasks/new"&&!N&&j(ce,F)},[u.pathname]),R.useEffect(()=>{if(!N){F(!1);return}const I=pp(N);F(I!==he.current)},[N]),R.useEffect(()=>{if(typeof window>"u")return;const I=H=>{we&&(H.preventDefault(),H.returnValue="")};return window.addEventListener("beforeunload",I),()=>window.removeEventListener("beforeunload",I)},[we]);const Ae=R.useCallback(I=>{he.current=pp(I),F(!1)},[]),Ue=I=>{N&&ae(H=>({...H,[Ne]:I}))},Ie=()=>{N&&ae(I=>{const H={...I};return delete H[Ne],H})},He=async I=>{if(!await h(`Delete all ${I}?`))return;await fetch(I==="screenshots"?"/api/clear-screenshots":"/api/clear-cookies",{method:"POST"}),d(`${Dy(I)} cleared.`,"success")},ct=()=>u.pathname.startsWith("/tasks")?"editor":u.pathname==="/settings"?"settings":u.pathname==="/executions"?"executions":u.pathname==="/captures"?"captures":"dashboard",S=R.useCallback(I=>{I==="dashboard"?i("/dashboard"):I==="settings"?i("/settings"):I==="executions"?i("/executions"):I==="captures"&&i("/captures")},[i]),pe=R.useCallback(()=>{j(ce,F)},[j,ce,F]),le=R.useCallback(I=>{k(I,Ae,ce)},[k,Ae,ce]),V=R.useCallback(I=>{B(I,u.pathname)},[B,u.pathname]),L=R.useCallback((I,H)=>D(Ae,u.pathname,I,H),[D,Ae,u.pathname]),W=R.useCallback(()=>{A(h)},[A,h]);let K;return x==="login"||x==="setup"?K=l.jsx(Jg,{status:x,onSubmit:_,error:g,busy:C}):x==="checking"?K=l.jsx(Lc,{title:"Authenticating",subtitle:"Verifying session state"}):K=l.jsxs("div",{className:"h-full flex flex-row overflow-hidden bg-[#020202]",children:[l.jsx(Ry,{}),l.jsx(Qg,{onNavigate:S,onNewTask:pe,onLogout:W,currentScreen:ct()}),l.jsxs(hg,{children:[l.jsx(ga,{path:"/",element:l.jsx(Wh,{tasks:w,onNewTask:pe,onEditTask:le,onDeleteTask:V,onExportTasks:M,onImportTasks:O})}),l.jsx(ga,{path:"/dashboard",element:l.jsx(Wh,{tasks:w,onNewTask:pe,onEditTask:le,onDeleteTask:V,onExportTasks:M,onImportTasks:O})}),l.jsx(ga,{path:"/tasks/new",element:N?l.jsx(Kp,{currentTask:N,setCurrentTask:p,tasks:w,editorView:z,setEditorView:U,isExecuting:X,onSave:L,onRun:()=>E(N,N,p),onRunSnapshot:I=>E(I||N,N,p),results:oe,pinnedResults:ke,onConfirm:h,onNotify:d,onPinResults:Ue,onUnpinResults:Ie,runId:q,onStop:()=>ne(),isHeadfulOpen:$,onOpenHeadful:(I,H,de,be)=>Q(I,H,de,be),onStopHeadful:Z,useNovnc:P}):l.jsx(Lc,{title:"Initializing",subtitle:"Preparing task workspace"})}),l.jsx(ga,{path:"/tasks/:id",element:l.jsx(zy,{tasks:w,loadTasks:b,touchTask:v,currentTask:N,setCurrentTask:p,editorView:z,setEditorView:U,isExecuting:X,onSave:L,onRun:()=>E(N,N,p),onRunSnapshot:I=>E(I||N,N,p),results:oe,pinnedResults:ke,onConfirm:h,onNotify:d,onPinResults:Ue,onUnpinResults:Ie,runId:q,onStop:()=>ne(),onTaskLoaded:Ae,isHeadfulOpen:$,onOpenHeadful:(I,H,de,be)=>Q(I,H,de,be),onStopHeadful:Z,useNovnc:P})}),l.jsx(ga,{path:"/settings",element:l.jsx(xy,{onClearStorage:He,onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"/executions",element:l.jsx(vy,{onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"/executions/:id",element:l.jsx(Sy,{onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"/captures",element:l.jsx(Ey,{onConfirm:h,onNotify:d})}),l.jsx(ga,{path:"*",element:l.jsx($p,{onBack:()=>i("/dashboard")})})]})]}),l.jsxs("div",{className:"h-full",children:[r&&l.jsx(ky,{message:r.message,tone:r.tone,onClose:()=>c(null)}),f&&l.jsx(Ay,{request:f,onResolve:m}),K]})}x0.createRoot(document.getElementById("root")).render(l.jsx(Fe.StrictMode,{children:l.jsx(Bg,{children:l.jsx(Vy,{})})}));
|