@fork-api/chat-sdk 0.1.178 → 0.1.180

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/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as kr from'react';import kr__default,{createContext,useState,useRef,useEffect,useCallback,useMemo,startTransition,Children,useContext,isValidElement}from'react';import*as mo from'react-dom';import {createPortal}from'react-dom';import*as ho from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as yo from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,BadgeCheck,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var tt="__FORK_SHARED__";function ur(){var t,r,n,o;let e=globalThis;return e[tt]||(e[tt]={}),(t=e[tt]).react||(t.react=kr),(r=e[tt])["react-dom"]||(r["react-dom"]=mo),(n=e[tt])["react/jsx-runtime"]||(n["react/jsx-runtime"]=ho),(o=e[tt])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=yo),e[tt]}function cr(e){return Object.assign(ur(),e)}var rn=false,dr=null,fr=null;function nn(e,t,r){rn=e,dr=t,fr=r;}function ce(){if(!rn)return {};let e={};return dr&&(e["X-Fork-App-Id"]=dr),fr&&(e["X-Fork-Container-Id"]=fr),e}async function pr(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let s=await o.json(),i={};for(let[l,f]of Object.entries(s.modules)){let w=f.moduleUrl??f.bundleUrl??null,h=f.legacyModuleUrl??f.legacyBundleUrl??null;i[l]={forkId:f.forkId,moduleUrl:w,legacyModuleUrl:h,bundleUrl:f.bundleUrl??w,legacyBundleUrl:f.legacyBundleUrl??h,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,highlightHint:f.highlightHint,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var ko="fork:manifest:v1";function gr(e,t,r){return `${ko}:${e}:${t}:${r}`}function bo(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(gr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function wo(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(gr(e,t,r),JSON.stringify(n));}catch{}}function vo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(gr(e,t,r));}catch{}}function Fo(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,l]of r){let f=t.slots[i];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,l]of o){let f=t.modules[i];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}return false}var jt={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},an=createContext(null),Ao=12e3,Io=45e3,on="fork:activity:v1",Ro=new Set(["pending","running","building"]),Co="Setting up environment";function $e(e){return Ro.has(e)}function Eo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function $o(e,t){let r=Eo(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function sn(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function Kt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function yt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function rt(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function nt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function To(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function Mo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:$e(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function Po(e){let t=e.filter(o=>$e(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():Co,detail:s?To(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function mr(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function _o(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let l=i.bundleUrl??i.legacyBundleUrl;l&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:mr(e,l),revealPending:i.revealPending===true,createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function Lo(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:mr(e,s),cssUrls:(o.cssUrls??[]).map(i=>mr(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function Ho(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,l="userHash"in e?e.userHash:void 0,f="authUrl"in e?e.authUrl:void 0,[w,h]=useState({}),[p,F]=useState(i?{userId:i,userHash:l}:null),[I,y]=useState(!!i),[u,O]=useState(jt),[P,R]=useState(false),[g,C]=useState(false),[_,D]=useState({}),[U,T]=useState(!o),[se,W]=useState(0),[A,S]=useState(null),[N,B]=useState(false),[K,X]=useState([]),[G,q]=useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),L=useRef(new Map),k=useRef(new Map),[E,x]=useState(0),d=useRef(new Set),M=useRef(new Map),v=useRef(void 0),j=useRef(new Map),ne=useRef([]),Ee=useRef(new Set),Le=useRef(false);ur(),useEffect(()=>{if(!o||!p?.userHash||!p.userId){O(jt),R(true);return}let c=false;R(false);let m=new URLSearchParams({app:o});return fetch(`${r}/api/v1/admin/containers?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":p.userId,"X-Fork-User-Hash":p.userHash}}).then(async b=>b.status===403||!b.ok?null:b.json()).then(b=>{if(c)return;if(!b){O(jt),R(true);return}let V=Array.isArray(b.containers)?b.containers:[],Y=b.currentContainerId??null,Q=V.find(Z=>Z.id===Y)?.name??null;O({isAdmin:true,actingUserId:typeof b.actingUserId=="string"?b.actingUserId:null,containerId:Y,containerName:Q,containers:V}),R(true);}).catch(()=>{c||(O(jt),R(true));}),()=>{c=true;}},[t,o,p?.userHash,p?.userId,r]),useEffect(()=>{nn(u.isAdmin,o??null,u.containerId);},[u.isAdmin,u.containerId,o]);let Ge=useCallback((c,m)=>{O(b=>{if(!b.isAdmin)return b;let V=b.containers.find(Z=>Z.id===c),Y=m??V?.name??null,Q=V?b.containers.map(Z=>({...Z,isPrimary:Z.id===c})):[{id:c,name:Y??"New container",isPrimary:true,forkCount:0},...b.containers.map(Z=>({...Z,isPrimary:false}))];return {...b,containerId:c,containerName:Y,containers:Q}}),C(false);},[]);s&&v.current!==s&&(cr(s),v.current=s),useEffect(()=>{f&&(y(false),fetch(f,{credentials:"include"}).then(c=>{if(!c.ok)throw new Error(`Auth endpoint returned ${c.status}`);return c.json()}).then(c=>{if(!c.userId||typeof c.userId!="string")throw new Error("authUrl response must include userId");F({userId:c.userId,userHash:typeof c.userHash=="string"?c.userHash:void 0});}).catch(c=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",c.message);}).finally(()=>{y(true);}));},[f]),useEffect(()=>{!f&&i&&(F({userId:i,userHash:l}),y(true));},[i,l,f]);let J=p?.userId??"",re=p?.userHash,He=!!o,Fe=useCallback(async()=>{if(!He){S(null),B(false),D({}),T(true),W(m=>m+1);return}if(!I){T(false);return}if(!J||!o){S(null),B(false),h({}),D({}),T(true),W(m=>m+1);return}T(false);let c=u.isAdmin?u.containerId:null;if(u.isAdmin&&g){B(true),h({}),D({}),W(m=>m+1),T(true);return}try{let m=await pr({baseUrl:r,apiKey:t,appId:o,userId:J,userHash:re,containerId:c??void 0});m&&(S(m.containerId),B(u.isAdmin?!1:!!m.forksPaused),h(_o(r,m,J,o)),D(Lo(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch fork manifest:",m.message),S(null),B(false),h({}),D({});}finally{W(m=>m+1),T(true);}},[t,o,r,I,He,re,J,u.isAdmin,u.containerId,g]);useEffect(()=>{if(!J||o)return;let c=new URLSearchParams({userId:J});re&&c.set("userHash",re),fetch(`${r}/api/v1/forks/active?${c.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ce()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{m&&typeof m=="object"&&h(m);}).catch(()=>{});},[t,o,J,re,r]),useEffect(()=>{Fe();},[Fe]);let Me=useCallback(async c=>{if(o){if(u.isAdmin){C(c),B(c),c?(h({}),D({}),W(m=>m+1)):await Fe();return}if(J){B(c),c&&(h({}),D({}),W(m=>m+1));try{let m=await fetch(`${r}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:c,userId:J,userHash:re})});if(!m.ok)throw new Error(`${m.status}`);c||await Fe();}catch(m){console.error("[ForkProvider] Failed to persist fork pause state:",m?.message??m),Fe().catch(()=>{});}}}},[t,o,r,Fe,u.isAdmin,re,J]),Ye=useCallback((c,m)=>{h(b=>({...b,[c]:m}));},[]),rr=useCallback(c=>{h(m=>{let b={...m};return delete b[c],b});},[]),Mt=useCallback(c=>{d.current.add(c);},[]),nr=useCallback(c=>d.current.has(c)?(d.current.delete(c),true):false,[]),Pt=useCallback(c=>{if(c.slotId&&h(b=>{let V=b[c.slotId];return !V||V.id!==c.id||!V.revealPending?b:{...b,[c.slotId]:{...V,revealPending:false}}}),u.isAdmin||!J)return;let m={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":J};re&&(m["X-Fork-User-Hash"]=re),fetch(`${r}/api/v1/forks/reveals`,{method:"POST",headers:m,body:JSON.stringify({forkId:c.id,userId:J,userHash:re})}).catch(()=>{});},[t,r,u.isAdmin,re,J]),ae=useCallback((c,m)=>{M.current.set(c,m);},[]),it=useCallback((c,m)=>M.current.get(c)!==m?false:(M.current.delete(c),true),[]),or=useCallback(c=>{if(!o)return;let m=JSON.stringify(c);L.current.get(c.id)===m||k.current.get(c.id)?.signature===m||(k.current.set(c.id,{boundary:c,signature:m}),x(V=>V+1));},[o]);useEffect(()=>{if(!o||k.current.size===0)return;let c=setTimeout(()=>{let m=Array.from(k.current.values());m.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:m.map(b=>b.boundary)})}).then(b=>{if(!b.ok)throw new Error(`${b.status}`)}).then(()=>{for(let b of m)k.current.get(b.boundary.id)?.signature===b.signature&&(k.current.delete(b.boundary.id),L.current.set(b.boundary.id,b.signature));}).catch(b=>{console.error("[ForkProvider] Failed to register module boundaries:",b.message);});},50);return ()=>{clearTimeout(c);}},[t,o,r,E]);let _t=useCallback(c=>_[c],[_]),ft=u.isAdmin?`admin:${u.actingUserId??"op"}`:J,Qe=`${t}:${o||"no-app"}:${A||"no-container"}:${ft||"anonymous"}`,Oe=u.isAdmin?`op:${u.actingUserId??"op"}`:J,Ze=`${t}:${o||"no-app"}:${Oe||"anonymous"}`,Ie=`${on}:seen:${Qe}`,be=`${on}:tracked:${Qe}`;useEffect(()=>{ne.current=K;},[K]);let Ne=useCallback(()=>{let c={Authorization:`Bearer ${t}`,...ce()};return o&&(c["X-Fork-App-Id"]=o),J&&(c["X-Fork-User-Id"]=J),re&&(c["X-Fork-User-Hash"]=re),c},[t,o,re,J]);useEffect(()=>{if(typeof window>"u")return;let c=window.__FORK_RUNTIME__,m={dataFetch:async(b,V,Y="POST")=>{if(!o||!A)throw new Error("Fork data is unavailable until appId and containerId are resolved");let Q=typeof b=="string"&&b.startsWith("/")?b:`/${String(b||"")}`,Z=Q.startsWith("/api/v1/data")?Q:`/api/v1/data${Q}`,de=Y.toUpperCase(),ie=new URL(`${r}${Z}`),pe={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...ce()};J&&(pe["X-Fork-User-Id"]=J),re&&(pe["X-Fork-User-Hash"]=re);let ge={method:de,headers:pe};de==="GET"?(ie.searchParams.set("appId",o),ie.searchParams.set("containerId",A)):ge.body=JSON.stringify({appId:o,containerId:A,...V&&typeof V=="object"?V:{}});let oe=await fetch(ie.toString(),ge),fe=await oe.json().catch(()=>({}));if(!oe.ok)throw new Error(typeof fe?.error=="string"?fe.error:`Fork data API ${oe.status}`);return fe}};return window.__FORK_RUNTIME__=m,()=>{window.__FORK_RUNTIME__===m&&(window.__FORK_RUNTIME__=c);}},[t,o,r,A,re,J]);let Ue=useCallback(async()=>{if(!A||!P)return;let c=new URLSearchParams({container_id:A}),m=await fetch(`${r}/api/v1/forks?${c.toString()}`,{headers:Ne()}).catch(()=>null);if(!m||!m.ok)return;let b=await m.json().catch(()=>({})),V=Array.isArray(b.forks)?b.forks:[],Y=rt(Ie),Q=rt(be),Z=false,de=new Map(ne.current.map(pe=>[pe.id,pe])),ie=[];for(let pe of V){let ge=sn(pe);$e(ge.status)&&!Q.has(ge.id)&&(Q.add(ge.id),Z=true);let oe=de.get(ge.id),fe=oe?$e(oe.status):false,Re=yt(ge);ge.status==="complete"&&(Q.has(ge.id)||fe)&&!Y.has(Re)&&!Ee.current.has(Re)&&!oe?.unread&&(Le.current||Q.has(ge.id)||fe)&&(Ee.current.add(Re),ie.push(ge));}if(X(pe=>{let ge=new Map(pe.map(me=>[me.id,me])),oe=new Set,fe=new Map;for(let me of V){let ve=sn(me);oe.add(ve.id);let Te=ge.get(ve.id),_e=Te?$e(Te.status):false,lt=yt(ve),Ht=ve.status==="complete"&&(Q.has(ve.id)||_e)&&!Y.has(lt),Ce=Kt(Te,{...ve,unread:Ht});fe.set(ve.id,Ce);}for(let me of pe)oe.has(me.id)||($e(me.status)||me.unread)&&fe.set(me.id,me);let Re=[...fe.values()].sort((me,ve)=>Date.parse(ve.updatedAt)-Date.parse(me.updatedAt));return ne.current=Re,Re}),Z&&nt(be,Q),ie.length>0){for(let pe of ie)pe.targetKind==="module"&&ae(pe.targetId,pe.id);Fe().catch(()=>{});}Le.current=true;},[Ie,be,P,r,Ne,A,Fe,ae]),pt=useCallback((c,m)=>{let b=$o(c,m);if(!b)return;let V=c.containerId??c._containerId;if(V&&!A&&S(V),$e(b.status)){let Z=rt(be);Z.has(b.id)||(Z.add(b.id),nt(be,Z)),B(false),u.isAdmin&&C(false);}let Y=new Map(ne.current.map(Z=>[Z.id,Z]));Y.set(b.id,Kt(Y.get(b.id),b));let Q=[...Y.values()].sort((Z,de)=>Date.parse(de.updatedAt)-Date.parse(Z.updatedAt));ne.current=Q,X(Q);},[be,t,o,A,u.isAdmin]),Pe=useCallback((c,m)=>{let b=Mo(m),V=rt(Ie),Y=rt(be),Q=ne.current.find(oe=>oe.id===c),Z=Q?$e(Q.status):false;b.status&&$e(b.status)&&!Y.has(c)&&(Y.add(c),nt(be,Y));let de=Q?Kt(Q,{...Q,...b}):null,ie=de?yt(de):null,pe=!!(de&&de.status==="complete"&&(Y.has(c)||Z)&&ie&&!V.has(ie)&&!Ee.current.has(ie)&&!Q?.unread),ge=m.type==="complete"&&Q?.targetKind==="module"?Q.targetId:null;if(X(oe=>{let fe=oe.find(_e=>_e.id===c);if(!fe)return oe;let Re=Kt(fe,{...fe,...b}),me=Re.status==="complete"&&(Y.has(c)||$e(fe.status))&&!V.has(yt(Re)),ve={...Re,unread:me},Te=oe.map(_e=>_e.id===c?ve:_e).sort((_e,lt)=>Date.parse(lt.updatedAt)-Date.parse(_e.updatedAt));return ne.current=Te,Te}),pe&&de&&ie&&Ee.current.add(ie),m.type==="complete"){let oe=m.data&&typeof m.data=="object"?m.data:{},fe=typeof oe.boundaryId=="string"?oe.boundaryId:ge;fe&&ae(fe,c),Fe().catch(()=>{});}},[Ie,be,Fe,ae]),Lt=useCallback(c=>{let m=rt(Ie),b=rt(be),V=false,Y=false;for(let Q of ne.current){if(Q.status!=="complete"||c&&Q.id!==c)continue;let Z=yt(Q);m.has(Z)||(m.add(Z),V=true),b.delete(Q.id)&&(Y=true);}X(Q=>{let Z=Q.map(de=>de.status!=="complete"||c&&de.id!==c?de:{...de,unread:false});return ne.current=Z,Z}),V&&nt(Ie,m),Y&&nt(be,b);},[Ie,be]);useEffect(()=>{Le.current=false,Ee.current.clear(),X([]);for(let c of j.current.values())c.close();j.current.clear(),A&&Ue();},[A,Ue]),useEffect(()=>{if(typeof document>"u")return;let c=()=>{let m=document.visibilityState!=="hidden";q(m),m&&A&&Ue();};return document.addEventListener("visibilitychange",c),window.addEventListener("focus",c),window.addEventListener("online",c),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("focus",c),window.removeEventListener("online",c);}},[A,Ue]),useEffect(()=>{let c=K.filter(V=>$e(V.status));if(!A||c.length===0)return;let m=G?Ao:Io,b=window.setInterval(()=>{Ue();},m);return ()=>window.clearInterval(b)},[A,G,K,Ue]),useEffect(()=>{for(let c of j.current.values())c.close();j.current.clear();},[t,r,u.containerId,re,J]),useEffect(()=>{let c=new Set(K.filter(m=>$e(m.status)).map(m=>m.id));for(let[m,b]of j.current.entries())c.has(m)||(b.close(),j.current.delete(m));for(let m of c){if(j.current.has(m))continue;let b=new URLSearchParams({key:t});J&&b.set("userId",J),re&&b.set("userHash",re),u.isAdmin&&u.containerId&&b.set("containerId",u.containerId);let V=new EventSource(`${r}/api/v1/forks/${m}/events?${b.toString()}`);V.onmessage=Y=>{try{Pe(m,JSON.parse(Y.data));}catch{}},V.onerror=()=>{V.close(),j.current.delete(m);},j.current.set(m,V);}},[t,r,K,u.isAdmin,u.containerId,Pe,re,J]),useEffect(()=>()=>{for(let c of j.current.values())c.close();j.current.clear();},[]);let Ve=Po(K),at=useCallback(async()=>{if(!J)throw new Error("Reset requires a resolved user identity.");let c=new URLSearchParams({userId:J});re&&c.set("userHash",re);let m={Authorization:`Bearer ${t}`,...ce()};o&&(m["X-Fork-App-Id"]=o);let b=await fetch(`${r}/api/v1/forks/all?${c.toString()}`,{method:"DELETE",headers:m});if(!b.ok){let Y=await b.json().catch(()=>({}));throw new Error(Y.error||`API error: ${b.status}`)}let V=await b.json().catch(()=>({}));return h({}),D({}),T(true),W(Y=>Y+1),X([]),Ee.current.clear(),nt(Ie,new Set),nt(be,new Set),d.current.clear(),M.current.clear(),V},[Ie,be,t,o,r,re,J]);return jsx(an.Provider,{value:{apiKey:t,userId:J,userHash:re,baseUrl:r,appId:o,forks:w,moduleOverridesEnabled:He,moduleManifestReady:U,moduleManifestVersion:se,currentContainerId:A,forksPaused:N,setForksPaused:Me,forkActivities:K,activitySummary:Ve,adminContext:u,setAdminContainer:Ge,trackForkActivity:pt,recordForkActivityEvent:Pe,markForkActivitySeen:Lt,refreshForkActivities:Ue,setSlotFork:Ye,clearSlotFork:rr,skipAnimationForSlot:Mt,shouldSkipAnimation:nr,markRevealSeen:Pt,queueBoundaryAnimation:ae,consumeBoundaryAnimation:it,registerBoundary:or,getBoundaryOverride:_t,refreshModuleManifest:Fe,resetAllForks:at,highlightScope:Ze},children:n})}function we(){let e=useContext(an);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function zt(e){return we().forks[e]}var kt=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(s=>s());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};var hr=new Set;function br(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var un=new Set;function cn(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Do(e,t){let r=[];for(let n of t)if(!e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jo(e,t){let r=[];for(let n of e)if(!t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function fn(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let h=0;h<e.length;h++){let{rect:p,borderRadius:F}=e[h],I=p.left-.5,y=p.top-.5,u=p.width+1,O=p.height+1,P=Math.min(F+.5,u/2,O/2),R=fn(I,y,u,O,P),g=`__fork-glow-${h}`,C=document.createElementNS(t,"filter");C.setAttribute("id",g),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let _=document.createElementNS(t,"feGaussianBlur");_.setAttribute("in","SourceGraphic"),_.setAttribute("stdDeviation","8"),C.appendChild(_),o.appendChild(C);let D=`__fork-mask-${h}`,U=document.createElementNS(t,"mask");U.setAttribute("id",D),U.setAttribute("maskUnits","userSpaceOnUse"),U.setAttribute("x",String(I-200)),U.setAttribute("y",String(y-200)),U.setAttribute("width",String(u+400)),U.setAttribute("height",String(O+400));let T=document.createElementNS(t,"rect");T.setAttribute("x",String(I-200)),T.setAttribute("y",String(y-200)),T.setAttribute("width",String(u+400)),T.setAttribute("height",String(O+400)),T.setAttribute("fill","white"),U.appendChild(T);let se=document.createElementNS(t,"path");se.setAttribute("d",R),se.setAttribute("fill","black"),U.appendChild(se),o.appendChild(U);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${D})`),W.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${g})`);let S=document.createElementNS(t,"path");S.setAttribute("d",R),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),A.appendChild(S),W.appendChild(A),n.appendChild(W);let N=document.createElementNS(t,"path");N.setAttribute("d",R),N.setAttribute("fill","none"),N.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),N.setAttribute("stroke-width","2"),N.setAttribute("stroke-linecap","round"),N.setAttribute("opacity","0"),n.appendChild(N),s.push(S,N),S.__group=W;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let h=0;h<s.length;h+=2){let p=s[h],F=s[h+1],I=p.__group,y=F.getTotalLength(),u=p.getTotalLength();if(y<=0)continue;let O=y*.35;F.setAttribute("stroke-dasharray",`${O} ${y-O}`),F.setAttribute("stroke-dashoffset","0"),i.push(F.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*y,opacity:.92,offset:.06},{strokeDashoffset:-2*y,opacity:.92,offset:.92},{strokeDashoffset:-2.25*y,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let P=u*.35;p.setAttribute("stroke-dasharray",`${P} ${u-P}`),p.setAttribute("stroke-dashoffset","0"),i.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*u,offset:.06},{strokeDashoffset:-2*u,offset:.92},{strokeDashoffset:-2.25*u,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of i)try{p.cancel();}catch{}let h=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});h.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Ko(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let w=l.left,h=l.top,p=l.width,F=l.height,I=Math.min(f,p/2,F/2),y=fn(w,h,p,F,I),u=document.createElementNS(t,"path");u.setAttribute("d",y),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),u.setAttribute("stroke-width","1.5"),u.setAttribute("stroke-dasharray","8 4"),u.setAttribute("stroke-linecap","round"),u.setAttribute("filter","url(#__fork-removed-shadow)"),u.setAttribute("opacity","0"),n.appendChild(u),u.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zo(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var Wo=kr__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&zo(e.hostProps,t.hostProps)),yr=class extends kr__default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function pn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){br(t,e);let i=zt(e),{baseUrl:l,apiKey:f,appId:w,shouldSkipAnimation:h,markRevealSeen:p}=we(),[F,I]=useState(null),y=useRef(null),u=useRef(null),O=useRef(null),P=useRef(false),R=useRef(null),g=useRef(null),C=!!(n||o),_=useRef(null);C&&!_.current&&(_.current=new kt(e));let D=useRef(o);if(D.current=o,useEffect(()=>{if(C)return ()=>{_.current?.destroy(),_.current=null;}},[C,e]),C&&_.current&&n)for(let[A,S]of Object.entries(n))_.current.set(A,S);useEffect(()=>{if(!C)return;_.current||(_.current=new kt(e));let A=_.current,S=Object.keys(D.current||{}).map(N=>A.on(N,(...B)=>D.current?.[N]?.(...B)));return ()=>S.forEach(N=>N())},[C,e]),useEffect(()=>{if(un.has(e))return;un.add(e);let A={id:e,appId:w,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${l}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"},body:JSON.stringify(A)}).catch(()=>{});},[e,l,f,r,w,s]);let U=i?.id||null;useEffect(()=>{if(i?.bundleUrl,y.current,u.current,!i?.bundleUrl||!U){return}let A=`${l}${i.bundleUrl.replace("bundle.js","component.js")}`,S=i.revealPending===true&&!hr.has(U),N=h(e),B=!N&&S;if(i.revealPending,N&&S&&(hr.add(U),p(i)),B&&u.current){let L=cn(u.current);O.current=L,P.current=true,`${e}${L.length}`;}window.__FORK_REACT__=kr__default,window.__FORK_REACT_DOM__=mo,window.__FORK_REACT_JSX__=ho;let K=Date.now(),X=`${l}${i.bundleUrl.replace("bundle.js","component.css")}?t=${K}`,G=document.createElement("link");G.rel="stylesheet",G.href=X,G.dataset.forkSlot=e,document.head.appendChild(G);let q=document.createElement("script");return q.src=A+"?t="+K,q.onload=()=>{let L=window.__FORK_EXPORT__;if(L?.default){if(u.current&&O.current&&P.current){let k=u.current.getBoundingClientRect(),E=u.current.cloneNode(true);E.setAttribute("data-fork-clone-overlay","true"),E.style.position="fixed",E.style.top=`${k.top}px`,E.style.left=`${k.left}px`,E.style.width=`${k.width}px`,E.style.height=`${k.height}px`,E.style.flex="none",E.style.minHeight="auto",E.style.zIndex="9998",E.style.pointerEvents="none",E.style.overflow="hidden";let x=getComputedStyle(u.current).backgroundColor;E.style.backgroundColor=x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"?x:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(E);let d=u.current.querySelectorAll("*"),M=E.querySelectorAll("*");for(let v=0;v<d.length;v++)d[v].scrollTop!==0&&(M[v].scrollTop=d[v].scrollTop),d[v].scrollLeft!==0&&(M[v].scrollLeft=d[v].scrollLeft);R.current=E;}I(()=>L.default),y.current=U;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},q.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(q),()=>{q.remove(),G.remove(),g.current&&(clearTimeout(g.current),g.current=null),R.current&&(R.current.remove(),R.current=null);}},[U,l,e]),useEffect(()=>{if(!P.current||!F||!u.current){`${e}${P.current}`,u.current;return}let A=O.current;if(!A){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!u.current)return;let S=cn(u.current),N=Do(A,S),B=jo(A,S),K=R.current;if(`${e}${N.length}${B.length}`,B.length>0&&K){let X=Ko(B);g.current=setTimeout(()=>{g.current=null;let G=400;K.animate([{opacity:1},{opacity:0}],{duration:G,fill:"forwards"}),X.animate([{opacity:1},{opacity:0}],{duration:G,fill:"forwards"}),setTimeout(()=>{K.remove(),X.remove(),R.current=null,N.length>0&&(dn(N));},G);},3500);}else K&&(K.remove(),R.current=null),N.length>0&&(dn(N));O.current=null,P.current=false,i&&U&&(hr.add(U),p(i),`${e}`);});});},[F]);let T={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:u,style:T,children:t});if(!F)return jsx("div",{ref:u,style:T,children:t});let W=t?.props??{};return jsx(yr,{slotId:e,resetKey:U,fallback:jsx("div",{ref:u,style:T,children:t}),children:jsx(Wo,{component:F,containerRef:u,wrapperStyle:T,hostProps:W})})}var mn=new Set;function qo(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function hn(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,s]of Object.entries(n))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&hn(n.children,t);}),t}function Xo({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:l="iframe",shared:f,events:w}){if(br(r,e),l==="direct")return jsx(pn,{slotId:e,githubRepo:s,shared:f,events:w,entityBindings:o,children:r});let h=zt(e),{baseUrl:p,apiKey:F,appId:I,userId:y,userHash:u,currentContainerId:O}=we(),P=useRef(null),R=useRef(false),g=useRef(null),C=useRef(i);C.current=i;let _=useRef(t);_.current=t;let D=useRef(n);D.current=n,useEffect(()=>{if(typeof process<"u")return;let W=hn(r),A=new Set(i?Object.keys(i):[]),S=[...W].filter(N=>!A.has(N));S.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
- `+S.map(N=>` - ${N}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{mn.has(e)||(mn.add(e),fetch(`${p}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?qo(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:l||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,p,F,s,I,o]);let U=useCallback(W=>{let A=P.current;if(A?.contentWindow&&R.current){let S=C.current?Object.keys(C.current):[];A.contentWindow.postMessage({type:"slot:props",props:W,callbackNames:S},"*"),g.current=null;}else g.current=W;},[]),T=useCallback((W,A)=>{let S=D.current;return !S||S.length===0?false:S.some(N=>{let[B,K]=N.split(" "),X=A.split("?")[0];return W.toUpperCase()===B.toUpperCase()&&X.startsWith(K)})},[]);if(useEffect(()=>{if(!h?.bundleUrl)return;let W=async A=>{if(A.source===P.current?.contentWindow){if(A.data?.type==="slot:ready")R.current=true,P.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:D.current||[]},"*"),D.current,g.current?U(g.current):U(_.current||{});else if(A.data?.type==="slot:event"){let S=A.data.event;S?.navigate&&(window.location.hash=S.navigate);}else if(A.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(A.data.text).catch(S=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,S.message);});else if(A.data?.type==="slot:callback"){let{name:S,args:N}=A.data,B=C.current?.[S];B?(B(...N||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${S}`);}else if(A.data?.type==="slot:fetch"){let{id:S,method:N,url:B,body:K}=A.data,X=P.current?.contentWindow;if(!X)return;let G=N||"GET";if(!T(G,B)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${S}: ${G} ${B} \u2014 not in allowedFetches`),X.postMessage({type:"slot:fetch-response",id:S,error:`Fetch not allowed: ${G} ${B}`},"*");return}try{let q={method:G};K&&G!=="GET"&&(q.headers={"Content-Type":"application/json"},q.body=JSON.stringify(K));let L=await fetch(B,q),k=await L.json();`${e}${S}${L.status}`,X.postMessage({type:"slot:fetch-response",id:S,data:k,status:L.status},"*");}catch(q){console.error(`[ForkSlot:${e}] fetch #${S} failed:`,q.message),X.postMessage({type:"slot:fetch-response",id:S,error:q.message},"*");}}else if(A.data?.type==="slot:fork-data"){let{id:S,path:N,method:B,body:K}=A.data,X=P.current?.contentWindow;if(!X)return;if(!O||!I){X.postMessage({type:"slot:fork-data-response",id:S,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let G=typeof N=="string"&&N.startsWith("/")?N:`/${String(N||"")}`,q=G.startsWith("/api/v1/data")?G:`/api/v1/data${G}`;try{let L={Authorization:`Bearer ${F}`,"Content-Type":"application/json","X-Fork-App-Id":I,...ce()};y&&(L["X-Fork-User-Id"]=y),u&&(L["X-Fork-User-Hash"]=u);let k=typeof B=="string"?B.toUpperCase():"POST",E=new URL(`${p}${q}`),x={method:k,headers:L};k==="GET"?(E.searchParams.set("appId",I),E.searchParams.set("containerId",O)):x.body=JSON.stringify({appId:I,containerId:O,...K&&typeof K=="object"?K:{}});let d=await fetch(E.toString(),x),M=await d.json().catch(()=>({}));if(!d.ok){let v=typeof M?.error=="string"?M.error:`Fork data API ${d.status}`;X.postMessage({type:"slot:fork-data-response",id:S,error:v,status:d.status},"*");return}X.postMessage({type:"slot:fork-data-response",id:S,data:M,status:d.status},"*");}catch(L){X.postMessage({type:"slot:fork-data-response",id:S,error:L.message},"*");}}}};return window.addEventListener("message",W),()=>{window.removeEventListener("message",W),R.current=false;}},[h?.bundleUrl,e,U,T,O,I,F,p,u,y]),useEffect(()=>{h?.bundleUrl&&R.current&&U(t||{});},[t,h?.bundleUrl,U]),!h||h.status!=="complete"||!h.bundleUrl)return `${e}${h?.status||"none"}${h?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${h.bundleUrl}`;let se=`${p}${h.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:P,src:se,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Vt({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var yn=5600,vr=2147483002;function es(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ts(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Fr(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function rs(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function Sr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=useState(false),[s,i]=useState(false),[l,f]=useState(null),[w,h]=useState(null),[p,F]=useState(null),I=useRef(0),y=n?48:40,u=es(r),O=!!(u&&r?.state==="complete"&&r.unreadCompletedCount>0),P=O?u:w?.key??null,R=!!(r&&r.state==="running"&&r.runningCount>0),g=!!(P&&P!==l&&(O||w)),C=R||g,_=O?r?.label:w?.label,D=g?"Built":r?.label??"Fork this app",U=g?_:r?.detail,T=Fr(r?.label??"Fork this app",r?.detail),se=Fr(D,U),W=g?Math.min(420,Math.max(326,se,w?.width??0,I.current+40)):se,A=g?46:40,S=C?[D,U].filter(Boolean).join(" "):rs(r,t)??"Fork this app",N=C?`${D}:${U??""}`:"idle",B=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!C;useEffect(()=>{if(typeof document>"u")return;let d=document.createElement("div");return d.setAttribute("data-fork-button-host","true"),d.style.position="relative",d.style.zIndex=String(vr),document.body.appendChild(d),F(d),()=>{d.remove(),F(null);}},[]),useEffect(()=>{R&&(I.current=T);},[T,R]),useEffect(()=>{!O||!u||!r?.label||h(d=>{if(d?.key===u)return d;let M=Math.min(420,Math.max(326,Fr("Built",r.label),I.current+40));return {key:u,label:r.label,width:M,startedAt:Date.now()}});},[r?.label,u,O]),useEffect(()=>{r&&r.unreadCompletedCount===0&&r.state!=="running"&&h(null);},[r,r?.state,r?.unreadCompletedCount]),useEffect(()=>{if(!P||!g||P===l)return;let d,M=w?.key===P?w.startedAt:Date.now(),v=()=>{let j=Date.now()-M;if(j>=yn&&!ts()||j>=yn*3){f(P);return}d=window.setTimeout(v,250);};return d=window.setTimeout(v,250),()=>{d!==void 0&&window.clearTimeout(d);}},[P,l,w?.key,w?.startedAt,g]);let K=C?{position:"fixed",bottom:24,right:24,zIndex:vr,width:`min(${W}px, calc(100vw - 32px))`,height:A,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:g?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:g?"flex-start":"center",gap:g?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:g?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:vr,width:y,height:y,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},X={minWidth:0,maxWidth:R?286:g?82:U?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},G={minWidth:0,maxWidth:g?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:g?1:0,color:"#64748b",fontSize:R?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},q={minWidth:0,flex:g?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:g?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},L={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:g?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},x=jsxs(Fragment,{children:[jsx("style",{children:`
1
+ import*as br from'react';import br__default,{createContext,useState,useRef,useEffect,useCallback,useMemo,startTransition,Children,useContext,isValidElement}from'react';import*as mo from'react-dom';import {createPortal}from'react-dom';import*as ho from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as yo from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,BadgeCheck,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var et="__FORK_SHARED__";function cr(){var t,r,n,o;let e=globalThis;return e[et]||(e[et]={}),(t=e[et]).react||(t.react=br),(r=e[et])["react-dom"]||(r["react-dom"]=mo),(n=e[et])["react/jsx-runtime"]||(n["react/jsx-runtime"]=ho),(o=e[et])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=yo),e[et]}function dr(e){return Object.assign(cr(),e)}var rn=false,fr=null,pr=null;function nn(e,t,r){rn=e,fr=t,pr=r;}function de(){if(!rn)return {};let e={};return fr&&(e["X-Fork-App-Id"]=fr),pr&&(e["X-Fork-Container-Id"]=pr),e}async function gr(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.userJwt&&(n["X-Fork-User-Jwt"]=e.userJwt),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let s=await o.json(),i={};for(let[l,f]of Object.entries(s.modules)){let b=f.moduleUrl??f.bundleUrl??null,w=f.legacyModuleUrl??f.legacyBundleUrl??null;i[l]={forkId:f.forkId,moduleUrl:b,legacyModuleUrl:w,bundleUrl:f.bundleUrl??b,legacyBundleUrl:f.legacyBundleUrl??w,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,highlightHint:f.highlightHint,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var ko="fork:manifest:v1";function mr(e,t,r){return `${ko}:${e}:${t}:${r}`}function bo(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(mr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function wo(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(mr(e,t,r),JSON.stringify(n));}catch{}}function vo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(mr(e,t,r));}catch{}}function Fo(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,l]of r){let f=t.slots[i];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,l]of o){let f=t.modules[i];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}return false}var Jt={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},an=createContext(null),Ao=12e3,Io=45e3,on="fork:activity:v1",Ro=new Set(["pending","running","building"]),Co="Setting up environment";function Le(e){return Ro.has(e)}function Eo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function $o(e,t){let r=Eo(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function sn(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function Wt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function bt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function tt(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function rt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function To(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function Mo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Le(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function Po(e){let t=e.filter(o=>Le(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():Co,detail:s?To(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function hr(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function _o(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let l=i.bundleUrl??i.legacyBundleUrl;l&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:hr(e,l),revealPending:i.revealPending===true,createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function Lo(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:hr(e,s),cssUrls:(o.cssUrls??[]).map(i=>hr(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function Ho(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,l="userHash"in e?e.userHash:void 0,f="userJwt"in e?e.userJwt:void 0,b="authUrl"in e?e.authUrl:void 0,[w,p]=useState({}),[h,R]=useState(i?{userId:i,userHash:l,userJwt:f}:null),[k,d]=useState(!!i),[F,T]=useState(Jt),[C,g]=useState(false),[$,_]=useState(false),[K,O]=useState({}),[N,ne]=useState(!o),[G,M]=useState(0),[y,L]=useState(null),[B,D]=useState(false),[W,z]=useState([]),[V,U]=useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),S=useRef(new Map),I=useRef(new Map),[A,u]=useState(0),P=useRef(new Set),v=useRef(new Map),J=useRef(void 0),se=useRef(new Map),Ae=useRef([]),Pe=useRef(new Set),Ne=useRef(false);cr(),useEffect(()=>{if(!o||!h?.userId||!(h.userHash||h.userJwt)){T(Jt),g(true);return}let c=false;g(false);let m=new URLSearchParams({app:o});return fetch(`${r}/api/v1/admin/containers?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":h.userId,...h.userHash?{"X-Fork-User-Hash":h.userHash}:{},...h.userJwt?{"X-Fork-User-Jwt":h.userJwt}:{}}}).then(async x=>x.status===403||!x.ok?null:x.json()).then(x=>{if(c)return;if(!x){T(Jt),g(true);return}let q=Array.isArray(x.containers)?x.containers:[],Z=x.currentContainerId??null,Q=q.find(X=>X.id===Z)?.name??null;T({isAdmin:true,actingUserId:typeof x.actingUserId=="string"?x.actingUserId:null,containerId:Z,containerName:Q,containers:q}),g(true);}).catch(()=>{c||(T(Jt),g(true));}),()=>{c=true;}},[t,o,h?.userHash,h?.userJwt,h?.userId,r]),useEffect(()=>{nn(F.isAdmin,o??null,F.containerId);},[F.isAdmin,F.containerId,o]);let ve=useCallback((c,m)=>{T(x=>{if(!x.isAdmin)return x;let q=x.containers.find(X=>X.id===c),Z=m??q?.name??null,Q=q?x.containers.map(X=>({...X,isPrimary:X.id===c})):[{id:c,name:Z??"New container",isPrimary:true,forkCount:0},...x.containers.map(X=>({...X,isPrimary:false}))];return {...x,containerId:c,containerName:Z,containers:Q}}),_(false);},[]);s&&J.current!==s&&(dr(s),J.current=s),useEffect(()=>{b&&(d(false),fetch(b,{credentials:"include"}).then(c=>{if(!c.ok)throw new Error(`Auth endpoint returned ${c.status}`);return c.json()}).then(c=>{if(!c.userId||typeof c.userId!="string")throw new Error("authUrl response must include userId");R({userId:c.userId,userHash:typeof c.userHash=="string"?c.userHash:void 0,userJwt:typeof c.userJwt=="string"?c.userJwt:void 0});}).catch(c=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",c.message);}).finally(()=>{d(true);}));},[b]),useEffect(()=>{!b&&i&&(R({userId:i,userHash:l,userJwt:f}),d(true));},[i,l,f,b]);let Y=h?.userId??"",oe=h?.userHash,st=h?.userJwt,_e=!!o,be=useCallback(async()=>{if(!_e){L(null),D(false),O({}),ne(true),M(m=>m+1);return}if(!k){ne(false);return}if(!Y||!o){L(null),D(false),p({}),O({}),ne(true),M(m=>m+1);return}ne(false);let c=F.isAdmin?F.containerId:null;if(F.isAdmin&&$){D(true),p({}),O({}),M(m=>m+1),ne(true);return}try{let m=await gr({baseUrl:r,apiKey:t,appId:o,userId:Y,userHash:oe,userJwt:st,containerId:c??void 0});m&&(L(m.containerId),D(F.isAdmin?!1:!!m.forksPaused),p(_o(r,m,Y,o)),O(Lo(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch fork manifest:",m.message),L(null),D(false),p({}),O({});}finally{M(m=>m+1),ne(true);}},[t,o,r,k,_e,oe,st,Y,F.isAdmin,F.containerId,$]);useEffect(()=>{if(!Y||o)return;let c=new URLSearchParams({userId:Y});oe&&c.set("userHash",oe),fetch(`${r}/api/v1/forks/active?${c.toString()}`,{headers:{Authorization:`Bearer ${t}`,...de()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{m&&typeof m=="object"&&p(m);}).catch(()=>{});},[t,o,Y,oe,r]),useEffect(()=>{be();},[be]);let sr=useCallback(async c=>{if(o){if(F.isAdmin){_(c),D(c),c?(p({}),O({}),M(m=>m+1)):await be();return}if(Y){D(c),c&&(p({}),O({}),M(m=>m+1));try{let m=await fetch(`${r}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:c,userId:Y,userHash:oe})});if(!m.ok)throw new Error(`${m.status}`);c||await be();}catch(m){console.error("[ForkProvider] Failed to persist fork pause state:",m?.message??m),be().catch(()=>{});}}}},[t,o,r,be,F.isAdmin,oe,Y]),_t=useCallback((c,m)=>{p(x=>({...x,[c]:m}));},[]),ir=useCallback(c=>{p(m=>{let x={...m};return delete x[c],x});},[]),Lt=useCallback(c=>{P.current.add(c);},[]),ge=useCallback(c=>P.current.has(c)?(P.current.delete(c),true):false,[]),it=useCallback(c=>{if(c.slotId&&p(x=>{let q=x[c.slotId];return !q||q.id!==c.id||!q.revealPending?x:{...x,[c.slotId]:{...q,revealPending:false}}}),F.isAdmin||!Y)return;let m={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":Y};oe&&(m["X-Fork-User-Hash"]=oe),fetch(`${r}/api/v1/forks/reveals`,{method:"POST",headers:m,body:JSON.stringify({forkId:c.id,userId:Y,userHash:oe})}).catch(()=>{});},[t,r,F.isAdmin,oe,Y]),Qe=useCallback((c,m)=>{v.current.set(c,m);},[]),Ht=useCallback((c,m)=>v.current.get(c)!==m?false:(v.current.delete(c),true),[]),pt=useCallback(c=>{if(!o)return;let m=JSON.stringify(c);S.current.get(c.id)===m||I.current.get(c.id)?.signature===m||(I.current.set(c.id,{boundary:c,signature:m}),u(q=>q+1));},[o]);useEffect(()=>{if(!o||I.current.size===0)return;let c=setTimeout(()=>{let m=Array.from(I.current.values());m.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:m.map(x=>x.boundary)})}).then(x=>{if(!x.ok)throw new Error(`${x.status}`)}).then(()=>{for(let x of m)I.current.get(x.boundary.id)?.signature===x.signature&&(I.current.delete(x.boundary.id),S.current.set(x.boundary.id,x.signature));}).catch(x=>{console.error("[ForkProvider] Failed to register module boundaries:",x.message);});},50);return ()=>{clearTimeout(c);}},[t,o,r,A]);let at=useCallback(c=>K[c],[K]),Ue=F.isAdmin?`admin:${F.actingUserId??"op"}`:Y,Ve=`${t}:${o||"no-app"}:${y||"no-container"}:${Ue||"anonymous"}`,gt=F.isAdmin?`op:${F.actingUserId??"op"}`:Y,Ot=`${t}:${o||"no-app"}:${gt||"anonymous"}`,Fe=`${on}:seen:${Ve}`,Se=`${on}:tracked:${Ve}`;useEffect(()=>{Ae.current=W;},[W]);let lt=useCallback(()=>{let c={Authorization:`Bearer ${t}`,...de()};return o&&(c["X-Fork-App-Id"]=o),Y&&(c["X-Fork-User-Id"]=Y),oe&&(c["X-Fork-User-Hash"]=oe),c},[t,o,oe,Y]);useEffect(()=>{if(typeof window>"u")return;let c=window.__FORK_RUNTIME__,m={dataFetch:async(x,q,Z="POST")=>{if(!o||!y)throw new Error("Fork data is unavailable until appId and containerId are resolved");let Q=typeof x=="string"&&x.startsWith("/")?x:`/${String(x||"")}`,X=Q.startsWith("/api/v1/data")?Q:`/api/v1/data${Q}`,fe=Z.toUpperCase(),xe=new URL(`${r}${X}`),ie={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...de()};Y&&(ie["X-Fork-User-Id"]=Y),oe&&(ie["X-Fork-User-Hash"]=oe);let me={method:fe,headers:ie};fe==="GET"?(xe.searchParams.set("appId",o),xe.searchParams.set("containerId",y)):me.body=JSON.stringify({appId:o,containerId:y,...q&&typeof q=="object"?q:{}});let le=await fetch(xe.toString(),me),ce=await le.json().catch(()=>({}));if(!le.ok)throw new Error(typeof ce?.error=="string"?ce.error:`Fork data API ${le.status}`);return ce}};return window.__FORK_RUNTIME__=m,()=>{window.__FORK_RUNTIME__===m&&(window.__FORK_RUNTIME__=c);}},[t,o,r,y,oe,Y]);let Ee=useCallback(async()=>{if(!y||!C)return;let c=new URLSearchParams({container_id:y}),m=await fetch(`${r}/api/v1/forks?${c.toString()}`,{headers:lt()}).catch(()=>null);if(!m||!m.ok)return;let x=await m.json().catch(()=>({})),q=Array.isArray(x.forks)?x.forks:[],Z=tt(Fe),Q=tt(Se),X=false,fe=new Map(Ae.current.map(ie=>[ie.id,ie])),xe=[];for(let ie of q){let me=sn(ie);Le(me.status)&&!Q.has(me.id)&&(Q.add(me.id),X=true);let le=fe.get(me.id),ce=le?Le(le.status):false,Ie=bt(me);me.status==="complete"&&(Q.has(me.id)||ce)&&!Z.has(Ie)&&!Pe.current.has(Ie)&&!le?.unread&&(Ne.current||Q.has(me.id)||ce)&&(Pe.current.add(Ie),xe.push(me));}if(z(ie=>{let me=new Map(ie.map(pe=>[pe.id,pe])),le=new Set,ce=new Map;for(let pe of q){let Me=sn(pe);le.add(Me.id);let Be=me.get(Me.id),He=Be?Le(Be.status):false,Re=bt(Me),Ut=Me.status==="complete"&&(Q.has(Me.id)||He)&&!Z.has(Re),mt=Wt(Be,{...Me,unread:Ut});ce.set(Me.id,mt);}for(let pe of ie)le.has(pe.id)||(Le(pe.status)||pe.unread)&&ce.set(pe.id,pe);let Ie=[...ce.values()].sort((pe,Me)=>Date.parse(Me.updatedAt)-Date.parse(pe.updatedAt));return Ae.current=Ie,Ie}),X&&rt(Se,Q),xe.length>0){for(let ie of xe)ie.targetKind==="module"&&Qe(ie.targetId,ie.id);be().catch(()=>{});}Ne.current=true;},[Fe,Se,C,r,lt,y,be,Qe]),Nt=useCallback((c,m)=>{let x=$o(c,m);if(!x)return;let q=c.containerId??c._containerId;if(q&&!y&&L(q),Le(x.status)){let X=tt(Se);X.has(x.id)||(X.add(x.id),rt(Se,X)),D(false),F.isAdmin&&_(false);}let Z=new Map(Ae.current.map(X=>[X.id,X]));Z.set(x.id,Wt(Z.get(x.id),x));let Q=[...Z.values()].sort((X,fe)=>Date.parse(fe.updatedAt)-Date.parse(X.updatedAt));Ae.current=Q,z(Q);},[Se,t,o,y,F.isAdmin]),Oe=useCallback((c,m)=>{let x=Mo(m),q=tt(Fe),Z=tt(Se),Q=Ae.current.find(le=>le.id===c),X=Q?Le(Q.status):false;x.status&&Le(x.status)&&!Z.has(c)&&(Z.add(c),rt(Se,Z));let fe=Q?Wt(Q,{...Q,...x}):null,xe=fe?bt(fe):null,ie=!!(fe&&fe.status==="complete"&&(Z.has(c)||X)&&xe&&!q.has(xe)&&!Pe.current.has(xe)&&!Q?.unread),me=m.type==="complete"&&Q?.targetKind==="module"?Q.targetId:null;if(z(le=>{let ce=le.find(He=>He.id===c);if(!ce)return le;let Ie=Wt(ce,{...ce,...x}),pe=Ie.status==="complete"&&(Z.has(c)||Le(ce.status))&&!q.has(bt(Ie)),Me={...Ie,unread:pe},Be=le.map(He=>He.id===c?Me:He).sort((He,Re)=>Date.parse(Re.updatedAt)-Date.parse(He.updatedAt));return Ae.current=Be,Be}),ie&&fe&&xe&&Pe.current.add(xe),m.type==="complete"){let le=m.data&&typeof m.data=="object"?m.data:{},ce=typeof le.boundaryId=="string"?le.boundaryId:me;ce&&Qe(ce,c),be().catch(()=>{});}},[Fe,Se,be,Qe]),ut=useCallback(c=>{let m=tt(Fe),x=tt(Se),q=false,Z=false;for(let Q of Ae.current){if(Q.status!=="complete"||c&&Q.id!==c)continue;let X=bt(Q);m.has(X)||(m.add(X),q=true),x.delete(Q.id)&&(Z=true);}z(Q=>{let X=Q.map(fe=>fe.status!=="complete"||c&&fe.id!==c?fe:{...fe,unread:false});return Ae.current=X,X}),q&&rt(Fe,m),Z&&rt(Se,x);},[Fe,Se]);useEffect(()=>{Ne.current=false,Pe.current.clear(),z([]);for(let c of se.current.values())c.close();se.current.clear(),y&&Ee();},[y,Ee]),useEffect(()=>{if(typeof document>"u")return;let c=()=>{let m=document.visibilityState!=="hidden";U(m),m&&y&&Ee();};return document.addEventListener("visibilitychange",c),window.addEventListener("focus",c),window.addEventListener("online",c),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("focus",c),window.removeEventListener("online",c);}},[y,Ee]),useEffect(()=>{let c=W.filter(q=>Le(q.status));if(!y||c.length===0)return;let m=V?Ao:Io,x=window.setInterval(()=>{Ee();},m);return ()=>window.clearInterval(x)},[y,V,W,Ee]),useEffect(()=>{for(let c of se.current.values())c.close();se.current.clear();},[t,r,F.containerId,oe,Y]),useEffect(()=>{let c=new Set(W.filter(m=>Le(m.status)).map(m=>m.id));for(let[m,x]of se.current.entries())c.has(m)||(x.close(),se.current.delete(m));for(let m of c){if(se.current.has(m))continue;let x=new URLSearchParams({key:t});Y&&x.set("userId",Y),oe&&x.set("userHash",oe),F.isAdmin&&F.containerId&&x.set("containerId",F.containerId);let q=new EventSource(`${r}/api/v1/forks/${m}/events?${x.toString()}`);q.onmessage=Z=>{try{Oe(m,JSON.parse(Z.data));}catch{}},q.onerror=()=>{q.close(),se.current.delete(m);},se.current.set(m,q);}},[t,r,W,F.isAdmin,F.containerId,Oe,oe,Y]),useEffect(()=>()=>{for(let c of se.current.values())c.close();se.current.clear();},[]);let te=Po(W),qe=useCallback(async()=>{if(!Y)throw new Error("Reset requires a resolved user identity.");let c=new URLSearchParams({userId:Y});oe&&c.set("userHash",oe);let m={Authorization:`Bearer ${t}`,...de()};o&&(m["X-Fork-App-Id"]=o);let x=await fetch(`${r}/api/v1/forks/all?${c.toString()}`,{method:"DELETE",headers:m});if(!x.ok){let Z=await x.json().catch(()=>({}));throw new Error(Z.error||`API error: ${x.status}`)}let q=await x.json().catch(()=>({}));return p({}),O({}),ne(true),M(Z=>Z+1),z([]),Pe.current.clear(),rt(Fe,new Set),rt(Se,new Set),P.current.clear(),v.current.clear(),q},[Fe,Se,t,o,r,oe,Y]);return jsx(an.Provider,{value:{apiKey:t,userId:Y,userHash:oe,baseUrl:r,appId:o,forks:w,moduleOverridesEnabled:_e,moduleManifestReady:N,moduleManifestVersion:G,currentContainerId:y,forksPaused:B,setForksPaused:sr,forkActivities:W,activitySummary:te,adminContext:F,setAdminContainer:ve,trackForkActivity:Nt,recordForkActivityEvent:Oe,markForkActivitySeen:ut,refreshForkActivities:Ee,setSlotFork:_t,clearSlotFork:ir,skipAnimationForSlot:Lt,shouldSkipAnimation:ge,markRevealSeen:it,queueBoundaryAnimation:Qe,consumeBoundaryAnimation:Ht,registerBoundary:pt,getBoundaryOverride:at,refreshModuleManifest:be,resetAllForks:qe,highlightScope:Ot},children:n})}function we(){let e=useContext(an);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Vt(e){return we().forks[e]}var wt=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(s=>s());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};var yr=new Set;function wr(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var un=new Set;function cn(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Do(e,t){let r=[];for(let n of t)if(!e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jo(e,t){let r=[];for(let n of e)if(!t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function fn(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let w=0;w<e.length;w++){let{rect:p,borderRadius:h}=e[w],R=p.left-.5,k=p.top-.5,d=p.width+1,F=p.height+1,T=Math.min(h+.5,d/2,F/2),C=fn(R,k,d,F,T),g=`__fork-glow-${w}`,$=document.createElementNS(t,"filter");$.setAttribute("id",g),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let _=document.createElementNS(t,"feGaussianBlur");_.setAttribute("in","SourceGraphic"),_.setAttribute("stdDeviation","8"),$.appendChild(_),o.appendChild($);let K=`__fork-mask-${w}`,O=document.createElementNS(t,"mask");O.setAttribute("id",K),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(R-200)),O.setAttribute("y",String(k-200)),O.setAttribute("width",String(d+400)),O.setAttribute("height",String(F+400));let N=document.createElementNS(t,"rect");N.setAttribute("x",String(R-200)),N.setAttribute("y",String(k-200)),N.setAttribute("width",String(d+400)),N.setAttribute("height",String(F+400)),N.setAttribute("fill","white"),O.appendChild(N);let ne=document.createElementNS(t,"path");ne.setAttribute("d",C),ne.setAttribute("fill","black"),O.appendChild(ne),o.appendChild(O);let G=document.createElementNS(t,"g");G.setAttribute("mask",`url(#${K})`),G.setAttribute("opacity","0");let M=document.createElementNS(t,"g");M.setAttribute("filter",`url(#${g})`);let y=document.createElementNS(t,"path");y.setAttribute("d",C),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),y.setAttribute("stroke-width","6"),y.setAttribute("stroke-linecap","round"),M.appendChild(y),G.appendChild(M),n.appendChild(G);let L=document.createElementNS(t,"path");L.setAttribute("d",C),L.setAttribute("fill","none"),L.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),L.setAttribute("stroke-width","2"),L.setAttribute("stroke-linecap","round"),L.setAttribute("opacity","0"),n.appendChild(L),s.push(y,L),y.__group=G;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let w=0;w<s.length;w+=2){let p=s[w],h=s[w+1],R=p.__group,k=h.getTotalLength(),d=p.getTotalLength();if(k<=0)continue;let F=k*.35;h.setAttribute("stroke-dasharray",`${F} ${k-F}`),h.setAttribute("stroke-dashoffset","0"),i.push(h.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*k,opacity:.92,offset:.06},{strokeDashoffset:-2*k,opacity:.92,offset:.92},{strokeDashoffset:-2.25*k,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=d*.35;p.setAttribute("stroke-dasharray",`${T} ${d-T}`),p.setAttribute("stroke-dashoffset","0"),i.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*d,offset:.06},{strokeDashoffset:-2*d,offset:.92},{strokeDashoffset:-2.25*d,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,f=()=>{if(l)return;l=true,clearTimeout(b);for(let p of i)try{p.cancel();}catch{}let w=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});w.onfinish=()=>r.remove(),window.removeEventListener("click",f);},b=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Ko(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let b=l.left,w=l.top,p=l.width,h=l.height,R=Math.min(f,p/2,h/2),k=fn(b,w,p,h,R),d=document.createElementNS(t,"path");d.setAttribute("d",k),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),d.setAttribute("stroke-width","1.5"),d.setAttribute("stroke-dasharray","8 4"),d.setAttribute("stroke-linecap","round"),d.setAttribute("filter","url(#__fork-removed-shadow)"),d.setAttribute("opacity","0"),n.appendChild(d),d.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zo(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var Jo=br__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&zo(e.hostProps,t.hostProps)),kr=class extends br__default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function pn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){wr(t,e);let i=Vt(e),{baseUrl:l,apiKey:f,appId:b,shouldSkipAnimation:w,markRevealSeen:p}=we(),[h,R]=useState(null),k=useRef(null),d=useRef(null),F=useRef(null),T=useRef(false),C=useRef(null),g=useRef(null),$=!!(n||o),_=useRef(null);$&&!_.current&&(_.current=new wt(e));let K=useRef(o);if(K.current=o,useEffect(()=>{if($)return ()=>{_.current?.destroy(),_.current=null;}},[$,e]),$&&_.current&&n)for(let[M,y]of Object.entries(n))_.current.set(M,y);useEffect(()=>{if(!$)return;_.current||(_.current=new wt(e));let M=_.current,y=Object.keys(K.current||{}).map(L=>M.on(L,(...B)=>K.current?.[L]?.(...B)));return ()=>y.forEach(L=>L())},[$,e]),useEffect(()=>{if(un.has(e))return;un.add(e);let M={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${l}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"},body:JSON.stringify(M)}).catch(()=>{});},[e,l,f,r,b,s]);let O=i?.id||null;useEffect(()=>{if(i?.bundleUrl,k.current,d.current,!i?.bundleUrl||!O){return}let M=`${l}${i.bundleUrl.replace("bundle.js","component.js")}`,y=i.revealPending===true&&!yr.has(O),L=w(e),B=!L&&y;if(i.revealPending,L&&y&&(yr.add(O),p(i)),B&&d.current){let U=cn(d.current);F.current=U,T.current=true,`${e}${U.length}`;}window.__FORK_REACT__=br__default,window.__FORK_REACT_DOM__=mo,window.__FORK_REACT_JSX__=ho;let D=Date.now(),W=`${l}${i.bundleUrl.replace("bundle.js","component.css")}?t=${D}`,z=document.createElement("link");z.rel="stylesheet",z.href=W,z.dataset.forkSlot=e,document.head.appendChild(z);let V=document.createElement("script");return V.src=M+"?t="+D,V.onload=()=>{let U=window.__FORK_EXPORT__;if(U?.default){if(d.current&&F.current&&T.current){let S=d.current.getBoundingClientRect(),I=d.current.cloneNode(true);I.setAttribute("data-fork-clone-overlay","true"),I.style.position="fixed",I.style.top=`${S.top}px`,I.style.left=`${S.left}px`,I.style.width=`${S.width}px`,I.style.height=`${S.height}px`,I.style.flex="none",I.style.minHeight="auto",I.style.zIndex="9998",I.style.pointerEvents="none",I.style.overflow="hidden";let A=getComputedStyle(d.current).backgroundColor;I.style.backgroundColor=A&&A!=="rgba(0, 0, 0, 0)"&&A!=="transparent"?A:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(I);let u=d.current.querySelectorAll("*"),P=I.querySelectorAll("*");for(let v=0;v<u.length;v++)u[v].scrollTop!==0&&(P[v].scrollTop=u[v].scrollTop),u[v].scrollLeft!==0&&(P[v].scrollLeft=u[v].scrollLeft);C.current=I;}R(()=>U.default),k.current=O;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},V.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(V),()=>{V.remove(),z.remove(),g.current&&(clearTimeout(g.current),g.current=null),C.current&&(C.current.remove(),C.current=null);}},[O,l,e]),useEffect(()=>{if(!T.current||!h||!d.current){`${e}${T.current}`,d.current;return}let M=F.current;if(!M){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!d.current)return;let y=cn(d.current),L=Do(M,y),B=jo(M,y),D=C.current;if(`${e}${L.length}${B.length}`,B.length>0&&D){let W=Ko(B);g.current=setTimeout(()=>{g.current=null;let z=400;D.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),W.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{D.remove(),W.remove(),C.current=null,L.length>0&&(dn(L));},z);},3500);}else D&&(D.remove(),C.current=null),L.length>0&&(dn(L));F.current=null,T.current=false,i&&O&&(yr.add(O),p(i),`${e}`);});});},[h]);let N={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:d,style:N,children:t});if(!h)return jsx("div",{ref:d,style:N,children:t});let G=t?.props??{};return jsx(kr,{slotId:e,resetKey:O,fallback:jsx("div",{ref:d,style:N,children:t}),children:jsx(Jo,{component:h,containerRef:d,wrapperStyle:N,hostProps:G})})}var mn=new Set;function qo(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function hn(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,s]of Object.entries(n))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&hn(n.children,t);}),t}function Xo({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:l="iframe",shared:f,events:b}){if(wr(r,e),l==="direct")return jsx(pn,{slotId:e,githubRepo:s,shared:f,events:b,entityBindings:o,children:r});let w=Vt(e),{baseUrl:p,apiKey:h,appId:R,userId:k,userHash:d,currentContainerId:F}=we(),T=useRef(null),C=useRef(false),g=useRef(null),$=useRef(i);$.current=i;let _=useRef(t);_.current=t;let K=useRef(n);K.current=n,useEffect(()=>{if(typeof process<"u")return;let G=hn(r),M=new Set(i?Object.keys(i):[]),y=[...G].filter(L=>!M.has(L));y.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
+ `+y.map(L=>` - ${L}`).join(`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{mn.has(e)||(mn.add(e),fetch(`${p}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:R,label:e,propsShape:t?qo(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:l||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,p,h,s,R,o]);let O=useCallback(G=>{let M=T.current;if(M?.contentWindow&&C.current){let y=$.current?Object.keys($.current):[];M.contentWindow.postMessage({type:"slot:props",props:G,callbackNames:y},"*"),g.current=null;}else g.current=G;},[]),N=useCallback((G,M)=>{let y=K.current;return !y||y.length===0?false:y.some(L=>{let[B,D]=L.split(" "),W=M.split("?")[0];return G.toUpperCase()===B.toUpperCase()&&W.startsWith(D)})},[]);if(useEffect(()=>{if(!w?.bundleUrl)return;let G=async M=>{if(M.source===T.current?.contentWindow){if(M.data?.type==="slot:ready")C.current=true,T.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:K.current||[]},"*"),K.current,g.current?O(g.current):O(_.current||{});else if(M.data?.type==="slot:event"){let y=M.data.event;y?.navigate&&(window.location.hash=y.navigate);}else if(M.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(M.data.text).catch(y=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,y.message);});else if(M.data?.type==="slot:callback"){let{name:y,args:L}=M.data,B=$.current?.[y];B?(B(...L||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${y}`);}else if(M.data?.type==="slot:fetch"){let{id:y,method:L,url:B,body:D}=M.data,W=T.current?.contentWindow;if(!W)return;let z=L||"GET";if(!N(z,B)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${y}: ${z} ${B} \u2014 not in allowedFetches`),W.postMessage({type:"slot:fetch-response",id:y,error:`Fetch not allowed: ${z} ${B}`},"*");return}try{let V={method:z};D&&z!=="GET"&&(V.headers={"Content-Type":"application/json"},V.body=JSON.stringify(D));let U=await fetch(B,V),S=await U.json();`${e}${y}${U.status}`,W.postMessage({type:"slot:fetch-response",id:y,data:S,status:U.status},"*");}catch(V){console.error(`[ForkSlot:${e}] fetch #${y} failed:`,V.message),W.postMessage({type:"slot:fetch-response",id:y,error:V.message},"*");}}else if(M.data?.type==="slot:fork-data"){let{id:y,path:L,method:B,body:D}=M.data,W=T.current?.contentWindow;if(!W)return;if(!F||!R){W.postMessage({type:"slot:fork-data-response",id:y,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let z=typeof L=="string"&&L.startsWith("/")?L:`/${String(L||"")}`,V=z.startsWith("/api/v1/data")?z:`/api/v1/data${z}`;try{let U={Authorization:`Bearer ${h}`,"Content-Type":"application/json","X-Fork-App-Id":R,...de()};k&&(U["X-Fork-User-Id"]=k),d&&(U["X-Fork-User-Hash"]=d);let S=typeof B=="string"?B.toUpperCase():"POST",I=new URL(`${p}${V}`),A={method:S,headers:U};S==="GET"?(I.searchParams.set("appId",R),I.searchParams.set("containerId",F)):A.body=JSON.stringify({appId:R,containerId:F,...D&&typeof D=="object"?D:{}});let u=await fetch(I.toString(),A),P=await u.json().catch(()=>({}));if(!u.ok){let v=typeof P?.error=="string"?P.error:`Fork data API ${u.status}`;W.postMessage({type:"slot:fork-data-response",id:y,error:v,status:u.status},"*");return}W.postMessage({type:"slot:fork-data-response",id:y,data:P,status:u.status},"*");}catch(U){W.postMessage({type:"slot:fork-data-response",id:y,error:U.message},"*");}}}};return window.addEventListener("message",G),()=>{window.removeEventListener("message",G),C.current=false;}},[w?.bundleUrl,e,O,N,F,R,h,p,d,k]),useEffect(()=>{w?.bundleUrl&&C.current&&O(t||{});},[t,w?.bundleUrl,O]),!w||w.status!=="complete"||!w.bundleUrl)return `${e}${w?.status||"none"}${w?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${w.bundleUrl}`;let ne=`${p}${w.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:T,src:ne,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Xt({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var yn=5600,Fr=2147483002;function es(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ts(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Sr(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function rs(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function xr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=useState(false),[s,i]=useState(false),[l,f]=useState(null),[b,w]=useState(null),[p,h]=useState(null),R=useRef(0),k=n?48:40,d=es(r),F=!!(d&&r?.state==="complete"&&r.unreadCompletedCount>0),T=F?d:b?.key??null,C=!!(r&&r.state==="running"&&r.runningCount>0),g=!!(T&&T!==l&&(F||b)),$=C||g,_=F?r?.label:b?.label,K=g?"Built":r?.label??"Fork this app",O=g?_:r?.detail,N=Sr(r?.label??"Fork this app",r?.detail),ne=Sr(K,O),G=g?Math.min(420,Math.max(326,ne,b?.width??0,R.current+40)):ne,M=g?46:40,y=$?[K,O].filter(Boolean).join(" "):rs(r,t)??"Fork this app",L=$?`${K}:${O??""}`:"idle",B=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!$;useEffect(()=>{if(typeof document>"u")return;let u=document.createElement("div");return u.setAttribute("data-fork-button-host","true"),u.style.position="relative",u.style.zIndex=String(Fr),document.body.appendChild(u),h(u),()=>{u.remove(),h(null);}},[]),useEffect(()=>{C&&(R.current=N);},[N,C]),useEffect(()=>{!F||!d||!r?.label||w(u=>{if(u?.key===d)return u;let P=Math.min(420,Math.max(326,Sr("Built",r.label),R.current+40));return {key:d,label:r.label,width:P,startedAt:Date.now()}});},[r?.label,d,F]),useEffect(()=>{r&&r.unreadCompletedCount===0&&r.state!=="running"&&w(null);},[r,r?.state,r?.unreadCompletedCount]),useEffect(()=>{if(!T||!g||T===l)return;let u,P=b?.key===T?b.startedAt:Date.now(),v=()=>{let J=Date.now()-P;if(J>=yn&&!ts()||J>=yn*3){f(T);return}u=window.setTimeout(v,250);};return u=window.setTimeout(v,250),()=>{u!==void 0&&window.clearTimeout(u);}},[T,l,b?.key,b?.startedAt,g]);let D=$?{position:"fixed",bottom:24,right:24,zIndex:Fr,width:`min(${G}px, calc(100vw - 32px))`,height:M,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:g?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:g?"flex-start":"center",gap:g?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:g?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:Fr,width:k,height:k,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},W={minWidth:0,maxWidth:C?286:g?82:O?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},z={minWidth:0,maxWidth:g?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:g?1:0,color:"#64748b",fontSize:C?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},V={minWidth:0,flex:g?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:g?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},U={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:g?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},A=jsxs(Fragment,{children:[jsx("style",{children:`
4
4
  @keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
5
5
  @keyframes __forkButtonTextSwap {
6
6
  from { opacity: 0; transform: translateY(2px); }
@@ -15,7 +15,7 @@ import*as kr from'react';import kr__default,{createContext,useState,useRef,useEf
15
15
  70% { opacity: 1; transform: scale(1.18); }
16
16
  100% { opacity: 1; transform: scale(1); }
17
17
  }
18
- `}),jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:K,title:S,"aria-label":S,children:[C&&r?jsxs(Fragment,{children:[R?jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(17, 24, 39, 0.18)",borderTopColor:"#111827",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):jsx("span",{"aria-hidden":true,style:L}),jsxs("span",{style:q,children:[jsx("span",{style:X,children:D}),U&&jsx("span",{style:G,children:U})]},N)]}):jsx(Vt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),B&&jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#111827",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return p?createPortal(x,p):x}var cs={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},ds={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},fs={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},ps={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Ar(e){let t=e.data;switch(e.type){case "status":return `${t.message||t.status||"..."}`;case "agent_message":{let r=String(t.content||"");return /failed:/i.test(r)&&(r.includes("ENOENT")||r.includes("{")||r.includes("/Users/"))?"Adapting approach...":r}case "tool_use":return String(t.label||"Working on it");case "build_start":return "Bundling your component...";case "build_complete":return "Build complete!";case "build_error":return `Build failed: ${t.error}`;case "complete":return "Your fork is ready!";case "error":return `Error: ${t.error}`;default:return JSON.stringify(t)}}function xn({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
18
+ `}),jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:D,title:y,"aria-label":y,children:[$&&r?jsxs(Fragment,{children:[C?jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(17, 24, 39, 0.18)",borderTopColor:"#111827",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):jsx("span",{"aria-hidden":true,style:U}),jsxs("span",{style:V,children:[jsx("span",{style:W,children:K}),O&&jsx("span",{style:z,children:O})]},L)]}):jsx(Xt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),B&&jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#111827",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return p?createPortal(A,p):A}var cs={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},ds={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},fs={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},ps={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Ir(e){let t=e.data;switch(e.type){case "status":return `${t.message||t.status||"..."}`;case "agent_message":{let r=String(t.content||"");return /failed:/i.test(r)&&(r.includes("ENOENT")||r.includes("{")||r.includes("/Users/"))?"Adapting approach...":r}case "tool_use":return String(t.label||"Working on it");case "build_start":return "Bundling your component...";case "build_complete":return "Build complete!";case "build_error":return `Build failed: ${t.error}`;case "complete":return "Your fork is ready!";case "error":return `Error: ${t.error}`;default:return JSON.stringify(t)}}function xn({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
19
19
  @keyframes __fork-spin {
20
20
  from { transform: rotate(0deg); }
21
21
  to { transform: rotate(360deg); }
@@ -33,7 +33,7 @@ import*as kr from'react';import kr__default,{createContext,useState,useRef,useEf
33
33
  .__fork-stream::-webkit-scrollbar-thumb:hover {
34
34
  background: rgba(255, 255, 255, 0.3);
35
35
  }
36
- `}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,s=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",i=o&&!s&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),l=cs[r.type]||Code,f=ds[r.type]||"#9ca3af";if(r.type==="tool_use"){let w=String(r.data.category||"");l=fs[w]||Wrench,f=ps[w]||"#fbbf24";}return i?l=Loader2:!o&&r.type==="status"&&(l=Check,f="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Ar(r)})]},n)})]})]})}var Rn=35,Fs="Setting up environment",Ss="Built Custom Feature",Cn=360,St=380;function xs(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function As(e){return e.length<=Rn?e:e.slice(0,Rn-3).trimEnd()+"..."}function Is({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),s=useRef(t),i=useRef(false);return useEffect(()=>{if(!i.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){i.current=true;break}}let l="Setting up environment...";if(i.current)for(let f=e.length-1;f>=0;f--){let w=e[f];if(w.type==="tool_use"||w.type==="build_start"||w.type==="build_complete"){l=As(Ar(w));break}}if(l!==s.current){o(false);let f=setTimeout(()=>{r(l),s.current=l,o(true);},200);return ()=>clearTimeout(f)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Rs({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function Yt({state:e,fork:t,events:r,error:n,runs:o={},slotId:s,targetId:i,targetLabel:l,historyMode:f="slot",onSubmit:w,onUndo:h,onClose:p,baseUrl:F,apiKey:I,userId:y,userHash:u,appId:O,embedded:P=false,completeVariant:R="bubble"}){let[g,C]=useState(""),[_,D]=useState([]),[U,T]=useState(false),[se,W]=useState(false),[A,S]=useState(false),[N,B]=useState(false),[K,X$1]=useState(false),[G,q]=useState(false),[L,k]=useState(false),[E,x]=useState(false),[d,M]=useState(false),[v,j]=useState(null),[ne,Ee]=useState(false),[Le,Ge]=useState([]),[J,re]=useState(null),[He,Fe]=useState(false),[Me,Ye]=useState(false),[rr,Mt]=useState(false),[nr,Pt]=useState(null),[ae,it]=useState(null),[or,_t]=useState(false),[ft,Qe]=useState(false),[Oe,Ze]=useState(""),Ie=useRef(null),[be,Ne]=useState(null),[Ue,pt]=useState(false),[Pe,Lt]=useState(null),[Ve,at]=useState([]),[c,m]=useState(null),[b,V]=useState(false),Y=useRef(false),Q=useRef(null),Z=useRef(null),{resetAllForks:de,adminContext:ie,setAdminContainer:pe,currentContainerId:ge,forksPaused:oe,setForksPaused:fe,forkActivities:Re,markForkActivitySeen:me}=we(),ve=ie.containerId??ge,Te=!!(ie.isAdmin&&Ue),_e=!!(ie.containerId??ge),[lt,Ht]=useState(false),Ce=Pe!==null,Kr=useRef(p);useEffect(()=>{Kr.current=p;});let sr=useRef(null),Ot=useRef(false),zr=typeof window<"u"&&"documentPictureInPicture"in window,so=async()=>{if(!(!zr||Ce))try{let a=await window.documentPictureInPicture.requestWindow({width:Cn,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let H=document.adoptedStyleSheets??[];H.length>0&&(a.document.adoptedStyleSheets=[...H]);}catch{}a.addEventListener("pagehide",()=>{sr.current=null,Lt(null),Ot.current||Kr.current(),Ot.current=!1;},{once:!0}),sr.current=a,Lt(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},io=()=>{Pe&&(Ot.current=true,Pe.close());};useEffect(()=>()=>{Ot.current=true,sr.current?.close();},[]);let ut=i??s??"";(l||ut).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase());let Nt=useRef(""),gt=()=>{let a={Authorization:`Bearer ${I}`,...ce()};return O&&(a["X-Fork-App-Id"]=O),y&&(a["X-Fork-User-Id"]=y),u&&(a["X-Fork-User-Hash"]=u),a},ct=P?true:se&&!A,mt=c?o[c]??null:null,Wr=c?Ve.find(a=>a.id===c)??null:null,ao=Wr?(a=>a==="pending"||a==="running"||a==="building")(Wr.status):false,Be=c?mt?.state??(ao?"running":null):b?e:null,Ut=c?mt?.events??[]:b?r:[],lo=c?mt?.state==="error"?mt.error:null:b&&e==="error"?n:null,ir=c?mt?.fork??null:b?t:null,uo=Object.values(o).filter(a=>a.state!=="running").length,Vr=c?!!Re.find(a=>a.id===c)?.unread:false;useEffect(()=>{c&&Vr&&me(c);},[c,Vr,me]);let co=Ut.find(a=>{let H=a.data;return a.type==="status"&&H.summary})?.data?.summary||ir?.summary||Fs,et=Ut.find(a=>{let H=a.data;return (a.type==="status"||a.type==="complete")&&typeof H?.estimateMinutes=="number"})?.data?.estimateMinutes??ir?.estimateMinutes;useEffect(()=>{if(f==="none"){T(true);return}if(!F||!I)return;if(!c){D([]),T(true);return}let a=new AbortController;return fetch(`${F}/api/v1/forks/${encodeURIComponent(c)}/messages`,{headers:gt(),signal:a.signal}).then(H=>H.ok?H.json():[]).then(H=>{if(a.signal.aborted)return;let z=[];for(let le of H){let he=le.forkId??c;le.role==="user"?z.push({type:"user",text:le.content,forkId:he}):z.push({type:"applied",text:le.content,forkId:he});}D(z),T(true);}).catch(()=>{a.signal.aborted||T(true);}),()=>{a.abort();}},[I,O,F,f,c,ie.containerId,u,y,t?.id,t?.completedAt]),useEffect(()=>{if(f==="none"||!F||!I||!He)return;if(!J){at([]);return}let a=new AbortController,H=new URLSearchParams({container_id:J});return fetch(`${F}/api/v1/forks?${H.toString()}`,{headers:gt(),signal:a.signal}).then(z=>z.ok?z.json():{forks:[]}).then(z=>{a.signal.aborted||at(z.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[I,O,F,f,J,He,t?.id,t?.completedAt,uo,ie.containerId,u,y]),useEffect(()=>{e==="complete"&&x(false);},[e]);let Jr=Ve.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!Jr||!F||!I||!J)return;let a=new URLSearchParams({container_id:J}),H=gt(),le=setInterval(async()=>{try{let he=await fetch(`${F}/api/v1/forks?${a.toString()}`,{headers:H});if(!he.ok)return;let ye=await he.json();at(ye.forks??[]);}catch{}},3e3);return ()=>clearInterval(le)},[Jr,F,I,O,J]),useEffect(()=>{if(P&&f==="none"){Ge([]),re(null),Fe(true),pt(false);return}if(ie.isAdmin){Ne(null),Ge(ie.containers.map(a=>({id:a.id,name:a.name,createdAt:"",hasAccess:true,isPrimary:a.isPrimary}))),re(ie.containerId??null),pt(true),Fe(true);return}ve?(Ge([{id:ve,name:"Primary container",createdAt:""}]),re(ve)):(Ge([]),re(null)),Fe(true),pt(false);},[I,ve,F,P,f,ie.isAdmin,ie.containerId,ie.containers]);let Bt=useRef(void 0);useEffect(()=>{if(He){if(Bt.current===void 0){Bt.current=J;return}Bt.current!==J&&(Bt.current=J,D([]),T(false));}},[J,He]);let Dt=useRef(null);useEffect(()=>{if(!Me)return;let a=z=>{if(!Dt.current)return;let le=typeof z.composedPath=="function"?z.composedPath():[];Dt.current.contains(z.target)||le.includes(Dt.current)||Ye(false);},H=z=>{z.key==="Escape"&&Ye(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",H,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",H,true);}},[Me]),useEffect(()=>{if(P||!ct||A||Ce)return;let a=H=>{(typeof H.composedPath=="function"?H.composedPath():[]).some(he=>he instanceof Element&&he.hasAttribute("data-fork-panel-host"))||(S(true),W(false),setTimeout(()=>p(),St));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[P,ct,A,Ce,p]),useEffect(()=>{Me||(Qe(false),Ze(""));},[Me]),useEffect(()=>{ft&&(Ie.current?.focus(),Ie.current?.select());},[ft]),useEffect(()=>{if(P)return;let a=requestAnimationFrame(()=>W(true));return ()=>cancelAnimationFrame(a)},[P]),useEffect(()=>{let a=P||Ce;if((a||ct)&&(e==="prompting"||e==="complete")){let H=setTimeout(()=>Q.current?.focus(),a?100:St+100);return ()=>clearTimeout(H)}},[ct,P,Ce,e]);let qr=useRef(new Set);useEffect(()=>{for(let a of Object.values(o)){if(a.state!=="complete"||a.events.length===0)continue;let H=`${a.forkId}:${a.fork.completedAt??""}`;if(qr.current.has(H))continue;qr.current.add(H);let le=a.events.find(he=>he.type==="complete")?.data?.summary||a.fork.summary||Ss;D(he=>{let ye=[...he].reverse().find(lr=>lr.forkId===a.forkId);return ye?.type==="applied"&&ye.text===le?he:[...he,{type:"applied",text:le,forkId:a.forkId}]});}},[o]),useEffect(()=>{Be==="complete"&&Nt.current&&(C(""),setTimeout(()=>Q.current?.focus(),200));},[Be]),useEffect(()=>{Z.current&&(Z.current.scrollTop=Z.current.scrollHeight);},[_,e]);let Xr=()=>{if(g.trim()){Nt.current=g.trim();let a={},H=b||!c;H?(a.forceNew=true,Y.current=true,b||V(true)):a.forkId=c,H||D(z=>[...z,{type:"user",text:g.trim(),forkId:c}]),w(g.trim(),ut,J,a),C("");}};useEffect(()=>{if(Y.current){if(e==="error"){Y.current=false;return}t?.id&&(m(t.id),V(false),Y.current=false);}},[t?.id,e]);let Gr=useRef(new Set);useEffect(()=>{t?.id&&(Y.current||e!=="running"&&e!=="complete"||Gr.current.has(t.id)||(Gr.current.add(t.id),m(a=>a??t.id),V(false)));},[t?.id,e]);let Yr=a=>{pe(a.container.id,a.container.name),re(a.container.id),Ge(H=>{let z=H.filter(le=>le.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...z.map(le=>({...le,isPrimary:false}))]}),m(null),V(false),Y.current=false,D([]),T(false),Nt.current="";},fo=async a=>{if(!(!Te||ae)){it(a),Ne(null);try{let H=await fetch(`${F}/api/v1/admin/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:gt()});if(!H.ok){let z=await H.json().catch(()=>({}));throw new Error(z.error||`API error: ${H.status}`)}Yr(await H.json()),Ye(!1);}catch(H){Ne(H instanceof Error?H.message:String(H));}finally{it(null);}}},Qr=async a=>{if(!Te||ae)return;let H=a.trim();if(H){it("__new__"),Ne(null);try{let z=await fetch(`${F}/api/v1/admin/containers`,{method:"POST",headers:{...gt(),"Content-Type":"application/json"},body:JSON.stringify({name:H})});if(!z.ok){let le=await z.json().catch(()=>({}));throw new Error(le.error||`API error: ${z.status}`)}Yr(await z.json()),Qe(!1),Ze(""),Ye(!1);}catch(z){Ne(z instanceof Error?z.message:String(z));}finally{it(null);}}},Zr=async()=>{if(!(!h||d||!ut)){M(true);try{let a=await h(ut);D(H=>{let z=[...H];return z.length>=2&&z[z.length-1]?.type==="applied"?z.splice(-2,2):z.length>=1&&z[z.length-1]?.type==="applied"&&z.splice(-1,1),z}),a?.removed&&D([]);}catch{}finally{M(false);}}},en=()=>{if(P){p();return}if(Ce){Pe?.close();return}S(true),W(false),setTimeout(()=>p(),St);},po=P||Ce?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:Cn,maxWidth:"100vw",background:"#ffffff",boxShadow:ct?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:ct?"translateX(0)":"translateX(100%)",transition:`transform ${St}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${St}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},tn=Le.find(a=>a.id===J)?.name??(He?"Fork":"Loading..."),ht=b?[]:c?_.filter(a=>a.forkId===c||a.forkId==null):_,ar=jsxs(Fragment,{children:[jsx("style",{children:`
36
+ `}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,s=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",i=o&&!s&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),l=cs[r.type]||Code,f=ds[r.type]||"#9ca3af";if(r.type==="tool_use"){let b=String(r.data.category||"");l=fs[b]||Wrench,f=ps[b]||"#fbbf24";}return i?l=Loader2:!o&&r.type==="status"&&(l=Check,f="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Ir(r)})]},n)})]})]})}var Rn=35,Fs="Setting up environment",Ss="Built Custom Feature",Cn=360,At=380;function xs(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function As(e){return e.length<=Rn?e:e.slice(0,Rn-3).trimEnd()+"..."}function Is({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),s=useRef(t),i=useRef(false);return useEffect(()=>{if(!i.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){i.current=true;break}}let l="Setting up environment...";if(i.current)for(let f=e.length-1;f>=0;f--){let b=e[f];if(b.type==="tool_use"||b.type==="build_start"||b.type==="build_complete"){l=As(Ir(b));break}}if(l!==s.current){o(false);let f=setTimeout(()=>{r(l),s.current=l,o(true);},200);return ()=>clearTimeout(f)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Rs({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function er({state:e,fork:t,events:r,error:n,runs:o={},slotId:s,targetId:i,targetLabel:l,historyMode:f="slot",onSubmit:b,onUndo:w,onClose:p,baseUrl:h,apiKey:R,userId:k,userHash:d,appId:F,embedded:T=false,completeVariant:C="bubble"}){let[g,$]=useState(""),[_,K]=useState([]),[O,N]=useState(false),[ne,G]=useState(false),[M,y]=useState(false),[L,B]=useState(false),[D,W]=useState(false),[z,V]=useState(false),[U,S]=useState(false),[I,A]=useState(false),[u,P]=useState(false),[v,J]=useState(null),[se,Ae]=useState(false),[Pe,Ne]=useState([]),[ve,Y]=useState(null),[oe,st]=useState(false),[_e,be]=useState(false),[sr,_t]=useState(false),[ir,Lt]=useState(null),[ge,it]=useState(null),[Qe,Ht]=useState(false),[pt,at]=useState(false),[Ue,Ve]=useState(""),gt=useRef(null),[Ot,Fe]=useState(null),[Se,lt]=useState(false),[Ee,Nt]=useState(null),[Oe,ut]=useState([]),[te,qe]=useState(null),[c,m]=useState(false),x=useRef(false),q=useRef(null),Z=useRef(null),{resetAllForks:Q,adminContext:X$1,setAdminContainer:fe,currentContainerId:xe,forksPaused:ie,setForksPaused:me,forkActivities:le,markForkActivitySeen:ce}=we(),Ie=X$1.containerId??xe,pe=!!(X$1.isAdmin&&Se),Me=!!(X$1.containerId??xe),[Be,He]=useState(false),Re=Ee!==null,Ut=useRef(p);useEffect(()=>{Ut.current=p;});let mt=useRef(null),Bt=useRef(false),zr=typeof window<"u"&&"documentPictureInPicture"in window,so=async()=>{if(!(!zr||Re))try{let a=await window.documentPictureInPicture.requestWindow({width:Cn,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let H=document.adoptedStyleSheets??[];H.length>0&&(a.document.adoptedStyleSheets=[...H]);}catch{}a.addEventListener("pagehide",()=>{mt.current=null,Nt(null),Bt.current||Ut.current(),Bt.current=!1;},{once:!0}),mt.current=a,Nt(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},io=()=>{Ee&&(Bt.current=true,Ee.close());};useEffect(()=>()=>{Bt.current=true,mt.current?.close();},[]);let ct=i??s??"";(l||ct).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase());let Dt=useRef(""),ht=()=>{let a={Authorization:`Bearer ${R}`,...de()};return F&&(a["X-Fork-App-Id"]=F),k&&(a["X-Fork-User-Id"]=k),d&&(a["X-Fork-User-Hash"]=d),a},dt=T?true:ne&&!M,yt=te?o[te]??null:null,Jr=te?Oe.find(a=>a.id===te)??null:null,ao=Jr?(a=>a==="pending"||a==="running"||a==="building")(Jr.status):false,De=te?yt?.state??(ao?"running":null):c?e:null,jt=te?yt?.events??[]:c?r:[],lo=te?yt?.state==="error"?yt.error:null:c&&e==="error"?n:null,ar=te?yt?.fork??null:c?t:null,uo=Object.values(o).filter(a=>a.state!=="running").length,Wr=te?!!le.find(a=>a.id===te)?.unread:false;useEffect(()=>{te&&Wr&&ce(te);},[te,Wr,ce]);let co=jt.find(a=>{let H=a.data;return a.type==="status"&&H.summary})?.data?.summary||ar?.summary||Fs,Ze=jt.find(a=>{let H=a.data;return (a.type==="status"||a.type==="complete")&&typeof H?.estimateMinutes=="number"})?.data?.estimateMinutes??ar?.estimateMinutes;useEffect(()=>{if(f==="none"){N(true);return}if(!h||!R)return;if(!te){K([]),N(true);return}let a=new AbortController;return fetch(`${h}/api/v1/forks/${encodeURIComponent(te)}/messages`,{headers:ht(),signal:a.signal}).then(H=>H.ok?H.json():[]).then(H=>{if(a.signal.aborted)return;let j=[];for(let ae of H){let he=ae.forkId??te;ae.role==="user"?j.push({type:"user",text:ae.content,forkId:he}):j.push({type:"applied",text:ae.content,forkId:he});}K(j),N(true);}).catch(()=>{a.signal.aborted||N(true);}),()=>{a.abort();}},[R,F,h,f,te,X$1.containerId,d,k,t?.id,t?.completedAt]),useEffect(()=>{if(f==="none"||!h||!R||!oe)return;if(!ve){ut([]);return}let a=new AbortController,H=new URLSearchParams({container_id:ve});return fetch(`${h}/api/v1/forks?${H.toString()}`,{headers:ht(),signal:a.signal}).then(j=>j.ok?j.json():{forks:[]}).then(j=>{a.signal.aborted||ut(j.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[R,F,h,f,ve,oe,t?.id,t?.completedAt,uo,X$1.containerId,d,k]),useEffect(()=>{e==="complete"&&A(false);},[e]);let Vr=Oe.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!Vr||!h||!R||!ve)return;let a=new URLSearchParams({container_id:ve}),H=ht(),ae=setInterval(async()=>{try{let he=await fetch(`${h}/api/v1/forks?${a.toString()}`,{headers:H});if(!he.ok)return;let ye=await he.json();ut(ye.forks??[]);}catch{}},3e3);return ()=>clearInterval(ae)},[Vr,h,R,F,ve]),useEffect(()=>{if(T&&f==="none"){Ne([]),Y(null),st(true),lt(false);return}if(X$1.isAdmin){Fe(null),Ne(X$1.containers.map(a=>({id:a.id,name:a.name,createdAt:"",hasAccess:true,isPrimary:a.isPrimary}))),Y(X$1.containerId??null),lt(true),st(true);return}Ie?(Ne([{id:Ie,name:"Primary container",createdAt:""}]),Y(Ie)):(Ne([]),Y(null)),st(true),lt(false);},[R,Ie,h,T,f,X$1.isAdmin,X$1.containerId,X$1.containers]);let Kt=useRef(void 0);useEffect(()=>{if(oe){if(Kt.current===void 0){Kt.current=ve;return}Kt.current!==ve&&(Kt.current=ve,K([]),N(false));}},[ve,oe]);let zt=useRef(null);useEffect(()=>{if(!_e)return;let a=j=>{if(!zt.current)return;let ae=typeof j.composedPath=="function"?j.composedPath():[];zt.current.contains(j.target)||ae.includes(zt.current)||be(false);},H=j=>{j.key==="Escape"&&be(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",H,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",H,true);}},[_e]),useEffect(()=>{if(T||!dt||M||Re)return;let a=H=>{(typeof H.composedPath=="function"?H.composedPath():[]).some(he=>he instanceof Element&&he.hasAttribute("data-fork-panel-host"))||(y(true),G(false),setTimeout(()=>p(),At));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[T,dt,M,Re,p]),useEffect(()=>{_e||(at(false),Ve(""));},[_e]),useEffect(()=>{pt&&(gt.current?.focus(),gt.current?.select());},[pt]),useEffect(()=>{if(T)return;let a=requestAnimationFrame(()=>G(true));return ()=>cancelAnimationFrame(a)},[T]),useEffect(()=>{let a=T||Re;if((a||dt)&&(e==="prompting"||e==="complete")){let H=setTimeout(()=>q.current?.focus(),a?100:At+100);return ()=>clearTimeout(H)}},[dt,T,Re,e]);let qr=useRef(new Set);useEffect(()=>{for(let a of Object.values(o)){if(a.state!=="complete"||a.events.length===0)continue;let H=`${a.forkId}:${a.fork.completedAt??""}`;if(qr.current.has(H))continue;qr.current.add(H);let ae=a.events.find(he=>he.type==="complete")?.data?.summary||a.fork.summary||Ss;K(he=>{let ye=[...he].reverse().find(ur=>ur.forkId===a.forkId);return ye?.type==="applied"&&ye.text===ae?he:[...he,{type:"applied",text:ae,forkId:a.forkId}]});}},[o]),useEffect(()=>{De==="complete"&&Dt.current&&($(""),setTimeout(()=>q.current?.focus(),200));},[De]),useEffect(()=>{Z.current&&(Z.current.scrollTop=Z.current.scrollHeight);},[_,e]);let Xr=()=>{if(g.trim()){Dt.current=g.trim();let a={},H=c||!te;H?(a.forceNew=true,x.current=true,c||m(true)):a.forkId=te,H||K(j=>[...j,{type:"user",text:g.trim(),forkId:te}]),b(g.trim(),ct,ve,a),$("");}};useEffect(()=>{if(x.current){if(e==="error"){x.current=false;return}t?.id&&(qe(t.id),m(false),x.current=false);}},[t?.id,e]);let Gr=useRef(new Set);useEffect(()=>{t?.id&&(x.current||e!=="running"&&e!=="complete"||Gr.current.has(t.id)||(Gr.current.add(t.id),qe(a=>a??t.id),m(false)));},[t?.id,e]);let Yr=a=>{fe(a.container.id,a.container.name),Y(a.container.id),Ne(H=>{let j=H.filter(ae=>ae.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...j.map(ae=>({...ae,isPrimary:false}))]}),qe(null),m(false),x.current=false,K([]),N(false),Dt.current="";},fo=async a=>{if(!(!pe||ge)){it(a),Fe(null);try{let H=await fetch(`${h}/api/v1/admin/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:ht()});if(!H.ok){let j=await H.json().catch(()=>({}));throw new Error(j.error||`API error: ${H.status}`)}Yr(await H.json()),be(!1);}catch(H){Fe(H instanceof Error?H.message:String(H));}finally{it(null);}}},Qr=async a=>{if(!pe||ge)return;let H=a.trim();if(H){it("__new__"),Fe(null);try{let j=await fetch(`${h}/api/v1/admin/containers`,{method:"POST",headers:{...ht(),"Content-Type":"application/json"},body:JSON.stringify({name:H})});if(!j.ok){let ae=await j.json().catch(()=>({}));throw new Error(ae.error||`API error: ${j.status}`)}Yr(await j.json()),at(!1),Ve(""),be(!1);}catch(j){Fe(j instanceof Error?j.message:String(j));}finally{it(null);}}},Zr=async()=>{if(!(!w||u||!ct)){P(true);try{let a=await w(ct);K(H=>{let j=[...H];return j.length>=2&&j[j.length-1]?.type==="applied"?j.splice(-2,2):j.length>=1&&j[j.length-1]?.type==="applied"&&j.splice(-1,1),j}),a?.removed&&K([]);}catch{}finally{P(false);}}},en=()=>{if(T){p();return}if(Re){Ee?.close();return}y(true),G(false),setTimeout(()=>p(),At);},po=T||Re?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:Cn,maxWidth:"100vw",background:"#ffffff",boxShadow:dt?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:dt?"translateX(0)":"translateX(100%)",transition:`transform ${At}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${At}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},tn=Pe.find(a=>a.id===ve)?.name??(oe?"Fork":"Loading..."),kt=c?[]:te?_.filter(a=>a.forkId===te||a.forkId==null):_,lr=jsxs(Fragment,{children:[jsx("style",{children:`
37
37
  @keyframes __fork-pulse {
38
38
  0%, 100% { opacity: 1; }
39
39
  50% { opacity: 0.5; }
@@ -55,9 +55,9 @@ import*as kr from'react';import kr__default,{createContext,useState,useRef,useEf
55
55
  scrollbar-width: thin;
56
56
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
57
57
  }
58
- `}),jsxs("div",{className:"__fork-panel",style:po,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!ne&&confirm("Kill all forks in this container?")){Ee(true);try{let H=await de();`${H?.deleted??0}`,at([]),m(null),V(!1),C("");}catch(H){console.error("[Fork] Reset failed:",H);}finally{Ee(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(Vt,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),Be==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:co}):Le.length===0&&!Te?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Te?jsxs("div",{ref:Dt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{Ye(a=>!a);},onMouseEnter:()=>Mt(true),onMouseLeave:()=>Mt(false),"aria-haspopup":"menu","aria-expanded":Me,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:rr||Me?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Me?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Me&&jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Le.map(a=>{let H=a.id===J,z=nr===a.id,le=ae===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pt(a.id),onMouseLeave:()=>Pt(null),onClick:()=>{a.id!==J&&fo(a.id);},disabled:!!ae,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:z?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ae?"default":"pointer",textAlign:"left",fontWeight:H?600:400,opacity:ae&&!le?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:H&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:le?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),ft?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:Ie,type:"text",value:Oe,placeholder:"Container name",disabled:ae==="__new__",onChange:a=>Ze(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Qr(Oe)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Qe(false),Ze(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#111827",a.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{Qr(Oe);},disabled:!Oe.trim()||ae==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Oe.trim()||ae==="__new__"?"#e5e7eb":"#111827",color:!Oe.trim()||ae==="__new__"?"#9ca3af":"#ffffff",cursor:!Oe.trim()||ae==="__new__"?"default":"pointer",flexShrink:0},children:ae==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>_t(true),onMouseLeave:()=>_t(false),onClick:()=>{ae||(Ne(null),Ze(""),Qe(true));},disabled:!!ae,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:or?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ae?"default":"pointer",textAlign:"left",opacity:ae&&ae!=="__new__"?.55:1},children:"+ New container"}),be&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:be})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),Be==="running"&&jsx("span",{title:et?`Estimated ~${et} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:et?"#111827":"#9ca3af",backgroundColor:et?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:et?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:et?`~${et}m`:"~ m"})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[_e&&jsx("button",{type:"button",role:"switch","aria-checked":!oe,"aria-label":oe?"Turn Fork back on":"Turn Fork off",title:oe?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{fe(!oe);},onMouseEnter:()=>Ht(true),onMouseLeave:()=>Ht(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:oe?lt?"#9ca3af":"#d1d5db":lt?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:oe?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!P&&jsxs(Fragment,{children:[zr&&jsx("button",{onClick:Ce?io:so,onMouseEnter:()=>X$1(true),onMouseLeave:()=>X$1(false),title:Ce?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:K?"#4b5563":"#9ca3af",backgroundColor:K?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ce?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:en,onMouseEnter:()=>B(true),onMouseLeave:()=>B(false),style:{padding:6,borderRadius:6,color:N?"#4b5563":"#9ca3af",backgroundColor:N?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]})]}),jsxs("div",{ref:Z,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(c||b)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{m(null),V(false),Y.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let H=(c?Ve.find(z=>z.id===c)?.targetId:null)??ut;return H?jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${H}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:H})]}):null})()]}),!c&&!b&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),Ve.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),Ve.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ve.map(a=>{let H=o[a.id],le=(H?H.events.find(ye=>{let lr=ye.data;return ye.type==="status"&&lr.summary})?.data?.summary??H.fork.summary:void 0)||a.summary||"Untitled fork",he=!!Re.find(ye=>ye.id===a.id)?.unread;return jsxs("button",{onClick:()=>{V(false),m(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:ye=>ye.currentTarget.style.background="#fafafa",onMouseLeave:ye=>ye.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[he&&jsx("span",{"aria-label":"Not viewed yet",title:"Not viewed yet",style:{width:7,height:7,borderRadius:"50%",backgroundColor:"#111827",flexShrink:0}}),jsx("span",{style:{fontSize:13,fontWeight:he?600:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:le}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:xs(a.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),(()=>{let ye=o[a.id]?.state??a.status;return ye==="running"||ye==="building"||ye==="pending"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,color:"#111827"},children:[jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),"running"]})]}):ye==="error"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#b91c1c"},children:"failed"})]}):null})()]})]},a.id)})})]}),c&&ht.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:ht.map((a,H)=>jsx("div",{style:{marginBottom:H<ht.length-1?10:0},children:a.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):R==="item"&&H===ht.length-1?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:jsx(BadgeCheck,{style:{width:16,height:16}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),h&&Be!=="running"&&jsx("button",{onClick:z=>{z.stopPropagation(),Zr();},disabled:d,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:d?"default":"pointer",opacity:d?.4:1,height:28,flexShrink:0},children:"Undo"})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:a.text}),h&&H===ht.length-1&&Be!=="running"&&jsxs("button",{onClick:z=>{z.stopPropagation(),Zr();},onMouseEnter:()=>j(H),onMouseLeave:()=>j(null),disabled:d,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===H?"rgba(0,0,0,0.06)":"transparent",color:v===H?"#6b7280":"#d1d5db",cursor:d?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:d?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),v===H&&jsx("span",{style:{position:"absolute",bottom:"calc(100% + 4px)",right:0,fontSize:10,fontWeight:500,color:"#fff",background:"#374151",borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",pointerEvents:"none",lineHeight:"16px"},children:"Undo"})]})]})]})},H))}),Be==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>x(!E),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(Is,{events:Ut},c??"__compose__")]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:E?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:E?320:0,opacity:E?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(xn,{events:Ut},c??"__compose__")})})]})}),Be==="error"&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:lo??n}),jsxs("button",{onClick:()=>{let a=ir?.prompt||Nt.current;a&&w(a,ut);},onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:L?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),!(c?Be==="running":b&&e==="running")&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:Q,value:g,onChange:a=>{C(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),Xr()),a.key==="Escape"&&!P&&en();},placeholder:c?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:Xr,disabled:!g.trim(),onMouseEnter:()=>q(true),onMouseLeave:()=>q(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:g.trim()?1:.25,transform:G&&g.trim()?"scale(1.1)":"scale(1)",background:g.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:g.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return P?ar:Ce&&Pe?createPortal(ar,Pe.document.body):jsx(Rs,{children:ar})}function $n(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function Rr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,adminContext:i,refreshModuleManifest:l,queueBoundaryAnimation:f,trackForkActivity:w,recordForkActivityEvent:h}=we(),[p,F]=useState({}),[I,y]=useState(null),[u,O]=useState("idle"),[P,R]=useState(false),[g,C]=useState(null),_=useRef(new Map),D=useCallback((k,E)=>{F(x=>{let M=x[k]??{forkId:k,state:"running",fork:E.fork,events:[],error:null};return {...x,[k]:{...M,...E}}});},[]),U=useCallback((k,E)=>{F(x=>{let d=x[k];return d?{...x,[k]:{...d,events:[...d.events,E]}}:x});},[]),T=useCallback(k=>{let E=_.current.get(k);E&&(E.close(),_.current.delete(k));},[]),se=useCallback(()=>{O("prompting"),C(null),R(false),y(null);},[]),W=useCallback(()=>{O("idle"),R(false),C(null),y(null);for(let k of _.current.values())k.close();_.current.clear(),F({});},[]),A=useCallback((k,E)=>{T(k.id);let x=new URLSearchParams({key:t});r&&x.set("userId",r),n&&x.set("userHash",n),i.isAdmin&&i.containerId&&x.set("containerId",i.containerId);let d=new EventSource(`${o}/api/v1/forks/${k.id}/events?${x.toString()}`);_.current.set(k.id,d),d.onmessage=M=>{try{let v=JSON.parse(M.data);if(h(k.id,v),U(k.id,v),v.type==="complete"){let j=v.data;f(E,k.id),l().catch(()=>{}).finally(()=>{let ne={...k,status:"complete",moduleUrl:j.moduleUrl,cssUrls:j.cssUrls,summary:j.summary,completedAt:new Date().toISOString()};D(k.id,{state:"complete",fork:ne}),T(k.id);});}else if(v.type==="error"){let j=v.data;D(k.id,{state:"error",error:j.error||"Unknown error"}),T(k.id);}}catch{}},d.onerror=()=>{let M={Authorization:`Bearer ${t}`,...ce()};r&&(M["X-Fork-User-Id"]=r),n&&(M["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${k.id}`,{headers:M}).then(v=>v.json()).then(v=>{v.status==="complete"?(f(E,v.id),l().catch(()=>{}),D(k.id,{state:"complete",fork:v})):v.status==="error"?D(k.id,{state:"error",fork:v,error:v.error||"Fork generation failed"}):D(k.id,{fork:v});}).catch(()=>{D(k.id,{state:"error",error:"Connection lost"});}),T(k.id);};},[i.containerId,i.isAdmin,t,U,o,T,f,h,l,D,n,r]),S=useCallback(async(k,E,x)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");R(!0),C(null),y(null);let d;if(x?.forkId){let M={prompt:k};r&&(M.userId=r),n&&(M.userHash=n);let v=await fetch(`${o}/api/v1/forks/${encodeURIComponent(x.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ce()},body:JSON.stringify(M)});if(!v.ok){let j=await v.json().catch(()=>({}));throw new Error(j.error||`API error: ${v.status}`)}d=await v.json();}else {let M={userId:r,prompt:k,boundaryId:e,appId:s};E?M.containerId=E:i.isAdmin&&i.containerId&&(M.containerId=i.containerId),n&&(M.userHash=n),x?.forceNew&&(M.force_new=!0);let v=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ce()},body:JSON.stringify(M)});if(!v.ok){let j=await v.json().catch(()=>({}));throw new Error(j.error||`API error: ${v.status}`)}d=await v.json();}F(M=>({...M,[d.id]:{forkId:d.id,state:"running",fork:d,events:[],error:null}})),y(d.id),R(!1),w(d,{targetKind:"module",targetId:e}),A(d,d.boundaryId??e);}catch(d){C(d.message),R(false);}},[i.containerId,i.isAdmin,t,s,o,e,A,w,n,r]),N=useCallback(async k=>{try{let E={Authorization:`Bearer ${t}`,...ce()};r&&(E["X-Fork-User-Id"]=r),n&&(E["X-Fork-User-Hash"]=n);let x=await fetch(`${o}/api/v1/forks/${k}`,{headers:E});if(!x.ok)return;let d=await x.json(),M=d.boundaryId??e;if(w(d,{targetKind:"module",targetId:M}),d.status==="complete"){F(v=>({...v,[d.id]:{forkId:d.id,state:"complete",fork:d,events:[],error:null}})),y(d.id);return}if(d.status==="error"){F(v=>({...v,[d.id]:{forkId:d.id,state:"error",fork:d,events:[],error:d.error||"Fork generation failed"}})),y(d.id);return}if(d.status!=="pending"&&d.status!=="running"&&d.status!=="building")return;F(v=>({...v,[d.id]:{forkId:d.id,state:"running",fork:d,events:[],error:null}})),y(d.id),A(d,M);}catch{}},[t,o,e,A,w,n,r]),B=useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let k={userId:r,boundaryId:e,appId:s};n&&(k.userHash=n);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(k)});if(!E.ok){let d=await E.json().catch(()=>({}));throw new Error(d.error||`API error: ${E.status}`)}let x=await E.json();if(await l().catch(()=>{}),x.removed)F(d=>{let M={};for(let[v,j]of Object.entries(d))(j.fork.boundaryId??e)!==e&&(M[v]=j);return M}),y(null),O("prompting");else if(x.fork){let d=x.fork;D(d.id,{state:"complete",fork:d}),y(d.id);}return x}catch(k){throw C(k.message),k}},[t,s,o,e,l,D,n,r]),K=I?p[I]??null:null,X=P?"running":g?"error":K?K.state:u,G=K?.fork??null,q=K?.events??[],L=g??K?.error??null;return {state:X,fork:G,events:q,error:L,runs:p,open:se,close:W,startFork:S,undoFork:B,adoptRunningFork:N}}var $s=0;function Pn(e){let{state:t,fork:r,events:n,error:o,runs:s,open:i,close:l,startFork:f,undoFork:w,adoptRunningFork:h}=Rr(e),[p,F]=useState(false),I=useRef(null),y=useRef(t),u=useCallback(()=>{I.current!==null&&(clearTimeout(I.current),I.current=null);},[]),O=useCallback(()=>{u(),F(true),i();},[u,i]),P=useCallback(()=>{u(),F(false),l();},[u,l]),R=useCallback(async C=>{u(),F(true),await h(C);},[h,u]),g=Object.values(s).filter(C=>C.state==="running").length;return useEffect(()=>{let C=y.current;y.current=t,t==="complete"&&C==="running"&&p&&g===0&&(u(),I.current=setTimeout(()=>{I.current=null,F(false),l();},$s)),(t==="running"||t==="prompting")&&u();},[t,p,g,u,l]),useEffect(()=>u,[u]),{state:t,fork:r,events:n,error:o,runs:s,isOpen:p,open:O,close:P,submit:f,undo:w,adoptRunningFork:R}}function Cr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,adminContext:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:l,trackForkActivity:f,recordForkActivityEvent:w}=we(),[h,p]=useState({}),[F,I]=useState(null),[y,u]=useState("idle"),[O,P]=useState(false),[R,g]=useState(null),C=useRef(new Map),_=useCallback((L,k)=>{p(E=>{let d=E[L]??{forkId:L,state:"running",fork:k.fork,events:[],error:null};return {...E,[L]:{...d,...k}}});},[]),D=useCallback((L,k)=>{p(E=>{let x=E[L];return x?{...E,[L]:{...x,events:[...x.events,k]}}:E});},[]),U=useCallback(L=>{let k=C.current.get(L);k&&(k.close(),C.current.delete(L));},[]),T=useCallback(()=>{u("prompting"),g(null),P(false),I(null);},[]),se=useCallback(()=>{u("idle"),P(false),g(null),I(null);for(let L of C.current.values())L.close();C.current.clear(),p({});},[]),W=useCallback((L,k)=>{U(L.id);let E=new URLSearchParams({key:e});t&&E.set("userId",t),r&&E.set("userHash",r),o.isAdmin&&o.containerId&&E.set("containerId",o.containerId);let x=new EventSource(`${n}/api/v1/forks/${L.id}/events?${E.toString()}`);C.current.set(L.id,x),x.onmessage=d=>{try{let M=JSON.parse(d.data);if(w(L.id,M),D(L.id,M),M.type==="complete"){let v=M.data,j={...L,status:"complete",bundleUrl:v.bundleUrl,summary:v.summary,revealPending:!0,completedAt:new Date().toISOString()};_(L.id,{state:"complete",fork:j});let ne=k??L.slotId;ne&&v.bundleUrl&&s(ne,j),U(L.id);}else if(M.type==="error"){let v=M.data;_(L.id,{state:"error",error:v.error||"Unknown error"}),U(L.id);}}catch{}},x.onerror=()=>{let d={Authorization:`Bearer ${e}`,...ce()};t&&(d["X-Fork-User-Id"]=t),r&&(d["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${L.id}`,{headers:d}).then(M=>M.json()).then(M=>{if(M.status==="complete"){_(L.id,{state:"complete",fork:{...M,revealPending:true}});let v=k??M.slotId;v&&M.bundleUrl&&s(v,{...M,revealPending:true});}else M.status==="error"?_(L.id,{state:"error",fork:M,error:M.error||"Fork generation failed"}):_(L.id,{fork:M});}).catch(()=>{_(L.id,{state:"error",error:"Connection lost"});}),U(L.id);};},[o.containerId,o.isAdmin,e,D,n,U,w,s,_,r,t]),A=useCallback(async(L,k,E,x)=>{try{P(!0),g(null),I(null);let d;if(x?.forkId){let v={prompt:L};t&&(v.userId=t),r&&(v.userHash=r);let j=await fetch(`${n}/api/v1/forks/${encodeURIComponent(x.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ce()},body:JSON.stringify(v)});if(!j.ok){let ne=await j.json().catch(()=>({}));throw new Error(ne.error||`API error: ${j.status}`)}d=await j.json();}else {let v={userId:t,prompt:L};k&&(v.slotId=k),E?v.containerId=E:o.isAdmin&&o.containerId&&(v.containerId=o.containerId),r&&(v.userHash=r),x?.forceNew&&(v.force_new=!0);let j=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ce()},body:JSON.stringify(v)});if(!j.ok){let ne=await j.json().catch(()=>({}));throw new Error(ne.error||`API error: ${j.status}`)}d=await j.json();}p(v=>({...v,[d.id]:{forkId:d.id,state:"running",fork:d,events:[],error:null}})),I(d.id),P(!1);let M=k??d.slotId;M&&f(d,{targetKind:"slot",targetId:M}),W(d,k);}catch(d){g(d.message),P(false);}},[o.containerId,o.isAdmin,e,n,W,f,r,t]),S=useCallback(async L=>{try{let k={Authorization:`Bearer ${e}`,...ce()};t&&(k["X-Fork-User-Id"]=t),r&&(k["X-Fork-User-Hash"]=r);let E=await fetch(`${n}/api/v1/forks/${L}`,{headers:k});if(!E.ok)return;let x=await E.json();if(x.slotId&&f(x,{targetKind:"slot",targetId:x.slotId}),x.status==="complete"){p(d=>({...d,[x.id]:{forkId:x.id,state:"complete",fork:x,events:[],error:null}})),I(x.id);return}if(x.status==="error"){p(d=>({...d,[x.id]:{forkId:x.id,state:"error",fork:x,events:[],error:x.error||"Fork generation failed"}})),I(x.id);return}if(x.status!=="pending"&&x.status!=="running"&&x.status!=="building")return;p(d=>({...d,[x.id]:{forkId:x.id,state:"running",fork:x,events:[],error:null}})),I(x.id),W(x,x.slotId);}catch{}},[e,n,W,f,r,t]),N=useCallback(async L=>{try{let k={userId:t,slotId:L};r&&(k.userHash=r);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(k)});if(!E.ok){let d=await E.json().catch(()=>({}));throw new Error(d.error||`API error: ${E.status}`)}let x=await E.json();if(l(L),x.removed)i(L),p(d=>{let M={};for(let[v,j]of Object.entries(d))j.fork.slotId!==L&&(M[v]=j);return M}),I(null),u("prompting");else if(x.fork){s(L,x.fork);let d=x.fork;_(d.id,{state:"complete",fork:d});}return x}catch(k){throw g(k.message),k}},[e,t,r,n,i,s,l,_]),B=F?h[F]??null:null,K=O?"running":R?"error":B?B.state:y,X=B?.fork??null,G=B?.events??[],q=R??B?.error??null;return {state:K,fork:X,events:G,error:q,runs:h,open:T,close:se,startFork:A,undoFork:N,adoptRunningFork:S}}var Ps=0;function Hn(){let{state:e,fork:t,events:r,error:n,runs:o,open:s,close:i,startFork:l,undoFork:f,adoptRunningFork:w}=Cr(),[h,p]=useState(false),F=useRef(null),I=useRef(e),y=useCallback(()=>{F.current!==null&&(clearTimeout(F.current),F.current=null);},[]),u=useCallback(()=>{y(),p(true),s();},[y,s]),O=useCallback(()=>{y(),p(false),i();},[y,i]),P=useCallback(async g=>{y(),p(true),await w(g);},[w,y]),R=Object.values(o).filter(g=>g.state==="running").length;return useEffect(()=>{let g=I.current;I.current=e,e==="complete"&&g==="running"&&h&&R===0&&(y(),F.current=setTimeout(()=>{F.current=null,p(false),i();},Ps)),(e==="running"||e==="prompting")&&y();},[e,h,R,y,i]),useEffect(()=>y,[y]),{state:e,fork:t,events:r,error:n,runs:o,isOpen:h,open:u,close:O,submit:l,undo:f,adoptRunningFork:P}}var _s=new Set(["pending","running","building"]);function $r(e){let t=$n(e),r=Hn(),n=Pn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:l,appId:f,activitySummary:w,forkActivities:h}=we(),p=t.type==="slot"?r:n,F=t.type==="slot"?"slot":"boundary",I=t.id,y=t.title,u=t.type==="slot"?"slot":"module",O=h.find(_=>_.targetKind===u&&_.targetId===t.id&&_s.has(_.status)),P=h.find(_=>_.targetKind===u&&_.targetId===t.id&&_.status==="complete"&&_.unread),R=useCallback(()=>{let _=O??P;if(_){p.adoptRunningFork(_.id);return}p.open();},[p,O,P]),g=useCallback((_,D,U,T)=>t.type==="slot"?r.submit(_,D??t.id,U,T):n.submit(_,U,T),[n,r,t]),C=useCallback(_=>t.type==="slot"?r.undo(_??t.id):n.undo(),[n,r,t]);return {...p,open:R,target:t,targetId:I,targetLabel:y,historyMode:F,submit:g,undo:C,buttonProps:{onClick:R,hasNotification:w.unreadCompletedCount>0,activity:w},panelProps:{state:p.state,fork:p.fork,events:p.events,error:p.error,runs:p.runs,...t.type==="slot"?{slotId:I,targetLabel:y,historyMode:F}:{targetId:I,targetLabel:y,historyMode:F},onSubmit:g,onUndo:C,onClose:p.close,baseUrl:o,apiKey:s,userId:i,userHash:l,appId:f}}}function It(e){let{embedded:t,completeVariant:r}=e,n=$r(e);return t?jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?jsx(Yt,{...n.panelProps,completeVariant:r}):jsx(Sr,{...n.buttonProps})}function Ls({boundaryId:e,title:t}){return jsx(It,{boundaryId:e,title:t})}function Mr(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function On(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Pr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Nn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Un(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Bn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function _r(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let h=0;h<e.length;h+=1){let{rect:p,borderRadius:F}=e[h],I=p.left-.5,y=p.top-.5,u=p.width+1,O=p.height+1,P=Math.min(F+.5,u/2,O/2),R=Bn(I,y,u,O,P),g=`__fork-glow-${h}`,C=document.createElementNS(t,"filter");C.setAttribute("id",g),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let _=document.createElementNS(t,"feGaussianBlur");_.setAttribute("in","SourceGraphic"),_.setAttribute("stdDeviation","8"),C.appendChild(_),o.appendChild(C);let D=`__fork-mask-${h}`,U=document.createElementNS(t,"mask");U.setAttribute("id",D),U.setAttribute("maskUnits","userSpaceOnUse"),U.setAttribute("x",String(I-200)),U.setAttribute("y",String(y-200)),U.setAttribute("width",String(u+400)),U.setAttribute("height",String(O+400));let T=document.createElementNS(t,"rect");T.setAttribute("x",String(I-200)),T.setAttribute("y",String(y-200)),T.setAttribute("width",String(u+400)),T.setAttribute("height",String(O+400)),T.setAttribute("fill","white"),U.appendChild(T);let se=document.createElementNS(t,"path");se.setAttribute("d",R),se.setAttribute("fill","black"),U.appendChild(se),o.appendChild(U);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${D})`),W.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${g})`);let S=document.createElementNS(t,"path");S.setAttribute("d",R),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),A.appendChild(S),W.appendChild(A),n.appendChild(W);let N=document.createElementNS(t,"path");N.setAttribute("d",R),N.setAttribute("fill","none"),N.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),N.setAttribute("stroke-width","2"),N.setAttribute("stroke-linecap","round"),N.setAttribute("opacity","0"),n.appendChild(N),s.push(S,N),S.__group=W;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let h=0;h<s.length;h+=2){let p=s[h],F=s[h+1],I=p.__group;if(!I)continue;let y=F.getTotalLength(),u=p.getTotalLength();if(y<=0)continue;let O=y*.35;F.setAttribute("stroke-dasharray",`${O} ${y-O}`),F.setAttribute("stroke-dashoffset","0"),i.push(F.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*y,opacity:.92,offset:.06},{strokeDashoffset:-2*y,opacity:.92,offset:.92},{strokeDashoffset:-2.25*y,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let P=u*.35;p.setAttribute("stroke-dasharray",`${P} ${u-P}`),p.setAttribute("stroke-dashoffset","0"),i.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*u,offset:.06},{strokeDashoffset:-2*u,offset:.92},{strokeDashoffset:-2.25*u,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of i)try{p.cancel();}catch{}let h=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});h.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let w=document.createElementNS(t,"path");w.setAttribute("d",Bn(l.left,l.top,l.width,l.height,f)),w.setAttribute("fill","none"),w.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),w.setAttribute("stroke-width","1.5"),w.setAttribute("stroke-dasharray","8 4"),w.setAttribute("stroke-linecap","round"),w.setAttribute("filter","url(#__fork-removed-shadow)"),w.setAttribute("opacity","0"),n.appendChild(w),w.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zn(e,t){if(Os(t.selector))return Kn(e,t);let n=Kn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(jn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Hr(e,h=>h===s);if(i)return i;let l=s.toLowerCase(),f=Hr(e,h=>h.toLowerCase()===l);if(f)return f;let w=Hr(e,h=>h.toLowerCase().includes(l));if(w)return w}}let o=Ns(t.selector);if(o&&o!==t.selector&&jn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function jn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Kn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Lr(t.label),o=Lr(t.textHint);return r.find(i=>{let l=Lr(i.getAttribute("data-fork-new"));return !!l&&(l===n||l===o)})??null}function Os(e){return e.trim()==="[data-fork-new]"}function Lr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ns(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Hr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let l=s.getBoundingClientRect();if(l.width<4||l.height<4)continue;let f=l.width*l.height;f<n&&(r=s,n=f);}return r}var Or=2147483600,Us=1600,Bs=3e4,Ds=300,qe=10;function js(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let l=e.getBoundingClientRect(),f=Math.min(l.width,l.height);return Math.max(4,i/100*f)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function Ks(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,l=e;l==="top"&&t.top<n+qe+8?l="bottom":l==="bottom"&&i-t.bottom<n+qe+8?l="top":l==="left"&&t.left<r+qe+8?l="right":l==="right"&&s-t.right<r+qe+8&&(l="left");let f=0,w=0;return l==="top"?(f=t.top-n-qe,w=t.left+t.width/2-r/2):l==="bottom"?(f=t.bottom+qe,w=t.left+t.width/2-r/2):l==="left"?(f=t.top+t.height/2-n/2,w=t.left-r-qe):(f=t.top+t.height/2-n/2,w=t.right+qe),w=Math.max(8,Math.min(w,s-r-8)),f=Math.max(8,Math.min(f,i-n-8)),{top:f,left:w,placement:l}}function zs(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Or}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Or-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Or+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function Ws(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
58
+ `}),jsxs("div",{className:"__fork-panel",style:po,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!se&&confirm("Kill all forks in this container?")){Ae(true);try{let H=await Q();`${H?.deleted??0}`,ut([]),qe(null),m(!1),$("");}catch(H){console.error("[Fork] Reset failed:",H);}finally{Ae(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(Xt,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),De==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:co}):Pe.length===0&&!pe?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):pe?jsxs("div",{ref:zt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{be(a=>!a);},onMouseEnter:()=>_t(true),onMouseLeave:()=>_t(false),"aria-haspopup":"menu","aria-expanded":_e,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:sr||_e?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:_e?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),_e&&jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Pe.map(a=>{let H=a.id===ve,j=ir===a.id,ae=ge===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Lt(a.id),onMouseLeave:()=>Lt(null),onClick:()=>{a.id!==ve&&fo(a.id);},disabled:!!ge,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:j?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",fontWeight:H?600:400,opacity:ge&&!ae?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:H&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ae?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),pt?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:gt,type:"text",value:Ue,placeholder:"Container name",disabled:ge==="__new__",onChange:a=>Ve(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Qr(Ue)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),at(false),Ve(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#111827",a.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{Qr(Ue);},disabled:!Ue.trim()||ge==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Ue.trim()||ge==="__new__"?"#e5e7eb":"#111827",color:!Ue.trim()||ge==="__new__"?"#9ca3af":"#ffffff",cursor:!Ue.trim()||ge==="__new__"?"default":"pointer",flexShrink:0},children:ge==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Ht(true),onMouseLeave:()=>Ht(false),onClick:()=>{ge||(Fe(null),Ve(""),at(true));},disabled:!!ge,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Qe?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",opacity:ge&&ge!=="__new__"?.55:1},children:"+ New container"}),Ot&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:Ot})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),De==="running"&&jsx("span",{title:Ze?`Estimated ~${Ze} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Ze?"#111827":"#9ca3af",backgroundColor:Ze?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Ze?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Ze?`~${Ze}m`:"~ m"})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Me&&jsx("button",{type:"button",role:"switch","aria-checked":!ie,"aria-label":ie?"Turn Fork back on":"Turn Fork off",title:ie?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{me(!ie);},onMouseEnter:()=>He(true),onMouseLeave:()=>He(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:ie?Be?"#9ca3af":"#d1d5db":Be?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:ie?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!T&&jsxs(Fragment,{children:[zr&&jsx("button",{onClick:Re?io:so,onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),title:Re?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:D?"#4b5563":"#9ca3af",backgroundColor:D?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Re?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:en,onMouseEnter:()=>B(true),onMouseLeave:()=>B(false),style:{padding:6,borderRadius:6,color:L?"#4b5563":"#9ca3af",backgroundColor:L?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]})]}),jsxs("div",{ref:Z,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(te||c)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{qe(null),m(false),x.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let H=(te?Oe.find(j=>j.id===te)?.targetId:null)??ct;return H?jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${H}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:H})]}):null})()]}),!te&&!c&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),Oe.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),Oe.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:Oe.map(a=>{let H=o[a.id],ae=(H?H.events.find(ye=>{let ur=ye.data;return ye.type==="status"&&ur.summary})?.data?.summary??H.fork.summary:void 0)||a.summary||"Untitled fork",he=!!le.find(ye=>ye.id===a.id)?.unread;return jsxs("button",{onClick:()=>{m(false),qe(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:ye=>ye.currentTarget.style.background="#fafafa",onMouseLeave:ye=>ye.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[he&&jsx("span",{"aria-label":"Not viewed yet",title:"Not viewed yet",style:{width:7,height:7,borderRadius:"50%",backgroundColor:"#111827",flexShrink:0}}),jsx("span",{style:{fontSize:13,fontWeight:he?600:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:ae}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:xs(a.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),(()=>{let ye=o[a.id]?.state??a.status;return ye==="running"||ye==="building"||ye==="pending"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,color:"#111827"},children:[jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),"running"]})]}):ye==="error"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#b91c1c"},children:"failed"})]}):null})()]})]},a.id)})})]}),te&&kt.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:kt.map((a,H)=>jsx("div",{style:{marginBottom:H<kt.length-1?10:0},children:a.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):C==="item"&&H===kt.length-1?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:jsx(BadgeCheck,{style:{width:16,height:16}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),w&&De!=="running"&&jsx("button",{onClick:j=>{j.stopPropagation(),Zr();},disabled:u,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:u?"default":"pointer",opacity:u?.4:1,height:28,flexShrink:0},children:"Undo"})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:a.text}),w&&H===kt.length-1&&De!=="running"&&jsxs("button",{onClick:j=>{j.stopPropagation(),Zr();},onMouseEnter:()=>J(H),onMouseLeave:()=>J(null),disabled:u,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===H?"rgba(0,0,0,0.06)":"transparent",color:v===H?"#6b7280":"#d1d5db",cursor:u?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:u?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),v===H&&jsx("span",{style:{position:"absolute",bottom:"calc(100% + 4px)",right:0,fontSize:10,fontWeight:500,color:"#fff",background:"#374151",borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",pointerEvents:"none",lineHeight:"16px"},children:"Undo"})]})]})]})},H))}),De==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>A(!I),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(Is,{events:jt},te??"__compose__")]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:I?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:I?320:0,opacity:I?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(xn,{events:jt},te??"__compose__")})})]})}),De==="error"&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:lo??n}),jsxs("button",{onClick:()=>{let a=ar?.prompt||Dt.current;a&&b(a,ct);},onMouseEnter:()=>S(true),onMouseLeave:()=>S(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:U?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),!(te?De==="running":c&&e==="running")&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:q,value:g,onChange:a=>{$(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),Xr()),a.key==="Escape"&&!T&&en();},placeholder:te?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:Xr,disabled:!g.trim(),onMouseEnter:()=>V(true),onMouseLeave:()=>V(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:g.trim()?1:.25,transform:z&&g.trim()?"scale(1.1)":"scale(1)",background:g.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:g.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return T?lr:Re&&Ee?createPortal(lr,Ee.document.body):jsx(Rs,{children:lr})}function $n(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function Cr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,adminContext:i,refreshModuleManifest:l,queueBoundaryAnimation:f,trackForkActivity:b,recordForkActivityEvent:w}=we(),[p,h]=useState({}),[R,k]=useState(null),[d,F]=useState("idle"),[T,C]=useState(false),[g,$]=useState(null),_=useRef(new Map),K=useCallback((S,I)=>{h(A=>{let P=A[S]??{forkId:S,state:"running",fork:I.fork,events:[],error:null};return {...A,[S]:{...P,...I}}});},[]),O=useCallback((S,I)=>{h(A=>{let u=A[S];return u?{...A,[S]:{...u,events:[...u.events,I]}}:A});},[]),N=useCallback(S=>{let I=_.current.get(S);I&&(I.close(),_.current.delete(S));},[]),ne=useCallback(()=>{F("prompting"),$(null),C(false),k(null);},[]),G=useCallback(()=>{F("idle"),C(false),$(null),k(null);for(let S of _.current.values())S.close();_.current.clear(),h({});},[]),M=useCallback((S,I)=>{N(S.id);let A=new URLSearchParams({key:t});r&&A.set("userId",r),n&&A.set("userHash",n),i.isAdmin&&i.containerId&&A.set("containerId",i.containerId);let u=new EventSource(`${o}/api/v1/forks/${S.id}/events?${A.toString()}`);_.current.set(S.id,u),u.onmessage=P=>{try{let v=JSON.parse(P.data);if(w(S.id,v),O(S.id,v),v.type==="complete"){let J=v.data;f(I,S.id),l().catch(()=>{}).finally(()=>{let se={...S,status:"complete",moduleUrl:J.moduleUrl,cssUrls:J.cssUrls,summary:J.summary,completedAt:new Date().toISOString()};K(S.id,{state:"complete",fork:se}),N(S.id);});}else if(v.type==="error"){let J=v.data;K(S.id,{state:"error",error:J.error||"Unknown error"}),N(S.id);}}catch{}},u.onerror=()=>{let P={Authorization:`Bearer ${t}`,...de()};r&&(P["X-Fork-User-Id"]=r),n&&(P["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${S.id}`,{headers:P}).then(v=>v.json()).then(v=>{v.status==="complete"?(f(I,v.id),l().catch(()=>{}),K(S.id,{state:"complete",fork:v})):v.status==="error"?K(S.id,{state:"error",fork:v,error:v.error||"Fork generation failed"}):K(S.id,{fork:v});}).catch(()=>{K(S.id,{state:"error",error:"Connection lost"});}),N(S.id);};},[i.containerId,i.isAdmin,t,O,o,N,f,w,l,K,n,r]),y=useCallback(async(S,I,A)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");C(!0),$(null),k(null);let u;if(A?.forkId){let P={prompt:S};r&&(P.userId=r),n&&(P.userHash=n);let v=await fetch(`${o}/api/v1/forks/${encodeURIComponent(A.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...de()},body:JSON.stringify(P)});if(!v.ok){let J=await v.json().catch(()=>({}));throw new Error(J.error||`API error: ${v.status}`)}u=await v.json();}else {let P={userId:r,prompt:S,boundaryId:e,appId:s};I?P.containerId=I:i.isAdmin&&i.containerId&&(P.containerId=i.containerId),n&&(P.userHash=n),A?.forceNew&&(P.force_new=!0);let v=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...de()},body:JSON.stringify(P)});if(!v.ok){let J=await v.json().catch(()=>({}));throw new Error(J.error||`API error: ${v.status}`)}u=await v.json();}h(P=>({...P,[u.id]:{forkId:u.id,state:"running",fork:u,events:[],error:null}})),k(u.id),C(!1),b(u,{targetKind:"module",targetId:e}),M(u,u.boundaryId??e);}catch(u){$(u.message),C(false);}},[i.containerId,i.isAdmin,t,s,o,e,M,b,n,r]),L=useCallback(async S=>{try{let I={Authorization:`Bearer ${t}`,...de()};r&&(I["X-Fork-User-Id"]=r),n&&(I["X-Fork-User-Hash"]=n);let A=await fetch(`${o}/api/v1/forks/${S}`,{headers:I});if(!A.ok)return;let u=await A.json(),P=u.boundaryId??e;if(b(u,{targetKind:"module",targetId:P}),u.status==="complete"){h(v=>({...v,[u.id]:{forkId:u.id,state:"complete",fork:u,events:[],error:null}})),k(u.id);return}if(u.status==="error"){h(v=>({...v,[u.id]:{forkId:u.id,state:"error",fork:u,events:[],error:u.error||"Fork generation failed"}})),k(u.id);return}if(u.status!=="pending"&&u.status!=="running"&&u.status!=="building")return;h(v=>({...v,[u.id]:{forkId:u.id,state:"running",fork:u,events:[],error:null}})),k(u.id),M(u,P);}catch{}},[t,o,e,M,b,n,r]),B=useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let S={userId:r,boundaryId:e,appId:s};n&&(S.userHash=n);let I=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(S)});if(!I.ok){let u=await I.json().catch(()=>({}));throw new Error(u.error||`API error: ${I.status}`)}let A=await I.json();if(await l().catch(()=>{}),A.removed)h(u=>{let P={};for(let[v,J]of Object.entries(u))(J.fork.boundaryId??e)!==e&&(P[v]=J);return P}),k(null),F("prompting");else if(A.fork){let u=A.fork;K(u.id,{state:"complete",fork:u}),k(u.id);}return A}catch(S){throw $(S.message),S}},[t,s,o,e,l,K,n,r]),D=R?p[R]??null:null,W=T?"running":g?"error":D?D.state:d,z=D?.fork??null,V=D?.events??[],U=g??D?.error??null;return {state:W,fork:z,events:V,error:U,runs:p,open:ne,close:G,startFork:y,undoFork:B,adoptRunningFork:L}}var $s=0;function Pn(e){let{state:t,fork:r,events:n,error:o,runs:s,open:i,close:l,startFork:f,undoFork:b,adoptRunningFork:w}=Cr(e),[p,h]=useState(false),R=useRef(null),k=useRef(t),d=useCallback(()=>{R.current!==null&&(clearTimeout(R.current),R.current=null);},[]),F=useCallback(()=>{d(),h(true),i();},[d,i]),T=useCallback(()=>{d(),h(false),l();},[d,l]),C=useCallback(async $=>{d(),h(true),await w($);},[w,d]),g=Object.values(s).filter($=>$.state==="running").length;return useEffect(()=>{let $=k.current;k.current=t,t==="complete"&&$==="running"&&p&&g===0&&(d(),R.current=setTimeout(()=>{R.current=null,h(false),l();},$s)),(t==="running"||t==="prompting")&&d();},[t,p,g,d,l]),useEffect(()=>d,[d]),{state:t,fork:r,events:n,error:o,runs:s,isOpen:p,open:F,close:T,submit:f,undo:b,adoptRunningFork:C}}function Er(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,adminContext:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:l,trackForkActivity:f,recordForkActivityEvent:b}=we(),[w,p]=useState({}),[h,R]=useState(null),[k,d]=useState("idle"),[F,T]=useState(false),[C,g]=useState(null),$=useRef(new Map),_=useCallback((U,S)=>{p(I=>{let u=I[U]??{forkId:U,state:"running",fork:S.fork,events:[],error:null};return {...I,[U]:{...u,...S}}});},[]),K=useCallback((U,S)=>{p(I=>{let A=I[U];return A?{...I,[U]:{...A,events:[...A.events,S]}}:I});},[]),O=useCallback(U=>{let S=$.current.get(U);S&&(S.close(),$.current.delete(U));},[]),N=useCallback(()=>{d("prompting"),g(null),T(false),R(null);},[]),ne=useCallback(()=>{d("idle"),T(false),g(null),R(null);for(let U of $.current.values())U.close();$.current.clear(),p({});},[]),G=useCallback((U,S)=>{O(U.id);let I=new URLSearchParams({key:e});t&&I.set("userId",t),r&&I.set("userHash",r),o.isAdmin&&o.containerId&&I.set("containerId",o.containerId);let A=new EventSource(`${n}/api/v1/forks/${U.id}/events?${I.toString()}`);$.current.set(U.id,A),A.onmessage=u=>{try{let P=JSON.parse(u.data);if(b(U.id,P),K(U.id,P),P.type==="complete"){let v=P.data,J={...U,status:"complete",bundleUrl:v.bundleUrl,summary:v.summary,revealPending:!0,completedAt:new Date().toISOString()};_(U.id,{state:"complete",fork:J});let se=S??U.slotId;se&&v.bundleUrl&&s(se,J),O(U.id);}else if(P.type==="error"){let v=P.data;_(U.id,{state:"error",error:v.error||"Unknown error"}),O(U.id);}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...de()};t&&(u["X-Fork-User-Id"]=t),r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${U.id}`,{headers:u}).then(P=>P.json()).then(P=>{if(P.status==="complete"){_(U.id,{state:"complete",fork:{...P,revealPending:true}});let v=S??P.slotId;v&&P.bundleUrl&&s(v,{...P,revealPending:true});}else P.status==="error"?_(U.id,{state:"error",fork:P,error:P.error||"Fork generation failed"}):_(U.id,{fork:P});}).catch(()=>{_(U.id,{state:"error",error:"Connection lost"});}),O(U.id);};},[o.containerId,o.isAdmin,e,K,n,O,b,s,_,r,t]),M=useCallback(async(U,S,I,A)=>{try{T(!0),g(null),R(null);let u;if(A?.forkId){let v={prompt:U};t&&(v.userId=t),r&&(v.userHash=r);let J=await fetch(`${n}/api/v1/forks/${encodeURIComponent(A.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...de()},body:JSON.stringify(v)});if(!J.ok){let se=await J.json().catch(()=>({}));throw new Error(se.error||`API error: ${J.status}`)}u=await J.json();}else {let v={userId:t,prompt:U};S&&(v.slotId=S),I?v.containerId=I:o.isAdmin&&o.containerId&&(v.containerId=o.containerId),r&&(v.userHash=r),A?.forceNew&&(v.force_new=!0);let J=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...de()},body:JSON.stringify(v)});if(!J.ok){let se=await J.json().catch(()=>({}));throw new Error(se.error||`API error: ${J.status}`)}u=await J.json();}p(v=>({...v,[u.id]:{forkId:u.id,state:"running",fork:u,events:[],error:null}})),R(u.id),T(!1);let P=S??u.slotId;P&&f(u,{targetKind:"slot",targetId:P}),G(u,S);}catch(u){g(u.message),T(false);}},[o.containerId,o.isAdmin,e,n,G,f,r,t]),y=useCallback(async U=>{try{let S={Authorization:`Bearer ${e}`,...de()};t&&(S["X-Fork-User-Id"]=t),r&&(S["X-Fork-User-Hash"]=r);let I=await fetch(`${n}/api/v1/forks/${U}`,{headers:S});if(!I.ok)return;let A=await I.json();if(A.slotId&&f(A,{targetKind:"slot",targetId:A.slotId}),A.status==="complete"){p(u=>({...u,[A.id]:{forkId:A.id,state:"complete",fork:A,events:[],error:null}})),R(A.id);return}if(A.status==="error"){p(u=>({...u,[A.id]:{forkId:A.id,state:"error",fork:A,events:[],error:A.error||"Fork generation failed"}})),R(A.id);return}if(A.status!=="pending"&&A.status!=="running"&&A.status!=="building")return;p(u=>({...u,[A.id]:{forkId:A.id,state:"running",fork:A,events:[],error:null}})),R(A.id),G(A,A.slotId);}catch{}},[e,n,G,f,r,t]),L=useCallback(async U=>{try{let S={userId:t,slotId:U};r&&(S.userHash=r);let I=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(S)});if(!I.ok){let u=await I.json().catch(()=>({}));throw new Error(u.error||`API error: ${I.status}`)}let A=await I.json();if(l(U),A.removed)i(U),p(u=>{let P={};for(let[v,J]of Object.entries(u))J.fork.slotId!==U&&(P[v]=J);return P}),R(null),d("prompting");else if(A.fork){s(U,A.fork);let u=A.fork;_(u.id,{state:"complete",fork:u});}return A}catch(S){throw g(S.message),S}},[e,t,r,n,i,s,l,_]),B=h?w[h]??null:null,D=F?"running":C?"error":B?B.state:k,W=B?.fork??null,z=B?.events??[],V=C??B?.error??null;return {state:D,fork:W,events:z,error:V,runs:w,open:N,close:ne,startFork:M,undoFork:L,adoptRunningFork:y}}var Ps=0;function Hn(){let{state:e,fork:t,events:r,error:n,runs:o,open:s,close:i,startFork:l,undoFork:f,adoptRunningFork:b}=Er(),[w,p]=useState(false),h=useRef(null),R=useRef(e),k=useCallback(()=>{h.current!==null&&(clearTimeout(h.current),h.current=null);},[]),d=useCallback(()=>{k(),p(true),s();},[k,s]),F=useCallback(()=>{k(),p(false),i();},[k,i]),T=useCallback(async g=>{k(),p(true),await b(g);},[b,k]),C=Object.values(o).filter(g=>g.state==="running").length;return useEffect(()=>{let g=R.current;R.current=e,e==="complete"&&g==="running"&&w&&C===0&&(k(),h.current=setTimeout(()=>{h.current=null,p(false),i();},Ps)),(e==="running"||e==="prompting")&&k();},[e,w,C,k,i]),useEffect(()=>k,[k]),{state:e,fork:t,events:r,error:n,runs:o,isOpen:w,open:d,close:F,submit:l,undo:f,adoptRunningFork:T}}var _s=new Set(["pending","running","building"]);function Tr(e){let t=$n(e),r=Hn(),n=Pn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:l,appId:f,activitySummary:b,forkActivities:w}=we(),p=t.type==="slot"?r:n,h=t.type==="slot"?"slot":"boundary",R=t.id,k=t.title,d=t.type==="slot"?"slot":"module",F=w.find(_=>_.targetKind===d&&_.targetId===t.id&&_s.has(_.status)),T=w.find(_=>_.targetKind===d&&_.targetId===t.id&&_.status==="complete"&&_.unread),C=useCallback(()=>{let _=F??T;if(_){p.adoptRunningFork(_.id);return}p.open();},[p,F,T]),g=useCallback((_,K,O,N)=>t.type==="slot"?r.submit(_,K??t.id,O,N):n.submit(_,O,N),[n,r,t]),$=useCallback(_=>t.type==="slot"?r.undo(_??t.id):n.undo(),[n,r,t]);return {...p,open:C,target:t,targetId:R,targetLabel:k,historyMode:h,submit:g,undo:$,buttonProps:{onClick:C,hasNotification:b.unreadCompletedCount>0,activity:b},panelProps:{state:p.state,fork:p.fork,events:p.events,error:p.error,runs:p.runs,...t.type==="slot"?{slotId:R,targetLabel:k,historyMode:h}:{targetId:R,targetLabel:k,historyMode:h},onSubmit:g,onUndo:$,onClose:p.close,baseUrl:o,apiKey:s,userId:i,userHash:l,appId:f}}}function Ct(e){let{embedded:t,completeVariant:r}=e,n=Tr(e);return t?jsx(er,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?jsx(er,{...n.panelProps,completeVariant:r}):jsx(xr,{...n.buttonProps})}function Ls({boundaryId:e,title:t}){return jsx(Ct,{boundaryId:e,title:t})}function Pr(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function On(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function _r(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Nn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Un(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Bn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Lr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let w=0;w<e.length;w+=1){let{rect:p,borderRadius:h}=e[w],R=p.left-.5,k=p.top-.5,d=p.width+1,F=p.height+1,T=Math.min(h+.5,d/2,F/2),C=Bn(R,k,d,F,T),g=`__fork-glow-${w}`,$=document.createElementNS(t,"filter");$.setAttribute("id",g),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let _=document.createElementNS(t,"feGaussianBlur");_.setAttribute("in","SourceGraphic"),_.setAttribute("stdDeviation","8"),$.appendChild(_),o.appendChild($);let K=`__fork-mask-${w}`,O=document.createElementNS(t,"mask");O.setAttribute("id",K),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(R-200)),O.setAttribute("y",String(k-200)),O.setAttribute("width",String(d+400)),O.setAttribute("height",String(F+400));let N=document.createElementNS(t,"rect");N.setAttribute("x",String(R-200)),N.setAttribute("y",String(k-200)),N.setAttribute("width",String(d+400)),N.setAttribute("height",String(F+400)),N.setAttribute("fill","white"),O.appendChild(N);let ne=document.createElementNS(t,"path");ne.setAttribute("d",C),ne.setAttribute("fill","black"),O.appendChild(ne),o.appendChild(O);let G=document.createElementNS(t,"g");G.setAttribute("mask",`url(#${K})`),G.setAttribute("opacity","0");let M=document.createElementNS(t,"g");M.setAttribute("filter",`url(#${g})`);let y=document.createElementNS(t,"path");y.setAttribute("d",C),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),y.setAttribute("stroke-width","6"),y.setAttribute("stroke-linecap","round"),M.appendChild(y),G.appendChild(M),n.appendChild(G);let L=document.createElementNS(t,"path");L.setAttribute("d",C),L.setAttribute("fill","none"),L.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),L.setAttribute("stroke-width","2"),L.setAttribute("stroke-linecap","round"),L.setAttribute("opacity","0"),n.appendChild(L),s.push(y,L),y.__group=G;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let w=0;w<s.length;w+=2){let p=s[w],h=s[w+1],R=p.__group;if(!R)continue;let k=h.getTotalLength(),d=p.getTotalLength();if(k<=0)continue;let F=k*.35;h.setAttribute("stroke-dasharray",`${F} ${k-F}`),h.setAttribute("stroke-dashoffset","0"),i.push(h.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*k,opacity:.92,offset:.06},{strokeDashoffset:-2*k,opacity:.92,offset:.92},{strokeDashoffset:-2.25*k,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=d*.35;p.setAttribute("stroke-dasharray",`${T} ${d-T}`),p.setAttribute("stroke-dashoffset","0"),i.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*d,offset:.06},{strokeDashoffset:-2*d,offset:.92},{strokeDashoffset:-2.25*d,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,f=()=>{if(l)return;l=true,clearTimeout(b);for(let p of i)try{p.cancel();}catch{}let w=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});w.onfinish=()=>r.remove(),window.removeEventListener("click",f);},b=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let b=document.createElementNS(t,"path");b.setAttribute("d",Bn(l.left,l.top,l.width,l.height,f)),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zn(e,t){if(Os(t.selector))return Kn(e,t);let n=Kn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(jn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Or(e,w=>w===s);if(i)return i;let l=s.toLowerCase(),f=Or(e,w=>w.toLowerCase()===l);if(f)return f;let b=Or(e,w=>w.toLowerCase().includes(l));if(b)return b}}let o=Ns(t.selector);if(o&&o!==t.selector&&jn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function jn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Kn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Hr(t.label),o=Hr(t.textHint);return r.find(i=>{let l=Hr(i.getAttribute("data-fork-new"));return !!l&&(l===n||l===o)})??null}function Os(e){return e.trim()==="[data-fork-new]"}function Hr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ns(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Or(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let l=s.getBoundingClientRect();if(l.width<4||l.height<4)continue;let f=l.width*l.height;f<n&&(r=s,n=f);}return r}var Nr=2147483600,Us=1600,Bs=3e4,Ds=300,Ge=10;function js(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let l=e.getBoundingClientRect(),f=Math.min(l.width,l.height);return Math.max(4,i/100*f)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function Ks(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,l=e;l==="top"&&t.top<n+Ge+8?l="bottom":l==="bottom"&&i-t.bottom<n+Ge+8?l="top":l==="left"&&t.left<r+Ge+8?l="right":l==="right"&&s-t.right<r+Ge+8&&(l="left");let f=0,b=0;return l==="top"?(f=t.top-n-Ge,b=t.left+t.width/2-r/2):l==="bottom"?(f=t.bottom+Ge,b=t.left+t.width/2-r/2):l==="left"?(f=t.top+t.height/2-n/2,b=t.left-r-Ge):(f=t.top+t.height/2-n/2,b=t.right+Ge),b=Math.max(8,Math.min(b,s-r-8)),f=Math.max(8,Math.min(f,i-n-8)),{top:f,left:b,placement:l}}function zs(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Nr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Nr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Nr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function Js(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
59
59
  @keyframes __fork-highlight-pulse {
60
60
  0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
61
61
  50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
62
62
  }
63
- `,document.head.appendChild(e);}function Wn(e,t,r="top"){Ws();let{outline:n,glow:o,tooltip:s}=zs(t),i=js(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${Us}ms ease-in-out infinite`,document.body.append(o,n,s);let l=()=>{let u=e.getBoundingClientRect();if(u.width===0&&u.height===0)return;n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,n.style.width=`${u.width}px`,n.style.height=`${u.height}px`,o.style.top=`${u.top-1}px`,o.style.left=`${u.left-1}px`,o.style.width=`${u.width+2}px`,o.style.height=`${u.height+2}px`;let O=s.getBoundingClientRect(),P=O.width||s.offsetWidth||80,R=O.height||s.offsetHeight||26,g=Ks(r,u,P,R);s.style.top=`${g.top}px`,s.style.left=`${g.left}px`;};l(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(l);});let f=false,w=new ResizeObserver(l);w.observe(e);let h=()=>l(),p=()=>l();window.addEventListener("scroll",h,true),window.addEventListener("resize",p);let F=()=>{f||(f=true,clearTimeout(y),w.disconnect(),window.removeEventListener("scroll",h,true),window.removeEventListener("resize",p),window.removeEventListener("click",I,true),n.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{n.remove(),o.remove(),s.remove();},Ds));},I=()=>F();setTimeout(()=>{f||window.addEventListener("click",I,{once:true,capture:true});},250);let y=setTimeout(F,Bs);return F}var Vs="fork:highlight:v1:seen";function Vn(e){return `${Vs}:${e}`}function Jn(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Js(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var qn=new Set;function Xn(e,t,r){return `${r}::${e}:${t}`}function Nr(e,t,r){let n=Xn(e,t,r);return qn.has(n)?true:Jn(Vn(r)).has(`${e}:${t}`)}function Gn(e,t,r){let n=Xn(e,t,r);qn.add(n);let o=Vn(r),s=`${e}:${t}`,i=Jn(o);i.has(s)||(i.add(s),Js(o,i));}var Et=new Map,$t=new Map,Ur=new Map;function Xs(e){for(let t of e)$t.set(t,($t.get(t)??0)+1);}function Gs(e){if(!(typeof document>"u"))for(let t of e){let r=($t.get(t)??0)-1;if(r>0){$t.set(t,r);continue}$t.delete(t),Et.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Ys(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Qn(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let r=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<n&&t.left<r}function Zn(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function Qs(e){if(!e||typeof document>"u")return Promise.resolve();let t=Et.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((s,i)=>{let l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),s();},f=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",f,{once:true});});return Et.set(e,o),o}let n=new Promise((o,s)=>{let i=document.createElement("link");i.rel="stylesheet",i.href=e,i.setAttribute("data-fork-override-href",e),i.onload=()=>o(),i.onerror=()=>{i.remove(),s(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(i);}).catch(o=>{throw Et.delete(e),o});return Et.set(e,n),n}var Ct=null;function Zs(){if(Ct)return Ct;try{Ct=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{Ct=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return Ct}function ei(e){let t=Ur.get(e);if(t)return t;let r=Zs()(e).catch(n=>{throw Ur.delete(e),n});return Ur.set(e,r),r}async function ti(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>Qs(s)));let o=await ei(e.moduleUrl);return Zn(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Zn(n,r)}function ri(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:l,getBoundaryOverride:f,consumeBoundaryAnimation:w,highlightScope:h}=we(),[p,F]=useState(null),[I,y]=useState(null),u=useRef(null),O=useRef(null),P=useRef(null),R=useRef(false),g=useRef(null),C=useRef(null),_=useRef(null),D=useRef(false),U=useRef(false),T=f(e.id),se=T?`override:${T.id}`:"original",W=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),g.current&&(g.current.remove(),g.current=null),_.current&&(_.current(),_.current=null);},[]),useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,W]),useEffect(()=>{let A=T?.cssUrls??[];if(A.length!==0)return Xs(A),()=>Gs(A)},[T?.cssUrls.join("|")]),useEffect(()=>{if(o&&!s&&!p||O.current===se&&p)return;let A=false;return y(null),ti(T,e.original,e.exportName).then(S=>{if(A)return;let N=T?.id?w(e.id,T.id):false;if(D.current=N,N&&u.current){let B=Mr(u.current);if(B){let K=Pr(B);K.length>0&&(P.current=K,R.current=true,C.current&&(clearTimeout(C.current),C.current=null),g.current&&g.current.remove(),g.current=On(B));}}O.current=se,startTransition(()=>{F(()=>S);});}).catch(S=>{A||y(Ys(S));}),()=>{A=true;}},[w,se,o,s,i,T?.id,T?.moduleUrl,T?.integrity,T?.cssUrls.join("|"),e.exportName,e.original,p]),useEffect(()=>{if(!p||!u.current)return;let A=false,S=null,N=()=>{if(A||!u.current)return false;let B=T?.highlightHint,K=T?.id,X=T?.createdAt?String(T.createdAt):"";if(!B||!K||Nr(K,X,h))return false;let G=Array.from(u.current.querySelectorAll("[data-fork-new]"));G.length,G.map(L=>L.getAttribute("data-fork-new")),B.label,B.textHint,B.selector;let q=zn(u.current,B);return q?.tagName,q?.getAttribute("data-fork-new"),q?.getAttribute("aria-label"),q?.textContent?.trim().slice(0,60),!q||!Qn(q)?(q&&Qn(q),q?.getBoundingClientRect(),false):(Gn(K,X,h),g.current&&(g.current.remove(),g.current=null),_.current&&_.current(),_.current=Wn(q,B.label,B.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(A||!u.current)return;let B=D.current,K=!U.current;U.current=true;let X=B||K,G=X?N():false;if(X&&!G&&T?.highlightHint&&T?.id&&!Nr(T.id,String(T.createdAt??""),h)){let j=[150,400,800],ne=0,Ee=()=>{if(A||ne>=j.length)return;let Le=j[ne];ne+=1,S=setTimeout(()=>{if(N()){G=true;return}Ee();},Le);};Ee();}let q=R.current,L=!!T?.highlightHint,k=P.current;if(P.current=null,R.current=false,G||L||!q){g.current&&(g.current.remove(),g.current=null);return}let E=Mr(u.current);if(!k||!E){g.current&&(g.current.remove(),g.current=null);return}let x=Pr(E),d=Nn(k,x),M=Un(k,x),v=g.current;if(M.length>0&&v){let j=Dn(M);C.current=setTimeout(()=>{C.current=null;let ne=400;v.animate([{opacity:1},{opacity:0}],{duration:ne,fill:"forwards"}),j.animate([{opacity:1},{opacity:0}],{duration:ne,fill:"forwards"}),setTimeout(()=>{v.remove(),j.remove(),g.current===v&&(g.current=null),d.length>0&&_r(d);},ne);},3500);}else v&&(v.remove(),g.current===v&&(g.current=null)),d.length>0&&_r(d);});}),()=>{A=true,S!==null&&(clearTimeout(S),S=null);}},[p,T?.id,T?.createdAt,T?.highlightHint,h]),I)throw I;return p?jsx("div",{ref:u,"data-fork-boundary":e.id,style:{display:"contents"},children:jsx(p,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function oi({slotId:e,title:t,slotLabel:r}){return jsx(It,{slotId:e,title:t,slotLabel:r})}function ai(e){return e.replace(/\/+$/,"")}function li(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Tt(e,t="value"){let r=li(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function Dr(e){if(Array.isArray(e))return e.map(Dr);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=Dr(t[n]);return r}function no(e){return JSON.stringify(Dr(e))}function eo(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function to(e){let t=await e.json().catch(()=>({}));if(!e.ok){let r=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(r)}return t}function oo(e){let t=ai(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let l=i&&typeof i=="object"&&!Array.isArray(i)?i:{},f=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:eo(e),body:JSON.stringify({...r,...l})});return to(f)},o=async(s,i)=>{let l=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[w,h]of Object.entries(i))h&&l.set(w,h);let f=await fetch(`${t}/api/v1/data${s}?${l.toString()}`,{headers:eo(e)});return to(f)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return n("/features",s)},queryValues(s){return n("/values/query",s)},setValues(s){return n("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return n("/options",s)},ensureLlmJobs(s){return n("/llm/ensure",s)},queryLlmJobs(s){return n("/llm/jobs/query",s)}}}function tr(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,userHash:s,userId:i}=we(),l=e||o;return useMemo(()=>{if(!r||!l)return null;let f=ce();return oo({apiKey:t,appId:r,baseUrl:n,containerId:l,userId:i,userHash:s,extraHeaders:f})},[t,r,n,l,s,i])}function ui(e){let t=tr(e.containerId),[r,n]=useState(null),[o,s]=useState([]),[i,l]=useState(false),[f,w]=useState(null),h=no({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),p=useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){l(true);try{let y=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(y.feature),s(y.values),w(null);}catch(y){w(y instanceof Error?y:new Error(String(y)));}finally{l(false);}}},[t,h]);useEffect(()=>{p();},[p]),useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let y=setInterval(()=>{p();},e.pollMs);return ()=>clearInterval(y)},[e.pollMs,p]);let F=useMemo(()=>new Map(o.map(y=>[Tt(y.entity,y.valueKey),y])),[o]),I=useCallback((y,u="value")=>F.get(Tt(y,u))??null,[F]);return {feature:r,values:o,byKey:F,getValue:I,loading:i,error:f,refresh:p}}function ci(e){let t=tr(e),r=useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(s)},[t]);return {client:t,ensureFeature:r,setValues:n,setOptions:o}}function ro(e){return e.some(t=>t.status==="queued"||t.status==="running")}function di(e){let t=tr(e.containerId),[r,n]=useState(null),[o,s]=useState([]),[i,l]=useState([]),[f,w]=useState(false),[h,p]=useState(null),F=useRef(""),I=no({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),y=useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){w(true);try{let R=await t.ensureLlmJobs(e);F.current=I,n(R.feature),s(R.jobs),l(R.values),p(null);}catch(R){p(R instanceof Error?R:new Error(String(R)));}finally{w(false);}}},[t,I]),u=useCallback(async()=>{if(!t)return;let R=o.map(g=>g.id);try{if(R.length>0){let g=await t.queryLlmJobs({jobIds:R});s(g.jobs);}if(e.featureId||e.featureKey){let g=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(C=>C.entity),valueKeys:Array.from(new Set(e.jobs.map(C=>C.valueKey||"value")))});n(g.feature),l(g.values);}p(null);}catch(g){p(g instanceof Error?g:new Error(String(g)));}},[t,o,I]);useEffect(()=>{F.current!==I&&y();},[y,I]),useEffect(()=>{let R=e.pollMs??3e3;if(R<=0||!ro(o))return;let g=setInterval(()=>{u();},R);return ()=>clearInterval(g)},[e.pollMs,o,u]);let O=useMemo(()=>new Map(i.map(R=>[Tt(R.entity,R.valueKey),R])),[i]),P=useCallback((R,g="value")=>O.get(Tt(R,g))??null,[O]);return {feature:r,jobs:o,values:i,byKey:O,getValue:P,loading:f,error:h,ensure:y,refresh:u,running:ro(o)}}export{Ls as ForkBoundaryUI,Sr as ForkButton,It as ForkChatInterface,Yt as ForkPanel,Ho as ForkProvider,Xo as ForkSlot,oi as ForkUI,vo as clearCachedManifest,oo as createForkDataClient,Tt as forkEntityValueKey,ri as forkable,pr as loadManifest,Fo as manifestDiffers,bo as readCachedManifest,cr as registerForkShared,Rr as useBoundaryFork,Cr as useFork,$r as useForkChatPanel,tr as useForkDataClient,ci as useForkDataMutation,ui as useForkFeatureValues,di as useForkLlmJobs,wo as writeCachedManifest};
63
+ `,document.head.appendChild(e);}function Jn(e,t,r="top"){Js();let{outline:n,glow:o,tooltip:s}=zs(t),i=js(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${Us}ms ease-in-out infinite`,document.body.append(o,n,s);let l=()=>{let d=e.getBoundingClientRect();if(d.width===0&&d.height===0)return;n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,n.style.width=`${d.width}px`,n.style.height=`${d.height}px`,o.style.top=`${d.top-1}px`,o.style.left=`${d.left-1}px`,o.style.width=`${d.width+2}px`,o.style.height=`${d.height+2}px`;let F=s.getBoundingClientRect(),T=F.width||s.offsetWidth||80,C=F.height||s.offsetHeight||26,g=Ks(r,d,T,C);s.style.top=`${g.top}px`,s.style.left=`${g.left}px`;};l(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(l);});let f=false,b=new ResizeObserver(l);b.observe(e);let w=()=>l(),p=()=>l();window.addEventListener("scroll",w,true),window.addEventListener("resize",p);let h=()=>{f||(f=true,clearTimeout(k),b.disconnect(),window.removeEventListener("scroll",w,true),window.removeEventListener("resize",p),window.removeEventListener("click",R,true),n.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{n.remove(),o.remove(),s.remove();},Ds));},R=()=>h();setTimeout(()=>{f||window.addEventListener("click",R,{once:true,capture:true});},250);let k=setTimeout(h,Bs);return h}var Ws="fork:highlight:v1:seen";function Wn(e){return `${Ws}:${e}`}function Vn(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Vs(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var qn=new Set;function Xn(e,t,r){return `${r}::${e}:${t}`}function Ur(e,t,r){let n=Xn(e,t,r);return qn.has(n)?true:Vn(Wn(r)).has(`${e}:${t}`)}function Gn(e,t,r){let n=Xn(e,t,r);qn.add(n);let o=Wn(r),s=`${e}:${t}`,i=Vn(o);i.has(s)||(i.add(s),Vs(o,i));}var Tt=new Map,Mt=new Map,Br=new Map;function Xs(e){for(let t of e)Mt.set(t,(Mt.get(t)??0)+1);}function Gs(e){if(!(typeof document>"u"))for(let t of e){let r=(Mt.get(t)??0)-1;if(r>0){Mt.set(t,r);continue}Mt.delete(t),Tt.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Ys(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Qn(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let r=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<n&&t.left<r}function Zn(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function Qs(e){if(!e||typeof document>"u")return Promise.resolve();let t=Tt.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((s,i)=>{let l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),s();},f=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",f,{once:true});});return Tt.set(e,o),o}let n=new Promise((o,s)=>{let i=document.createElement("link");i.rel="stylesheet",i.href=e,i.setAttribute("data-fork-override-href",e),i.onload=()=>o(),i.onerror=()=>{i.remove(),s(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(i);}).catch(o=>{throw Tt.delete(e),o});return Tt.set(e,n),n}var $t=null;function Zs(){if($t)return $t;try{$t=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{$t=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return $t}function ei(e){let t=Br.get(e);if(t)return t;let r=Zs()(e).catch(n=>{throw Br.delete(e),n});return Br.set(e,r),r}async function ti(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>Qs(s)));let o=await ei(e.moduleUrl);return Zn(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Zn(n,r)}function ri(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:l,getBoundaryOverride:f,consumeBoundaryAnimation:b,highlightScope:w}=we(),[p,h]=useState(null),[R,k]=useState(null),d=useRef(null),F=useRef(null),T=useRef(null),C=useRef(false),g=useRef(null),$=useRef(null),_=useRef(null),K=useRef(false),O=useRef(false),N=f(e.id),ne=N?`override:${N.id}`:"original",G=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{$.current&&(clearTimeout($.current),$.current=null),g.current&&(g.current.remove(),g.current=null),_.current&&(_.current(),_.current=null);},[]),useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,G]),useEffect(()=>{let M=N?.cssUrls??[];if(M.length!==0)return Xs(M),()=>Gs(M)},[N?.cssUrls.join("|")]),useEffect(()=>{if(o&&!s&&!p||F.current===ne&&p)return;let M=false;return k(null),ti(N,e.original,e.exportName).then(y=>{if(M)return;let L=N?.id?b(e.id,N.id):false;if(K.current=L,L&&d.current){let B=Pr(d.current);if(B){let D=_r(B);D.length>0&&(T.current=D,C.current=true,$.current&&(clearTimeout($.current),$.current=null),g.current&&g.current.remove(),g.current=On(B));}}F.current=ne,startTransition(()=>{h(()=>y);});}).catch(y=>{M||k(Ys(y));}),()=>{M=true;}},[b,ne,o,s,i,N?.id,N?.moduleUrl,N?.integrity,N?.cssUrls.join("|"),e.exportName,e.original,p]),useEffect(()=>{if(!p||!d.current)return;let M=false,y=null,L=()=>{if(M||!d.current)return false;let B=N?.highlightHint,D=N?.id,W=N?.createdAt?String(N.createdAt):"";if(!B||!D||Ur(D,W,w))return false;let z=Array.from(d.current.querySelectorAll("[data-fork-new]"));z.length,z.map(U=>U.getAttribute("data-fork-new")),B.label,B.textHint,B.selector;let V=zn(d.current,B);return V?.tagName,V?.getAttribute("data-fork-new"),V?.getAttribute("aria-label"),V?.textContent?.trim().slice(0,60),!V||!Qn(V)?(V&&Qn(V),V?.getBoundingClientRect(),false):(Gn(D,W,w),g.current&&(g.current.remove(),g.current=null),_.current&&_.current(),_.current=Jn(V,B.label,B.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(M||!d.current)return;let B=K.current,D=!O.current;O.current=true;let W=B||D,z=W?L():false;if(W&&!z&&N?.highlightHint&&N?.id&&!Ur(N.id,String(N.createdAt??""),w)){let J=[150,400,800],se=0,Ae=()=>{if(M||se>=J.length)return;let Pe=J[se];se+=1,y=setTimeout(()=>{if(L()){z=true;return}Ae();},Pe);};Ae();}let V=C.current,U=!!N?.highlightHint,S=T.current;if(T.current=null,C.current=false,z||U||!V){g.current&&(g.current.remove(),g.current=null);return}let I=Pr(d.current);if(!S||!I){g.current&&(g.current.remove(),g.current=null);return}let A=_r(I),u=Nn(S,A),P=Un(S,A),v=g.current;if(P.length>0&&v){let J=Dn(P);$.current=setTimeout(()=>{$.current=null;let se=400;v.animate([{opacity:1},{opacity:0}],{duration:se,fill:"forwards"}),J.animate([{opacity:1},{opacity:0}],{duration:se,fill:"forwards"}),setTimeout(()=>{v.remove(),J.remove(),g.current===v&&(g.current=null),u.length>0&&Lr(u);},se);},3500);}else v&&(v.remove(),g.current===v&&(g.current=null)),u.length>0&&Lr(u);});}),()=>{M=true,y!==null&&(clearTimeout(y),y=null);}},[p,N?.id,N?.createdAt,N?.highlightHint,w]),R)throw R;return p?jsx("div",{ref:d,"data-fork-boundary":e.id,style:{display:"contents"},children:jsx(p,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function oi({slotId:e,title:t,slotLabel:r}){return jsx(Ct,{slotId:e,title:t,slotLabel:r})}function ai(e){return e.replace(/\/+$/,"")}function li(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Pt(e,t="value"){let r=li(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function jr(e){if(Array.isArray(e))return e.map(jr);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=jr(t[n]);return r}function no(e){return JSON.stringify(jr(e))}function eo(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function to(e){let t=await e.json().catch(()=>({}));if(!e.ok){let r=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(r)}return t}function oo(e){let t=ai(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let l=i&&typeof i=="object"&&!Array.isArray(i)?i:{},f=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:eo(e),body:JSON.stringify({...r,...l})});return to(f)},o=async(s,i)=>{let l=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[b,w]of Object.entries(i))w&&l.set(b,w);let f=await fetch(`${t}/api/v1/data${s}?${l.toString()}`,{headers:eo(e)});return to(f)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return n("/features",s)},queryValues(s){return n("/values/query",s)},setValues(s){return n("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return n("/options",s)},ensureLlmJobs(s){return n("/llm/ensure",s)},queryLlmJobs(s){return n("/llm/jobs/query",s)}}}function or(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,userHash:s,userId:i}=we(),l=e||o;return useMemo(()=>{if(!r||!l)return null;let f=de();return oo({apiKey:t,appId:r,baseUrl:n,containerId:l,userId:i,userHash:s,extraHeaders:f})},[t,r,n,l,s,i])}function ui(e){let t=or(e.containerId),[r,n]=useState(null),[o,s]=useState([]),[i,l]=useState(false),[f,b]=useState(null),w=no({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),p=useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){l(true);try{let k=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(k.feature),s(k.values),b(null);}catch(k){b(k instanceof Error?k:new Error(String(k)));}finally{l(false);}}},[t,w]);useEffect(()=>{p();},[p]),useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let k=setInterval(()=>{p();},e.pollMs);return ()=>clearInterval(k)},[e.pollMs,p]);let h=useMemo(()=>new Map(o.map(k=>[Pt(k.entity,k.valueKey),k])),[o]),R=useCallback((k,d="value")=>h.get(Pt(k,d))??null,[h]);return {feature:r,values:o,byKey:h,getValue:R,loading:i,error:f,refresh:p}}function ci(e){let t=or(e),r=useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(s)},[t]);return {client:t,ensureFeature:r,setValues:n,setOptions:o}}function ro(e){return e.some(t=>t.status==="queued"||t.status==="running")}function di(e){let t=or(e.containerId),[r,n]=useState(null),[o,s]=useState([]),[i,l]=useState([]),[f,b]=useState(false),[w,p]=useState(null),h=useRef(""),R=no({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),k=useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){b(true);try{let C=await t.ensureLlmJobs(e);h.current=R,n(C.feature),s(C.jobs),l(C.values),p(null);}catch(C){p(C instanceof Error?C:new Error(String(C)));}finally{b(false);}}},[t,R]),d=useCallback(async()=>{if(!t)return;let C=o.map(g=>g.id);try{if(C.length>0){let g=await t.queryLlmJobs({jobIds:C});s(g.jobs);}if(e.featureId||e.featureKey){let g=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map($=>$.entity),valueKeys:Array.from(new Set(e.jobs.map($=>$.valueKey||"value")))});n(g.feature),l(g.values);}p(null);}catch(g){p(g instanceof Error?g:new Error(String(g)));}},[t,o,R]);useEffect(()=>{h.current!==R&&k();},[k,R]),useEffect(()=>{let C=e.pollMs??3e3;if(C<=0||!ro(o))return;let g=setInterval(()=>{d();},C);return ()=>clearInterval(g)},[e.pollMs,o,d]);let F=useMemo(()=>new Map(i.map(C=>[Pt(C.entity,C.valueKey),C])),[i]),T=useCallback((C,g="value")=>F.get(Pt(C,g))??null,[F]);return {feature:r,jobs:o,values:i,byKey:F,getValue:T,loading:f,error:w,ensure:k,refresh:d,running:ro(o)}}export{Ls as ForkBoundaryUI,xr as ForkButton,Ct as ForkChatInterface,er as ForkPanel,Ho as ForkProvider,Xo as ForkSlot,oi as ForkUI,vo as clearCachedManifest,oo as createForkDataClient,Pt as forkEntityValueKey,ri as forkable,gr as loadManifest,Fo as manifestDiffers,bo as readCachedManifest,dr as registerForkShared,Cr as useBoundaryFork,Er as useFork,Tr as useForkChatPanel,or as useForkDataClient,ci as useForkDataMutation,ui as useForkFeatureValues,di as useForkLlmJobs,wo as writeCachedManifest};