@fork-api/chat-sdk 0.1.161 → 0.1.162

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.cjs CHANGED
@@ -1,7 +1,7 @@
1
- 'use strict';var ur=require('react'),zn=require('react-dom'),Wn=require('react/jsx-runtime'),Kn=require('react/jsx-dev-runtime'),lucideReact=require('lucide-react');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ur__namespace=/*#__PURE__*/_interopNamespace(ur);var zn__namespace=/*#__PURE__*/_interopNamespace(zn);var Wn__namespace=/*#__PURE__*/_interopNamespace(Wn);var Kn__namespace=/*#__PURE__*/_interopNamespace(Kn);var qe="__FORK_SHARED__";function er(){var t,r,n,o;let e=globalThis;return e[qe]||(e[qe]={}),(t=e[qe]).react||(t.react=ur__namespace),(r=e[qe])["react-dom"]||(r["react-dom"]=zn__namespace),(n=e[qe])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Wn__namespace),(o=e[qe])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Kn__namespace),e[qe]}function tr(e){return Object.assign(er(),e)}var Xn="__fork_preview_session__";function Lt(e){return `${Xn}${e}`}var Q={apiKey:null,session:null},rr=new Set;function Nt(){for(let e of rr)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Ur(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Vn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Lt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Ur(r)?(window.sessionStorage.removeItem(Lt(e)),null):r}catch{return null}}function nr(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Lt(e),JSON.stringify(t)):window.sessionStorage.removeItem(Lt(e));}catch{}}function it(e){Q.apiKey!==e&&(Q.apiKey=e,Q.session=Vn(e),Nt());}function Ue(){return Q.session?Ur(Q.session)?(Bt(null),null):Q.session:null}function Bt(e){Q.session=e,Q.apiKey&&nr(Q.apiKey,e),Nt();}function ut(e){Q.session&&Q.session.fork_id!==e&&(Q.session={...Q.session,fork_id:e},Q.apiKey&&nr(Q.apiKey,Q.session),Nt());}function Ge(e,t){Q.session&&(Q.session.container_id===e&&Q.session.container_name===t||(Q.session={...Q.session,container_id:e,container_name:t??Q.session.container_name??"Fork",fork_id:null},Q.apiKey&&nr(Q.apiKey,Q.session),Nt()));}function or(e){return rr.add(e),()=>{rr.delete(e);}}var Dr="__fork_preview";function jr(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(Dr);return typeof r=="string"&&r.length>0?r:null}function ir(e){if(typeof window>"u")return false;try{let t=window.sessionStorage.getItem(`__fork_preview_session__${e}`);if(t){let r=JSON.parse(t),n=typeof r?.expires_at=="string"?Date.parse(r.expires_at):NaN;if(Number.isFinite(n)&&n>Date.now())return !0;window.sessionStorage.removeItem(`__fork_preview_session__${e}`);}}catch{}return Wr()!==null}function zr(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(Dr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Ye=null,sr=null,ft=null;function Wr(){if(Ye)return Ye;let e=jr();return e?(Ye=e,zr(),Ye):null}async function ar(e,t){it(e);let r=Ue();if(r)return Ye=null,r;let n=Ye??jr();if(Ye=null,!n)return null;zr();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let l=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${l.error??"unknown"}`),null}let s=await o.json(),i={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Bt(i),i}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function lr(e,t,r){it(e);let n=Ue();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
2
- `);return ft&&sr===o||(sr=o,ft=(async()=>{try{let s=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(s.status===204)return null;if(!s.ok){let c=await s.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${s.status}): ${c.error??"unknown"}`),null}let i=await s.json(),l={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Bt(l),l}catch(s){return console.warn("[fork-preview] auto admin activate threw",s),null}finally{sr=null,ft=null;}})()),ft}function qn(){return Ue()}function Gn(){return null}function Ot(){return ur.useSyncExternalStore(or,qn,Gn)}function ee(){let e=Ue();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Ut(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,c]of Object.entries(s.modules)){let g=c.moduleUrl??c.bundleUrl??null,b=c.legacyModuleUrl??c.legacyBundleUrl??null;i[l]={forkId:c.forkId,moduleUrl:g,legacyModuleUrl:b,bundleUrl:c.bundleUrl??g,legacyBundleUrl:c.legacyBundleUrl??b,cssUrls:c.cssUrls??[],integrity:c.integrity,metadata:c.metadata,buildId:c.buildId,updatedAt:c.updatedAt};}return {containerId:s.containerId,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var Yn="fork:manifest:v1";function cr(e,t,r){return `${Yn}:${e}:${t}:${r}`}function Zn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(cr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Qn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(cr(e,t,r),JSON.stringify(n));}catch{}}function eo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(cr(e,t,r));}catch{}}function to(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)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 c=t.slots[i];if(!c||c.forkId!==l.forkId||c.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 c=t.modules[i];if(!c||c.forkId!==l.forkId||c.buildId!==l.buildId)return true}return false}var Yr=ur.createContext(null),oo=12e3,so=45e3,Kr="fork:activity:v1",Xr="fork:feature-highlight:v1",io=new Set(["pending","running","building"]),ao="Setting up environment";function Ae(e){return io.has(e)}function lo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function co(e,t){let r=lo(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 Vr(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 Dt(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 pt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function De(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 je(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function uo(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function fo(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:Ae(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=>Ae(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():ao,detail:s?uo(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 mt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Jr(e,t){if(!e||!t)return e;let r=e.includes("?")?"&":"?";return `${e}${r}fork_v=${encodeURIComponent(t)}`}function mo(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:mt(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(s=>mt(e,s)):[]};return r}function qr(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:mt(e,l),createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function Gr(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";if(!s)continue;let i=o.buildId?void 0:o.updatedAt,l=Jr(mt(e,s),i);r[n]={id:o.forkId,boundaryId:n,moduleUrl:l,cssUrls:(o.cssUrls??[]).map(c=>Jr(mt(e,c),i)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt};}return r}function go(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,l="authUrl"in e?e.authUrl:void 0,[c]=ur.useState(()=>(it(t),ir(t))),[g,b]=ur.useState({}),[f,k]=ur.useState(i?{userId:i,userHash:void 0}:null),[R,C]=ur.useState(!!i||c),[F,_]=ur.useState({}),[U,A]=ur.useState(!o),[w,O]=ur.useState(0),[$,T]=ur.useState(null),[I,v]=ur.useState([]),[p,P]=ur.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),h=ur.useRef(new Map),d=ur.useRef(new Map),[H,j]=ur.useState(0),N=ur.useRef(new Set),x=ur.useRef(new Map),y=ur.useRef(void 0),B=ur.useRef(new Map),J=ur.useRef([]),G=ur.useRef(new Set),Se=ur.useRef(false);er(),ur.useEffect(()=>{return ar(t,r).then(()=>{}),()=>{}},[]);let D=Ot();ur.useEffect(()=>{c||D||!o||!f?.userHash||lr(t,r,{appId:o,userId:f.userId,userHash:f.userHash});},[t,o,f?.userHash,f?.userId,r,c,D?.preview_session_id]),s&&y.current!==s&&(tr(s),y.current=s),ur.useEffect(()=>{l&&(c||(C(false),fetch(l,{credentials:"include"}).then(m=>{if(!m.ok)throw new Error(`Auth endpoint returned ${m.status}`);return m.json()}).then(m=>{if(!m.userId||typeof m.userId!="string")throw new Error("authUrl response must include userId");k({userId:m.userId,userHash:typeof m.userHash=="string"?m.userHash:void 0});}).catch(m=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",m.message);}).finally(()=>{C(true);})));},[l,c]),ur.useEffect(()=>{!l&&i&&(k({userId:i,userHash:void 0}),C(true));},[i,l]);let te=f?.userId??"",ue=f?.userHash,Y=D?"":te,ne=D?void 0:ue,tt=!!o,_e=ur.useCallback(async()=>{if(!tt){T(null),_({}),A(true),O(u=>u+1);return}if(!R){A(false);return}if(!D&&!Y||!o){T(null),_({}),A(true),O(u=>u+1);return}if(A(false),!D){try{let u=await Ut({baseUrl:r,apiKey:t,appId:o,userId:Y,userHash:ne});u&&(T(u.containerId),b(qr(r,u,Y,o)),_(Gr(r,u)));}catch(u){console.error("[ForkProvider] Failed to fetch fork manifest:",u.message),T(null),b({}),_({});}finally{O(u=>u+1),A(true);}return}if(T(D.container_id??null),D.container_id){try{let u=await Ut({baseUrl:r,apiKey:t,appId:o,userId:Y,containerId:D.container_id,extraHeaders:ee()});u&&(b(qr(r,u,Y,o)),_(Gr(r,u)));}catch(u){console.error("[ForkProvider] Failed to fetch preview container manifest:",u.message),b({}),_({});}finally{O(u=>u+1),A(true);}return}let m=new URLSearchParams({appId:o,userId:Y});ne&&m.set("userHash",ne);try{let u=await fetch(`${r}/api/v1/boundaries/manifest?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ee()}});if(!u.ok)throw new Error(`${u.status}`);let M=await u.json();_(mo(r,M));}catch(u){console.error("[ForkProvider] Failed to fetch module override manifest:",u.message),_({});}finally{O(u=>u+1),A(true);}},[t,o,r,R,tt,ne,Y,D?.preview_session_id,D?.fork_id,D?.container_id]);ur.useEffect(()=>{if(!Y||o&&(!D||D.container_id))return;let m=new URLSearchParams({userId:Y});ne&&m.set("userHash",ne),fetch(`${r}/api/v1/forks/active?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ee()}}).then(u=>{if(!u.ok)throw new Error(`${u.status}`);return u.json()}).then(u=>{u&&typeof u=="object"&&b(u);}).catch(()=>{});},[t,o,Y,ne,r,D?.preview_session_id,D?.fork_id]),ur.useEffect(()=>{_e();},[_e]);let Ie=ur.useCallback((m,u)=>{b(M=>({...M,[m]:u}));},[]),me=ur.useCallback(m=>{b(u=>{let M={...u};return delete M[m],M});},[]),Me=ur.useCallback(m=>{N.current.add(m);},[]),Ke=ur.useCallback(m=>N.current.has(m)?(N.current.delete(m),true):false,[]),rt=D?`preview:${D.preview_session_id}`:Y,$e=`${t}:${o||"no-app"}:${$||D?.container_id||"no-container"}:${rt||"anonymous"}`,Te=`${Xr}:${$e}`,Xe=ur.useCallback((m,u)=>{x.current.set(m,u);},[]),Ct=ur.useCallback((m,u,M)=>{if(x.current.get(m)!==u)return false;x.current.delete(m);let W=`${m}:${M||u}`,z=De(Te);return z.has(W)?false:(z.add(W),je(Te,z),true)},[Te]),Zt=ur.useCallback(m=>{if(!o)return;let u=JSON.stringify(m);h.current.get(m.id)===u||d.current.get(m.id)?.signature===u||(d.current.set(m.id,{boundary:m,signature:u}),j(Z=>Z+1));},[o]);ur.useEffect(()=>{if(!o||d.current.size===0)return;let m=setTimeout(()=>{let u=Array.from(d.current.values());u.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:u.map(M=>M.boundary)})}).then(M=>{if(!M.ok)throw new Error(`${M.status}`)}).then(()=>{for(let M of u)d.current.get(M.boundary.id)?.signature===M.signature&&(d.current.delete(M.boundary.id),h.current.set(M.boundary.id,M.signature));}).catch(M=>{console.error("[ForkProvider] Failed to register module boundaries:",M.message);});},50);return ()=>{clearTimeout(m);}},[t,o,r,H]);let Et=ur.useCallback(m=>F[m],[F]),ae=D?`preview:${D.preview_session_id}`:Y,Ve=`${t}:${o||"no-app"}:${$||"no-container"}:${ae||"anonymous"}`,Ce=`${Kr}:seen:${Ve}`,fe=`${Kr}:tracked:${Ve}`;ur.useEffect(()=>{J.current=I;},[I]);let nt=ur.useCallback(()=>{let m={Authorization:`Bearer ${t}`,...ee()};return o&&(m["X-Fork-App-Id"]=o),!D&&Y&&(m["X-Fork-User-Id"]=Y),!D&&ne&&(m["X-Fork-User-Hash"]=ne),m},[t,o,D,ne,Y]),xe=ur.useCallback(async()=>{if(!$)return;let m=new URLSearchParams({container_id:$}),u=await fetch(`${r}/api/v1/forks?${m.toString()}`,{headers:nt()}).catch(()=>null);if(!u||!u.ok)return;let M=await u.json().catch(()=>({})),Z=Array.isArray(M.forks)?M.forks:[],W=De(Ce),z=De(fe),K=false,re=new Map(J.current.map(oe=>[oe.id,oe])),pe=[];for(let oe of Z){let se=Vr(oe);Ae(se.status)&&!z.has(se.id)&&(z.add(se.id),K=true);let le=re.get(se.id),ce=le?Ae(le.status):false,Fe=pt(se);se.status==="complete"&&(z.has(se.id)||ce)&&!W.has(Fe)&&!G.current.has(Fe)&&!le?.unread&&(Se.current||z.has(se.id)||ce)&&(G.current.add(Fe),pe.push(se));}if(v(oe=>{let se=new Map(oe.map(X=>[X.id,X])),le=new Set,ce=new Map;for(let X of Z){let we=Vr(X);le.add(we.id);let ke=se.get(we.id),ve=ke?Ae(ke.status):false,ge=pt(we),Pt=we.status==="complete"&&(z.has(we.id)||ve)&&!W.has(ge),ct=Dt(ke,{...we,unread:Pt});ce.set(we.id,ct);}for(let X of oe)le.has(X.id)||(Ae(X.status)||X.unread)&&ce.set(X.id,X);let Fe=[...ce.values()].sort((X,we)=>Date.parse(we.updatedAt)-Date.parse(X.updatedAt));return J.current=Fe,Fe}),K&&je(fe,z),pe.length>0){for(let oe of pe)oe.targetKind==="module"&&Xe(oe.targetId,oe.id);_e().catch(()=>{});}Se.current=true;},[Ce,fe,r,nt,$,_e,Xe]),He=ur.useCallback((m,u)=>{let M=co(m,u);if(!M)return;let Z=m.containerId??m._containerId;if(Z&&!$&&T(Z),Ae(M.status)){let K=De(fe);K.has(M.id)||(K.add(M.id),je(fe,K));}let W=new Map(J.current.map(K=>[K.id,K]));W.set(M.id,Dt(W.get(M.id),M));let z=[...W.values()].sort((K,re)=>Date.parse(re.updatedAt)-Date.parse(K.updatedAt));J.current=z,v(z);},[fe,$]),Le=ur.useCallback((m,u)=>{let M=fo(u),Z=De(Ce),W=De(fe),z=J.current.find(le=>le.id===m),K=z?Ae(z.status):false;M.status&&Ae(M.status)&&!W.has(m)&&(W.add(m),je(fe,W));let re=z?Dt(z,{...z,...M}):null,pe=re?pt(re):null,oe=!!(re&&re.status==="complete"&&(W.has(m)||K)&&pe&&!Z.has(pe)&&!G.current.has(pe)&&!z?.unread),se=u.type==="complete"&&z?.targetKind==="module"?z.targetId:null;if(v(le=>{let ce=le.find(ve=>ve.id===m);if(!ce)return le;let Fe=Dt(ce,{...ce,...M}),X=Fe.status==="complete"&&(W.has(m)||Ae(ce.status))&&!Z.has(pt(Fe)),we={...Fe,unread:X},ke=le.map(ve=>ve.id===m?we:ve).sort((ve,ge)=>Date.parse(ge.updatedAt)-Date.parse(ve.updatedAt));return J.current=ke,ke}),oe&&re&&pe&&G.current.add(pe),u.type==="complete"){let le=u.data&&typeof u.data=="object"?u.data:{},ce=typeof le.boundaryId=="string"?le.boundaryId:se;ce&&Xe(ce,m),_e().catch(()=>{});}},[Ce,fe,_e,Xe]),lt=ur.useCallback(m=>{let u=De(Ce),M=De(fe),Z=false,W=false;for(let z of J.current){if(z.status!=="complete"||m&&z.id!==m)continue;let K=pt(z);u.has(K)||(u.add(K),Z=true),M.delete(z.id)&&(W=true);}v(z=>{let K=z.map(re=>re.status!=="complete"||m&&re.id!==m?re:{...re,unread:false});return J.current=K,K}),Z&&je(Ce,u),W&&je(fe,M);},[Ce,fe]);ur.useEffect(()=>{Se.current=false,G.current.clear(),v([]);for(let m of B.current.values())m.close();B.current.clear(),$&&xe();},[$,xe]),ur.useEffect(()=>{if(typeof document>"u")return;let m=()=>{let u=document.visibilityState!=="hidden";P(u),u&&$&&xe();};return document.addEventListener("visibilitychange",m),window.addEventListener("focus",m),window.addEventListener("online",m),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("focus",m),window.removeEventListener("online",m);}},[$,xe]),ur.useEffect(()=>{let m=I.filter(Z=>Ae(Z.status));if(!$||m.length===0)return;let u=p?oo:so,M=window.setInterval(()=>{xe();},u);return ()=>window.clearInterval(M)},[$,p,I,xe]),ur.useEffect(()=>{for(let m of B.current.values())m.close();B.current.clear();},[t,r,D?.preview_session_id,ne,Y]),ur.useEffect(()=>{let m=new Set(I.filter(u=>Ae(u.status)).map(u=>u.id));for(let[u,M]of B.current.entries())m.has(u)||(M.close(),B.current.delete(u));for(let u of m){if(B.current.has(u))continue;let M=new URLSearchParams({key:t});D?(M.set("previewSessionId",D.preview_session_id),M.set("previewForkId",u)):Y&&M.set("userId",Y),ne&&M.set("userHash",ne);let Z=new EventSource(`${r}/api/v1/forks/${u}/events?${M.toString()}`);Z.onmessage=W=>{try{Le(u,JSON.parse(W.data));}catch{}},Z.onerror=()=>{Z.close(),B.current.delete(u);},B.current.set(u,Z);}},[t,r,I,D,Le,ne,Y]),ur.useEffect(()=>()=>{for(let m of B.current.values())m.close();B.current.clear();},[]);let $t=po(I),Ne=ur.useCallback(async()=>{if(!Y)throw new Error("Reset requires a resolved user identity.");let m=new URLSearchParams({userId:Y});ne&&m.set("userHash",ne);let u={Authorization:`Bearer ${t}`,...ee()};o&&(u["X-Fork-App-Id"]=o);let M=await fetch(`${r}/api/v1/forks/all?${m.toString()}`,{method:"DELETE",headers:u});if(!M.ok){let W=await M.json().catch(()=>({}));throw new Error(W.error||`API error: ${M.status}`)}let Z=await M.json().catch(()=>({}));b({}),_({}),A(true),O(W=>W+1),v([]),G.current.clear(),je(Ce,new Set),je(fe,new Set),N.current.clear(),x.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let z=sessionStorage.key(W);z&&z.startsWith("__fork_animated_")&&sessionStorage.removeItem(z);}}catch{}try{for(let W=localStorage.length-1;W>=0;W-=1){let z=localStorage.key(W);z&&z.startsWith(Xr)&&localStorage.removeItem(z);}}catch{}return Z},[Ce,fe,t,o,r,ne,Y]);return Wn.jsx(Yr.Provider,{value:{apiKey:t,userId:Y,userHash:ne,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:tt,moduleManifestReady:U,moduleManifestVersion:w,currentContainerId:$,forkActivities:I,activitySummary:$t,previewSession:D,trackForkActivity:He,recordForkActivityEvent:Le,markForkActivitySeen:lt,refreshForkActivities:xe,setSlotFork:Ie,clearSlotFork:me,skipAnimationForSlot:Me,shouldSkipAnimation:Ke,queueBoundaryAnimation:Xe,consumeBoundaryAnimation:Ct,registerBoundary:Zt,getBoundaryOverride:Et,refreshModuleManifest:_e,resetAllForks:Ne},children:n})}function ye(){let e=ur.useContext(Yr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function jt(e){return ye().forks[e]}var gt=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];}};function fr(e,t){let r;try{r=ur.Children.only(e);}catch{let o=ur.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 Qr=new Set;function en(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 wo(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 vo(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 rn(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 tn(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 b=0;b<e.length;b++){let{rect:f,borderRadius:k}=e[b],R=f.left-.5,C=f.top-.5,F=f.width+1,_=f.height+1,U=Math.min(k+.5,F/2,_/2),A=rn(R,C,F,_,U),w=`__fork-glow-${b}`,O=document.createElementNS(t,"filter");O.setAttribute("id",w),O.setAttribute("x","-100%"),O.setAttribute("y","-100%"),O.setAttribute("width","300%"),O.setAttribute("height","300%");let $=document.createElementNS(t,"feGaussianBlur");$.setAttribute("in","SourceGraphic"),$.setAttribute("stdDeviation","8"),O.appendChild($),o.appendChild(O);let T=`__fork-mask-${b}`,I=document.createElementNS(t,"mask");I.setAttribute("id",T),I.setAttribute("maskUnits","userSpaceOnUse"),I.setAttribute("x",String(R-200)),I.setAttribute("y",String(C-200)),I.setAttribute("width",String(F+400)),I.setAttribute("height",String(_+400));let v=document.createElementNS(t,"rect");v.setAttribute("x",String(R-200)),v.setAttribute("y",String(C-200)),v.setAttribute("width",String(F+400)),v.setAttribute("height",String(_+400)),v.setAttribute("fill","white"),I.appendChild(v);let p=document.createElementNS(t,"path");p.setAttribute("d",A),p.setAttribute("fill","black"),I.appendChild(p),o.appendChild(I);let P=document.createElementNS(t,"g");P.setAttribute("mask",`url(#${T})`),P.setAttribute("opacity","0");let h=document.createElementNS(t,"g");h.setAttribute("filter",`url(#${w})`);let d=document.createElementNS(t,"path");d.setAttribute("d",A),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),d.setAttribute("stroke-width","6"),d.setAttribute("stroke-linecap","round"),h.appendChild(d),P.appendChild(h),n.appendChild(P);let H=document.createElementNS(t,"path");H.setAttribute("d",A),H.setAttribute("fill","none"),H.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),H.setAttribute("stroke-width","2"),H.setAttribute("stroke-linecap","round"),H.setAttribute("opacity","0"),n.appendChild(H),s.push(d,H),d.__group=P;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let b=0;b<s.length;b+=2){let f=s[b],k=s[b+1],R=f.__group,C=k.getTotalLength(),F=f.getTotalLength();if(C<=0)continue;let _=C*.35;k.setAttribute("stroke-dasharray",`${_} ${C-_}`),k.setAttribute("stroke-dashoffset","0"),i.push(k.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*C,opacity:.92,offset:.06},{strokeDashoffset:-2*C,opacity:.92,offset:.92},{strokeDashoffset:-2.25*C,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let U=F*.35;f.setAttribute("stroke-dasharray",`${U} ${F-U}`),f.setAttribute("stroke-dashoffset","0"),i.push(f.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*F,offset:.06},{strokeDashoffset:-2*F,offset:.92},{strokeDashoffset:-2.25*F,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,c=()=>{if(l)return;l=true,clearTimeout(g);for(let f of i)try{f.cancel();}catch{}let b=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});b.onfinish=()=>r.remove(),window.removeEventListener("click",c);},g=setTimeout(c,14500);return setTimeout(()=>{l||window.addEventListener("click",c);},500),c}function So(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:c}of e){let g=l.left,b=l.top,f=l.width,k=l.height,R=Math.min(c,f/2,k/2),C=rn(g,b,f,k,R),F=document.createElementNS(t,"path");F.setAttribute("d",C),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),F.setAttribute("stroke-width","1.5"),F.setAttribute("stroke-dasharray","8 4"),F.setAttribute("stroke-linecap","round"),F.setAttribute("filter","url(#__fork-removed-shadow)"),F.setAttribute("opacity","0"),n.appendChild(F),F.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 xo(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 Fo=ur__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return Wn.jsx("div",{ref:r,style:n,children:Wn.jsx(t,{...o})})},(e,t)=>e.component===t.component&&xo(e.hostProps,t.hostProps)),dr=class extends ur__namespace.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 nn({slotId:e,children:t,githubRepo:r,shared:n,events:o}){fr(t,e);let s=jt(e),{baseUrl:i,apiKey:l,appId:c,shouldSkipAnimation:g}=ye(),[b,f]=ur.useState(null),k=ur.useRef(null),R=ur.useRef(null),C=ur.useRef(null),F=ur.useRef(false),_=ur.useRef(null),U=ur.useRef(null),A=!!(n||o),w=ur.useRef(null);A&&!w.current&&(w.current=new gt(e));let O=ur.useRef(o);if(O.current=o,ur.useEffect(()=>{if(A)return ()=>{w.current?.destroy(),w.current=null;}},[A,e]),A&&w.current&&n)for(let[p,P]of Object.entries(n))w.current.set(p,P);ur.useEffect(()=>{if(!A)return;w.current||(w.current=new gt(e));let p=w.current,P=Object.keys(O.current||{}).map(h=>p.on(h,(...d)=>O.current?.[h]?.(...d)));return ()=>P.forEach(h=>h())},[A,e]),ur.useEffect(()=>{if(Qr.has(e))return;Qr.add(e);let p={id:e,appId:c,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${i}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(p)}).catch(()=>{});},[e,i,l,r,c]);let $=s?.id||null;ur.useEffect(()=>{if(s?.bundleUrl,k.current,R.current,!s?.bundleUrl||!$){return}let p=`${i}${s.bundleUrl.replace("bundle.js","component.js")}`,P=`__fork_animated_${e}`,h=sessionStorage.getItem(P),d=g(e),H=!d&&h!==$;if(d&&$&&sessionStorage.setItem(P,$),H&&R.current){let B=en(R.current);C.current=B,F.current=true,`${e}${B.length}`;}window.__FORK_REACT__=ur__namespace.default,window.__FORK_REACT_DOM__=zn__namespace,window.__FORK_REACT_JSX__=Wn__namespace;let j=Date.now(),N=`${i}${s.bundleUrl.replace("bundle.js","component.css")}?t=${j}`,x=document.createElement("link");x.rel="stylesheet",x.href=N,x.dataset.forkSlot=e,document.head.appendChild(x);let y=document.createElement("script");return y.src=p+"?t="+j,y.onload=()=>{let B=window.__FORK_EXPORT__;if(B?.default){if(R.current&&C.current&&F.current){let J=R.current.getBoundingClientRect(),G=R.current.cloneNode(true);G.setAttribute("data-fork-clone-overlay","true"),G.style.position="fixed",G.style.top=`${J.top}px`,G.style.left=`${J.left}px`,G.style.width=`${J.width}px`,G.style.height=`${J.height}px`,G.style.flex="none",G.style.minHeight="auto",G.style.zIndex="9998",G.style.pointerEvents="none",G.style.overflow="hidden";let Se=getComputedStyle(R.current).backgroundColor;G.style.backgroundColor=Se&&Se!=="rgba(0, 0, 0, 0)"&&Se!=="transparent"?Se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(G);let D=R.current.querySelectorAll("*"),te=G.querySelectorAll("*");for(let ue=0;ue<D.length;ue++)D[ue].scrollTop!==0&&(te[ue].scrollTop=D[ue].scrollTop),D[ue].scrollLeft!==0&&(te[ue].scrollLeft=D[ue].scrollLeft);_.current=G;}f(()=>B.default),k.current=$;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},y.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(y),()=>{y.remove(),x.remove(),U.current&&(clearTimeout(U.current),U.current=null),_.current&&(_.current.remove(),_.current=null);}},[$,i,e]),ur.useEffect(()=>{if(!F.current||!b||!R.current){`${e}${F.current}`,R.current;return}let p=C.current;if(!p){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let P=en(R.current),h=wo(p,P),d=vo(p,P),H=_.current;if(`${e}${h.length}${d.length}`,d.length>0&&H){let j=So(d);U.current=setTimeout(()=>{U.current=null;let N=400;H.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),j.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),setTimeout(()=>{H.remove(),j.remove(),_.current=null,h.length>0&&(tn(h));},N);},3500);}else H&&(H.remove(),_.current=null),h.length>0&&(tn(h));C.current=null,F.current=false,$&&(sessionStorage.setItem(`__fork_animated_${e}`,$),`${e}`);});});},[b]);let T={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!s||s.status!=="complete"||!s.bundleUrl)return Wn.jsx("div",{ref:R,style:T,children:t});if(!b)return Wn.jsx("div",{ref:R,style:T,children:t});let v=t?.props??{};return Wn.jsx(dr,{slotId:e,resetKey:$,fallback:Wn.jsx("div",{ref:R,style:T,children:t}),children:Wn.jsx(Fo,{component:b,containerRef:R,wrapperStyle:T,hostProps:v})})}var sn=new Set;function _o(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 an(e,t=new Set){return ur.Children.forEach(e,r=>{if(!ur.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&&an(n.children,t);}),t}function Co({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:s,mode:i="iframe",shared:l,events:c}){if(fr(r,e),i==="direct")return Wn.jsx(nn,{slotId:e,githubRepo:o,shared:l,events:c,children:r});let g=jt(e),{baseUrl:b,apiKey:f,appId:k}=ye(),R=ur.useRef(null),C=ur.useRef(false),F=ur.useRef(null),_=ur.useRef(s);_.current=s;let U=ur.useRef(t);U.current=t;let A=ur.useRef(n);A.current=n,ur.useEffect(()=>{if(typeof process<"u")return;let T=an(r),I=new Set(s?Object.keys(s):[]),v=[...T].filter(p=>!I.has(p));v.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:
3
- `+v.map(p=>` - ${p}`).join(`
4
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,s]),ur.useEffect(()=>{sn.has(e)||(sn.add(e),fetch(`${b}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:k,label:e,propsShape:t?_o(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:s?Object.keys(s):[],mode:i||"iframe"})}).catch(()=>{}));},[e,b,f,o,k]);let w=ur.useCallback(T=>{let I=R.current;if(I?.contentWindow&&C.current){let v=_.current?Object.keys(_.current):[];I.contentWindow.postMessage({type:"slot:props",props:T,callbackNames:v},"*"),F.current=null;}else F.current=T;},[]),O=ur.useCallback((T,I)=>{let v=A.current;return !v||v.length===0?false:v.some(p=>{let[P,h]=p.split(" "),d=I.split("?")[0];return T.toUpperCase()===P.toUpperCase()&&d.startsWith(h)})},[]);if(ur.useEffect(()=>{if(!g?.bundleUrl)return;let T=async I=>{if(I.source===R.current?.contentWindow){if(I.data?.type==="slot:ready")C.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,F.current?w(F.current):w(U.current||{});else if(I.data?.type==="slot:event"){let v=I.data.event;v?.navigate&&(window.location.hash=v.navigate);}else if(I.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(I.data.text).catch(v=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,v.message);});else if(I.data?.type==="slot:callback"){let{name:v,args:p}=I.data,P=_.current?.[v];P?(P(...p||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${v}`);}else if(I.data?.type==="slot:fetch"){let{id:v,method:p,url:P,body:h}=I.data,d=R.current?.contentWindow;if(!d)return;let H=p||"GET";if(!O(H,P)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${v}: ${H} ${P} \u2014 not in allowedFetches`),d.postMessage({type:"slot:fetch-response",id:v,error:`Fetch not allowed: ${H} ${P}`},"*");return}try{let j={method:H};h&&H!=="GET"&&(j.headers={"Content-Type":"application/json"},j.body=JSON.stringify(h));let N=await fetch(P,j),x=await N.json();`${e}${v}${N.status}`,d.postMessage({type:"slot:fetch-response",id:v,data:x,status:N.status},"*");}catch(j){console.error(`[ForkSlot:${e}] fetch #${v} failed:`,j.message),d.postMessage({type:"slot:fetch-response",id:v,error:j.message},"*");}}}};return window.addEventListener("message",T),()=>{window.removeEventListener("message",T),C.current=false;}},[g?.bundleUrl,e,w,O]),ur.useEffect(()=>{g?.bundleUrl&&C.current&&w(t||{});},[t,g?.bundleUrl,w]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,Wn.jsx(Wn.Fragment,{children:r});`${e}${g.bundleUrl}`;let $=`${b}${g.bundleUrl.replace("/bundle.js","/host")}`;return Wn.jsx("iframe",{ref:R,src:$,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Wt({style:e={width:20,height:20},...t}){return Wn.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Wn.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"}),Wn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Wn.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"}),Wn.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"}),Wn.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 Mo=5600,mr=2147483002;function To(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Ho(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function gr(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 Lo(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 hr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=ur.useState(false),[s,i]=ur.useState(false),[l,c]=ur.useState(null),[g,b]=ur.useState(null),[f,k]=ur.useState(null),R=ur.useRef(0),C=n?48:40,F=To(r),_=!!(F&&r?.state==="complete"&&r.unreadCompletedCount>0),U=_?F:g?.key??null,A=!!(r&&r.state==="running"&&r.runningCount>0),w=!!(U&&U!==l&&(_||g)),O=A||w,$=_?r?.label:g?.label,T=w?"Built":r?.label??"Fork this app",I=w?$:r?.detail,v=gr(r?.label??"Fork this app",r?.detail),p=gr(T,I),P=w?Math.min(420,Math.max(326,p,g?.width??0,R.current+40)):p,h=w?46:40,d=O?[T,I].filter(Boolean).join(" "):Lo(r,t)??"Fork this app",H=O?`${T}:${I??""}`:"idle",j=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!O;ur.useEffect(()=>{if(typeof document>"u")return;let te=document.createElement("div");return te.setAttribute("data-fork-button-host","true"),te.style.position="relative",te.style.zIndex=String(mr),document.body.appendChild(te),k(te),()=>{te.remove(),k(null);}},[]),ur.useEffect(()=>{A&&(R.current=v);},[v,A]),ur.useEffect(()=>{!_||!F||!r?.label||b(te=>{if(te?.key===F)return te;let ue=Math.min(420,Math.max(326,gr("Built",r.label),R.current+40));return {key:F,label:r.label,width:ue,startedAt:Date.now()}});},[r?.label,F,_]),ur.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&b(null);},[r?.state,r?.unreadCompletedCount]),ur.useEffect(()=>{if(!U||!w||U===l)return;let te,ue=g?.key===U?g.startedAt:Date.now(),Y=()=>{if(Date.now()-ue>=Mo&&!Ho()){c(U);return}te=window.setTimeout(Y,250);};return te=window.setTimeout(Y,250),()=>{te!==void 0&&window.clearTimeout(te);}},[U,l,g?.key,g?.startedAt,w]);let N=O?{position:"fixed",bottom:24,right:24,zIndex:mr,width:`min(${P}px, calc(100vw - 32px))`,height:h,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:w?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:w?"flex-start":"center",gap:w?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:w?"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:mr,width:C,height:C,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?"#1c4587":"rgba(28, 69, 135, 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:A?286:w?82:I?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},y={minWidth:0,maxWidth:w?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:w?1:0,color:"#64748b",fontSize:A?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},B={minWidth:0,flex:w?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:w?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},J={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:w?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},D=Wn.jsxs(Wn.Fragment,{children:[Wn.jsx("style",{children:`
1
+ 'use strict';var ur=require('react'),eo=require('react-dom'),to=require('react/jsx-runtime'),ro=require('react/jsx-dev-runtime'),lucideReact=require('lucide-react');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ur__namespace=/*#__PURE__*/_interopNamespace(ur);var eo__namespace=/*#__PURE__*/_interopNamespace(eo);var to__namespace=/*#__PURE__*/_interopNamespace(to);var ro__namespace=/*#__PURE__*/_interopNamespace(ro);var Ve="__FORK_SHARED__";function Qt(){var t,r,n,o;let e=globalThis;return e[Ve]||(e[Ve]={}),(t=e[Ve]).react||(t.react=ur__namespace),(r=e[Ve])["react-dom"]||(r["react-dom"]=eo__namespace),(n=e[Ve])["react/jsx-runtime"]||(n["react/jsx-runtime"]=to__namespace),(o=e[Ve])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=ro__namespace),e[Ve]}function er(e){return Object.assign(Qt(),e)}var no="__fork_preview_session__";function Tt(e){return `${no}${e}`}var te={apiKey:null,session:null},tr=new Set;function Mt(){for(let e of tr)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function zr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function oo(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Tt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:zr(r)?(window.sessionStorage.removeItem(Tt(e)),null):r}catch{return null}}function rr(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Tt(e),JSON.stringify(t)):window.sessionStorage.removeItem(Tt(e));}catch{}}function st(e){te.apiKey!==e&&(te.apiKey=e,te.session=oo(e),Mt());}function Be(){return te.session?zr(te.session)?(Lt(null),null):te.session:null}function Lt(e){te.session=e,te.apiKey&&rr(te.apiKey,e),Mt();}function ut(e){te.session&&te.session.fork_id!==e&&(te.session={...te.session,fork_id:e},te.apiKey&&rr(te.apiKey,te.session),Mt());}function Xe(e,t){te.session&&(te.session.container_id===e&&te.session.container_name===t||(te.session={...te.session,container_id:e,container_name:t??te.session.container_name??"Fork",fork_id:null},te.apiKey&&rr(te.apiKey,te.session),Mt()));}function nr(e){return tr.add(e),()=>{tr.delete(e);}}var Kr="__fork_preview";function Wr(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(Kr);return typeof r=="string"&&r.length>0?r:null}function sr(e){if(typeof window>"u")return false;try{let t=window.sessionStorage.getItem(`__fork_preview_session__${e}`);if(t){let r=JSON.parse(t),n=typeof r?.expires_at=="string"?Date.parse(r.expires_at):NaN;if(Number.isFinite(n)&&n>Date.now())return !0;window.sessionStorage.removeItem(`__fork_preview_session__${e}`);}}catch{}return Xr()!==null}function Vr(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(Kr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Je=null,or=null,dt=null;function Xr(){if(Je)return Je;let e=Wr();return e?(Je=e,Vr(),Je):null}async function ir(e,t){st(e);let r=Be();if(r)return Je=null,r;let n=Je??Wr();if(Je=null,!n)return null;Vr();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let s=await o.json(),i={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Lt(i),i}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function ar(e,t,r){st(e);let n=Be();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
2
+ `);return dt&&or===o||(or=o,dt=(async()=>{try{let s=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(s.status===204)return null;if(!s.ok){let u=await s.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${s.status}): ${u.error??"unknown"}`),null}let i=await s.json(),a={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Lt(a),a}catch(s){return console.warn("[fork-preview] auto admin activate threw",s),null}finally{or=null,dt=null;}})()),dt}function io(){return Be()}function ao(){return null}function Ht(){return ur.useSyncExternalStore(nr,io,ao)}function ne(){let e=Be();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Bt(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[a,u]of Object.entries(s.modules)){let p=u.moduleUrl??u.bundleUrl??null,h=u.legacyModuleUrl??u.legacyBundleUrl??null;i[a]={forkId:u.forkId,moduleUrl:p,legacyModuleUrl:h,bundleUrl:u.bundleUrl??p,legacyBundleUrl:u.legacyBundleUrl??h,cssUrls:u.cssUrls??[],integrity:u.integrity,metadata:u.metadata,highlightHint:u.highlightHint,buildId:u.buildId,updatedAt:u.updatedAt};}return {containerId:s.containerId,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var lo="fork:manifest:v1";function lr(e,t,r){return `${lo}:${e}:${t}:${r}`}function co(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(lr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function uo(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(lr(e,t,r),JSON.stringify(n));}catch{}}function fo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(lr(e,t,r));}catch{}}function po(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,a]of r){let u=t.slots[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,a]of o){let u=t.modules[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}return false}var Zr=ur.createContext(null),ho=12e3,yo=45e3,Jr="fork:activity:v1",ko=new Set(["pending","running","building"]),bo="Setting up environment";function Se(e){return ko.has(e)}function wo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function vo(e,t){let r=wo(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 qr(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 Nt(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 ft(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function qe(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 Ge(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function So(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function xo(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:Se(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 Fo(e){let t=e.filter(o=>Se(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():bo,detail:s?So(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 pt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Ao(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:pt(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(s=>pt(e,s)):[]};return r}function Gr(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let a=i.bundleUrl??i.legacyBundleUrl;a&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:pt(e,a),createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function Yr(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:pt(e,s),cssUrls:(o.cssUrls??[]).map(i=>pt(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function _o(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[u]=ur.useState(()=>(st(t),sr(t))),[p,h]=ur.useState({}),[d,v]=ur.useState(i?{userId:i,userHash:void 0}:null),[w,x]=ur.useState(!!i||u),[f,F]=ur.useState({}),[N,_]=ur.useState(!o),[S,U]=ur.useState(0),[L,C]=ur.useState(null),[P,R]=ur.useState([]),[k,$]=ur.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),b=ur.useRef(new Map),c=ur.useRef(new Map),[T,j]=ur.useState(0),H=ur.useRef(new Set),y=ur.useRef(new Map),A=ur.useRef(void 0),O=ur.useRef(new Map),G=ur.useRef([]),z=ur.useRef(new Set),pe=ur.useRef(false);Qt(),ur.useEffect(()=>{return ir(t,r).then(()=>{}),()=>{}},[]);let D=Ht();ur.useEffect(()=>{u||D||!o||!d?.userHash||ar(t,r,{appId:o,userId:d.userId,userHash:d.userHash});},[t,o,d?.userHash,d?.userId,r,u,D?.preview_session_id]),s&&A.current!==s&&(er(s),A.current=s),ur.useEffect(()=>{a&&(u||(x(false),fetch(a,{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`Auth endpoint returned ${g.status}`);return g.json()}).then(g=>{if(!g.userId||typeof g.userId!="string")throw new Error("authUrl response must include userId");v({userId:g.userId,userHash:typeof g.userHash=="string"?g.userHash:void 0});}).catch(g=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",g.message);}).finally(()=>{x(true);})));},[a,u]),ur.useEffect(()=>{!a&&i&&(v({userId:i,userHash:void 0}),x(true));},[i,a]);let Q=d?.userId??"",le=d?.userHash,Y=D?"":Q,ie=D?void 0:le,et=!!o,Fe=ur.useCallback(async()=>{if(!et){C(null),F({}),_(true),U(m=>m+1);return}if(!w){_(false);return}if(!D&&!Y||!o){C(null),F({}),_(true),U(m=>m+1);return}if(_(false),!D){try{let m=await Bt({baseUrl:r,apiKey:t,appId:o,userId:Y,userHash:ie});m&&(C(m.containerId),h(Gr(r,m,Y,o)),F(Yr(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch fork manifest:",m.message),C(null),h({}),F({});}finally{U(m=>m+1),_(true);}return}if(C(D.container_id??null),D.container_id){try{let m=await Bt({baseUrl:r,apiKey:t,appId:o,userId:Y,containerId:D.container_id,extraHeaders:ne()});m&&(h(Gr(r,m,Y,o)),F(Yr(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch preview container manifest:",m.message),h({}),F({});}finally{U(m=>m+1),_(true);}return}let g=new URLSearchParams({appId:o,userId:Y});ie&&g.set("userHash",ie);try{let m=await fetch(`${r}/api/v1/boundaries/manifest?${g.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ne()}});if(!m.ok)throw new Error(`${m.status}`);let M=await m.json();F(Ao(r,M));}catch(m){console.error("[ForkProvider] Failed to fetch module override manifest:",m.message),F({});}finally{U(m=>m+1),_(true);}},[t,o,r,w,et,ie,Y,D?.preview_session_id,D?.fork_id,D?.container_id]);ur.useEffect(()=>{if(!Y||o&&(!D||D.container_id))return;let g=new URLSearchParams({userId:Y});ie&&g.set("userHash",ie),fetch(`${r}/api/v1/forks/active?${g.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ne()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{m&&typeof m=="object"&&h(m);}).catch(()=>{});},[t,o,Y,ie,r,D?.preview_session_id,D?.fork_id]),ur.useEffect(()=>{Fe();},[Fe]);let Re=ur.useCallback((g,m)=>{h(M=>({...M,[g]:m}));},[]),me=ur.useCallback(g=>{h(m=>{let M={...m};return delete M[g],M});},[]),$e=ur.useCallback(g=>{H.current.add(g);},[]),Ue=ur.useCallback(g=>H.current.has(g)?(H.current.delete(g),true):false,[]),Ce=ur.useCallback((g,m)=>{y.current.set(g,m);},[]),Ee=ur.useCallback((g,m)=>y.current.get(g)!==m?false:(y.current.delete(g),true),[]),De=ur.useCallback(g=>{if(!o)return;let m=JSON.stringify(g);b.current.get(g.id)===m||c.current.get(g.id)?.signature===m||(c.current.set(g.id,{boundary:g,signature:m}),j(ee=>ee+1));},[o]);ur.useEffect(()=>{if(!o||c.current.size===0)return;let g=setTimeout(()=>{let m=Array.from(c.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(M=>M.boundary)})}).then(M=>{if(!M.ok)throw new Error(`${M.status}`)}).then(()=>{for(let M of m)c.current.get(M.boundary.id)?.signature===M.signature&&(c.current.delete(M.boundary.id),b.current.set(M.boundary.id,M.signature));}).catch(M=>{console.error("[ForkProvider] Failed to register module boundaries:",M.message);});},50);return ()=>{clearTimeout(g);}},[t,o,r,T]);let Gt=ur.useCallback(g=>f[g],[f]),Ct=D?`preview:${D.preview_session_id}`:Y,at=`${t}:${o||"no-app"}:${L||"no-container"}:${Ct||"anonymous"}`,ve=`${Jr}:seen:${at}`,W=`${Jr}:tracked:${at}`;ur.useEffect(()=>{G.current=P;},[P]);let je=ur.useCallback(()=>{let g={Authorization:`Bearer ${t}`,...ne()};return o&&(g["X-Fork-App-Id"]=o),!D&&Y&&(g["X-Fork-User-Id"]=Y),!D&&ie&&(g["X-Fork-User-Hash"]=ie),g},[t,o,D,ie,Y]),Pe=ur.useCallback(async()=>{if(!L)return;let g=new URLSearchParams({container_id:L}),m=await fetch(`${r}/api/v1/forks?${g.toString()}`,{headers:je()}).catch(()=>null);if(!m||!m.ok)return;let M=await m.json().catch(()=>({})),ee=Array.isArray(M.forks)?M.forks:[],X=qe(ve),K=qe(W),oe=false,ae=new Map(G.current.map(J=>[J.id,J])),be=[];for(let J of ee){let ce=qr(J);Se(ce.status)&&!K.has(ce.id)&&(K.add(ce.id),oe=true);let re=ae.get(ce.id),se=re?Se(re.status):false,ge=ft(ce);ce.status==="complete"&&(K.has(ce.id)||se)&&!X.has(ge)&&!z.current.has(ge)&&!re?.unread&&(pe.current||K.has(ce.id)||se)&&(z.current.add(ge),be.push(ce));}if(R(J=>{let ce=new Map(J.map(de=>[de.id,de])),re=new Set,se=new Map;for(let de of ee){let he=qr(de);re.add(he.id);let He=ce.get(he.id),Z=He?Se(He.status):false,lt=ft(he),Te=he.status==="complete"&&(K.has(he.id)||Z)&&!X.has(lt),rt=Nt(He,{...he,unread:Te});se.set(he.id,rt);}for(let de of J)re.has(de.id)||(Se(de.status)||de.unread)&&se.set(de.id,de);let ge=[...se.values()].sort((de,he)=>Date.parse(he.updatedAt)-Date.parse(de.updatedAt));return G.current=ge,ge}),oe&&Ge(W,K),be.length>0){for(let J of be)J.targetKind==="module"&&Ce(J.targetId,J.id);Fe().catch(()=>{});}pe.current=true;},[ve,W,r,je,L,Fe,Ce]),Et=ur.useCallback((g,m)=>{let M=vo(g,m);if(!M)return;let ee=g.containerId??g._containerId;if(ee&&!L&&C(ee),Se(M.status)){let oe=qe(W);oe.has(M.id)||(oe.add(M.id),Ge(W,oe));}let X=new Map(G.current.map(oe=>[oe.id,oe]));X.set(M.id,Nt(X.get(M.id),M));let K=[...X.values()].sort((oe,ae)=>Date.parse(ae.updatedAt)-Date.parse(oe.updatedAt));G.current=K,R(K);},[W,L]),ze=ur.useCallback((g,m)=>{let M=xo(m),ee=qe(ve),X=qe(W),K=G.current.find(re=>re.id===g),oe=K?Se(K.status):false;M.status&&Se(M.status)&&!X.has(g)&&(X.add(g),Ge(W,X));let ae=K?Nt(K,{...K,...M}):null,be=ae?ft(ae):null,J=!!(ae&&ae.status==="complete"&&(X.has(g)||oe)&&be&&!ee.has(be)&&!z.current.has(be)&&!K?.unread),ce=m.type==="complete"&&K?.targetKind==="module"?K.targetId:null;if(R(re=>{let se=re.find(Z=>Z.id===g);if(!se)return re;let ge=Nt(se,{...se,...M}),de=ge.status==="complete"&&(X.has(g)||Se(se.status))&&!ee.has(ft(ge)),he={...ge,unread:de},He=re.map(Z=>Z.id===g?he:Z).sort((Z,lt)=>Date.parse(lt.updatedAt)-Date.parse(Z.updatedAt));return G.current=He,He}),J&&ae&&be&&z.current.add(be),m.type==="complete"){let re=m.data&&typeof m.data=="object"?m.data:{},se=typeof re.boundaryId=="string"?re.boundaryId:ce;se&&Ce(se,g),Fe().catch(()=>{});}},[ve,W,Fe,Ce]),tt=ur.useCallback(g=>{let m=qe(ve),M=qe(W),ee=false,X=false;for(let K of G.current){if(K.status!=="complete"||g&&K.id!==g)continue;let oe=ft(K);m.has(oe)||(m.add(oe),ee=true),M.delete(K.id)&&(X=true);}R(K=>{let oe=K.map(ae=>ae.status!=="complete"||g&&ae.id!==g?ae:{...ae,unread:false});return G.current=oe,oe}),ee&&Ge(ve,m),X&&Ge(W,M);},[ve,W]);ur.useEffect(()=>{pe.current=false,z.current.clear(),R([]);for(let g of O.current.values())g.close();O.current.clear(),L&&Pe();},[L,Pe]),ur.useEffect(()=>{if(typeof document>"u")return;let g=()=>{let m=document.visibilityState!=="hidden";$(m),m&&L&&Pe();};return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),window.addEventListener("online",g),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g),window.removeEventListener("online",g);}},[L,Pe]),ur.useEffect(()=>{let g=P.filter(ee=>Se(ee.status));if(!L||g.length===0)return;let m=k?ho:yo,M=window.setInterval(()=>{Pe();},m);return ()=>window.clearInterval(M)},[L,k,P,Pe]),ur.useEffect(()=>{for(let g of O.current.values())g.close();O.current.clear();},[t,r,D?.preview_session_id,ie,Y]),ur.useEffect(()=>{let g=new Set(P.filter(m=>Se(m.status)).map(m=>m.id));for(let[m,M]of O.current.entries())g.has(m)||(M.close(),O.current.delete(m));for(let m of g){if(O.current.has(m))continue;let M=new URLSearchParams({key:t});D?(M.set("previewSessionId",D.preview_session_id),M.set("previewForkId",m)):Y&&M.set("userId",Y),ie&&M.set("userHash",ie);let ee=new EventSource(`${r}/api/v1/forks/${m}/events?${M.toString()}`);ee.onmessage=X=>{try{ze(m,JSON.parse(X.data));}catch{}},ee.onerror=()=>{ee.close(),O.current.delete(m);},O.current.set(m,ee);}},[t,r,P,D,ze,ie,Y]),ur.useEffect(()=>()=>{for(let g of O.current.values())g.close();O.current.clear();},[]);let Ie=Fo(P),Ke=ur.useCallback(async()=>{if(!Y)throw new Error("Reset requires a resolved user identity.");let g=new URLSearchParams({userId:Y});ie&&g.set("userHash",ie);let m={Authorization:`Bearer ${t}`,...ne()};o&&(m["X-Fork-App-Id"]=o);let M=await fetch(`${r}/api/v1/forks/all?${g.toString()}`,{method:"DELETE",headers:m});if(!M.ok){let X=await M.json().catch(()=>({}));throw new Error(X.error||`API error: ${M.status}`)}let ee=await M.json().catch(()=>({}));h({}),F({}),_(true),U(X=>X+1),R([]),z.current.clear(),Ge(ve,new Set),Ge(W,new Set),H.current.clear(),y.current.clear();try{for(let X=sessionStorage.length-1;X>=0;X-=1){let K=sessionStorage.key(X);K&&K.startsWith("__fork_animated_")&&sessionStorage.removeItem(K);}}catch{}return ee},[ve,W,t,o,r,ie,Y]);return to.jsx(Zr.Provider,{value:{apiKey:t,userId:Y,userHash:ie,baseUrl:r,appId:o,forks:p,moduleOverridesEnabled:et,moduleManifestReady:N,moduleManifestVersion:S,currentContainerId:L,forkActivities:P,activitySummary:Ie,previewSession:D,trackForkActivity:Et,recordForkActivityEvent:ze,markForkActivitySeen:tt,refreshForkActivities:Pe,setSlotFork:Re,clearSlotFork:me,skipAnimationForSlot:$e,shouldSkipAnimation:Ue,queueBoundaryAnimation:Ce,consumeBoundaryAnimation:Ee,registerBoundary:De,getBoundaryOverride:Gt,refreshModuleManifest:Fe,resetAllForks:Ke,highlightScope:at},children:n})}function ke(){let e=ur.useContext(Zr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ot(e){return ke().forks[e]}var gt=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];}};function dr(e,t){let r;try{r=ur.Children.only(e);}catch{let o=ur.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 en=new Set;function tn(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 Po(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 a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Io(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 a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function nn(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 rn(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:d,borderRadius:v}=e[h],w=d.left-.5,x=d.top-.5,f=d.width+1,F=d.height+1,N=Math.min(v+.5,f/2,F/2),_=nn(w,x,f,F,N),S=`__fork-glow-${h}`,U=document.createElementNS(t,"filter");U.setAttribute("id",S),U.setAttribute("x","-100%"),U.setAttribute("y","-100%"),U.setAttribute("width","300%"),U.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),U.appendChild(L),o.appendChild(U);let C=`__fork-mask-${h}`,P=document.createElementNS(t,"mask");P.setAttribute("id",C),P.setAttribute("maskUnits","userSpaceOnUse"),P.setAttribute("x",String(w-200)),P.setAttribute("y",String(x-200)),P.setAttribute("width",String(f+400)),P.setAttribute("height",String(F+400));let R=document.createElementNS(t,"rect");R.setAttribute("x",String(w-200)),R.setAttribute("y",String(x-200)),R.setAttribute("width",String(f+400)),R.setAttribute("height",String(F+400)),R.setAttribute("fill","white"),P.appendChild(R);let k=document.createElementNS(t,"path");k.setAttribute("d",_),k.setAttribute("fill","black"),P.appendChild(k),o.appendChild(P);let $=document.createElementNS(t,"g");$.setAttribute("mask",`url(#${C})`),$.setAttribute("opacity","0");let b=document.createElementNS(t,"g");b.setAttribute("filter",`url(#${S})`);let c=document.createElementNS(t,"path");c.setAttribute("d",_),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),b.appendChild(c),$.appendChild(b),n.appendChild($);let T=document.createElementNS(t,"path");T.setAttribute("d",_),T.setAttribute("fill","none"),T.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),T.setAttribute("stroke-width","2"),T.setAttribute("stroke-linecap","round"),T.setAttribute("opacity","0"),n.appendChild(T),s.push(c,T),c.__group=$;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let h=0;h<s.length;h+=2){let d=s[h],v=s[h+1],w=d.__group,x=v.getTotalLength(),f=d.getTotalLength();if(x<=0)continue;let F=x*.35;v.setAttribute("stroke-dasharray",`${F} ${x-F}`),v.setAttribute("stroke-dashoffset","0"),i.push(v.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let N=f*.35;d.setAttribute("stroke-dasharray",`${N} ${f-N}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*f,offset:.06},{strokeDashoffset:-2*f,offset:.92},{strokeDashoffset:-2.25*f,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(w.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 a=false,u=()=>{if(a)return;a=true,clearTimeout(p);for(let d of i)try{d.cancel();}catch{}let h=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});h.onfinish=()=>r.remove(),window.removeEventListener("click",u);},p=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function To(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:a,borderRadius:u}of e){let p=a.left,h=a.top,d=a.width,v=a.height,w=Math.min(u,d/2,v/2),x=nn(p,h,d,v,w),f=document.createElementNS(t,"path");f.setAttribute("d",x),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),f.setAttribute("stroke-width","1.5"),f.setAttribute("stroke-dasharray","8 4"),f.setAttribute("stroke-linecap","round"),f.setAttribute("filter","url(#__fork-removed-shadow)"),f.setAttribute("opacity","0"),n.appendChild(f),f.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 Mo(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 Lo=ur__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return to.jsx("div",{ref:r,style:n,children:to.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Mo(e.hostProps,t.hostProps)),cr=class extends ur__namespace.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 on({slotId:e,children:t,githubRepo:r,shared:n,events:o}){dr(t,e);let s=Ot(e),{baseUrl:i,apiKey:a,appId:u,shouldSkipAnimation:p}=ke(),[h,d]=ur.useState(null),v=ur.useRef(null),w=ur.useRef(null),x=ur.useRef(null),f=ur.useRef(false),F=ur.useRef(null),N=ur.useRef(null),_=!!(n||o),S=ur.useRef(null);_&&!S.current&&(S.current=new gt(e));let U=ur.useRef(o);if(U.current=o,ur.useEffect(()=>{if(_)return ()=>{S.current?.destroy(),S.current=null;}},[_,e]),_&&S.current&&n)for(let[k,$]of Object.entries(n))S.current.set(k,$);ur.useEffect(()=>{if(!_)return;S.current||(S.current=new gt(e));let k=S.current,$=Object.keys(U.current||{}).map(b=>k.on(b,(...c)=>U.current?.[b]?.(...c)));return ()=>$.forEach(b=>b())},[_,e]),ur.useEffect(()=>{if(en.has(e))return;en.add(e);let k={id:e,appId:u,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${i}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(k)}).catch(()=>{});},[e,i,a,r,u]);let L=s?.id||null;ur.useEffect(()=>{if(s?.bundleUrl,v.current,w.current,!s?.bundleUrl||!L){return}let k=`${i}${s.bundleUrl.replace("bundle.js","component.js")}`,$=`__fork_animated_${e}`,b=sessionStorage.getItem($),c=p(e),T=!c&&b!==L;if(c&&L&&sessionStorage.setItem($,L),T&&w.current){let O=tn(w.current);x.current=O,f.current=true,`${e}${O.length}`;}window.__FORK_REACT__=ur__namespace.default,window.__FORK_REACT_DOM__=eo__namespace,window.__FORK_REACT_JSX__=to__namespace;let j=Date.now(),H=`${i}${s.bundleUrl.replace("bundle.js","component.css")}?t=${j}`,y=document.createElement("link");y.rel="stylesheet",y.href=H,y.dataset.forkSlot=e,document.head.appendChild(y);let A=document.createElement("script");return A.src=k+"?t="+j,A.onload=()=>{let O=window.__FORK_EXPORT__;if(O?.default){if(w.current&&x.current&&f.current){let G=w.current.getBoundingClientRect(),z=w.current.cloneNode(true);z.setAttribute("data-fork-clone-overlay","true"),z.style.position="fixed",z.style.top=`${G.top}px`,z.style.left=`${G.left}px`,z.style.width=`${G.width}px`,z.style.height=`${G.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let pe=getComputedStyle(w.current).backgroundColor;z.style.backgroundColor=pe&&pe!=="rgba(0, 0, 0, 0)"&&pe!=="transparent"?pe:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let D=w.current.querySelectorAll("*"),Q=z.querySelectorAll("*");for(let le=0;le<D.length;le++)D[le].scrollTop!==0&&(Q[le].scrollTop=D[le].scrollTop),D[le].scrollLeft!==0&&(Q[le].scrollLeft=D[le].scrollLeft);F.current=z;}d(()=>O.default),v.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},A.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(A),()=>{A.remove(),y.remove(),N.current&&(clearTimeout(N.current),N.current=null),F.current&&(F.current.remove(),F.current=null);}},[L,i,e]),ur.useEffect(()=>{if(!f.current||!h||!w.current){`${e}${f.current}`,w.current;return}let k=x.current;if(!k){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!w.current)return;let $=tn(w.current),b=Po(k,$),c=Io(k,$),T=F.current;if(`${e}${b.length}${c.length}`,c.length>0&&T){let j=To(c);N.current=setTimeout(()=>{N.current=null;let H=400;T.animate([{opacity:1},{opacity:0}],{duration:H,fill:"forwards"}),j.animate([{opacity:1},{opacity:0}],{duration:H,fill:"forwards"}),setTimeout(()=>{T.remove(),j.remove(),F.current=null,b.length>0&&(rn(b));},H);},3500);}else T&&(T.remove(),F.current=null),b.length>0&&(rn(b));x.current=null,f.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[h]);let C={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!s||s.status!=="complete"||!s.bundleUrl)return to.jsx("div",{ref:w,style:C,children:t});if(!h)return to.jsx("div",{ref:w,style:C,children:t});let R=t?.props??{};return to.jsx(cr,{slotId:e,resetKey:L,fallback:to.jsx("div",{ref:w,style:C,children:t}),children:to.jsx(Lo,{component:h,containerRef:w,wrapperStyle:C,hostProps:R})})}var an=new Set;function No(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 ln(e,t=new Set){return ur.Children.forEach(e,r=>{if(!ur.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&&ln(n.children,t);}),t}function Oo({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:s,mode:i="iframe",shared:a,events:u}){if(dr(r,e),i==="direct")return to.jsx(on,{slotId:e,githubRepo:o,shared:a,events:u,children:r});let p=Ot(e),{baseUrl:h,apiKey:d,appId:v}=ke(),w=ur.useRef(null),x=ur.useRef(false),f=ur.useRef(null),F=ur.useRef(s);F.current=s;let N=ur.useRef(t);N.current=t;let _=ur.useRef(n);_.current=n,ur.useEffect(()=>{if(typeof process<"u")return;let C=ln(r),P=new Set(s?Object.keys(s):[]),R=[...C].filter(k=>!P.has(k));R.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:
3
+ `+R.map(k=>` - ${k}`).join(`
4
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,s]),ur.useEffect(()=>{an.has(e)||(an.add(e),fetch(`${h}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:v,label:e,propsShape:t?No(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:s?Object.keys(s):[],mode:i||"iframe"})}).catch(()=>{}));},[e,h,d,o,v]);let S=ur.useCallback(C=>{let P=w.current;if(P?.contentWindow&&x.current){let R=F.current?Object.keys(F.current):[];P.contentWindow.postMessage({type:"slot:props",props:C,callbackNames:R},"*"),f.current=null;}else f.current=C;},[]),U=ur.useCallback((C,P)=>{let R=_.current;return !R||R.length===0?false:R.some(k=>{let[$,b]=k.split(" "),c=P.split("?")[0];return C.toUpperCase()===$.toUpperCase()&&c.startsWith(b)})},[]);if(ur.useEffect(()=>{if(!p?.bundleUrl)return;let C=async P=>{if(P.source===w.current?.contentWindow){if(P.data?.type==="slot:ready")x.current=true,w.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:_.current||[]},"*"),_.current,f.current?S(f.current):S(N.current||{});else if(P.data?.type==="slot:event"){let R=P.data.event;R?.navigate&&(window.location.hash=R.navigate);}else if(P.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(P.data.text).catch(R=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,R.message);});else if(P.data?.type==="slot:callback"){let{name:R,args:k}=P.data,$=F.current?.[R];$?($(...k||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${R}`);}else if(P.data?.type==="slot:fetch"){let{id:R,method:k,url:$,body:b}=P.data,c=w.current?.contentWindow;if(!c)return;let T=k||"GET";if(!U(T,$)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${R}: ${T} ${$} \u2014 not in allowedFetches`),c.postMessage({type:"slot:fetch-response",id:R,error:`Fetch not allowed: ${T} ${$}`},"*");return}try{let j={method:T};b&&T!=="GET"&&(j.headers={"Content-Type":"application/json"},j.body=JSON.stringify(b));let H=await fetch($,j),y=await H.json();`${e}${R}${H.status}`,c.postMessage({type:"slot:fetch-response",id:R,data:y,status:H.status},"*");}catch(j){console.error(`[ForkSlot:${e}] fetch #${R} failed:`,j.message),c.postMessage({type:"slot:fetch-response",id:R,error:j.message},"*");}}}};return window.addEventListener("message",C),()=>{window.removeEventListener("message",C),x.current=false;}},[p?.bundleUrl,e,S,U]),ur.useEffect(()=>{p?.bundleUrl&&x.current&&S(t||{});},[t,p?.bundleUrl,S]),!p||p.status!=="complete"||!p.bundleUrl)return `${e}${p?.status||"none"}${p?.bundleUrl||"none"}`,to.jsx(to.Fragment,{children:r});`${e}${p.bundleUrl}`;let L=`${h}${p.bundleUrl.replace("/bundle.js","/host")}`;return to.jsx("iframe",{ref:w,src:L,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Dt({style:e={width:20,height:20},...t}){return to.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[to.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"}),to.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),to.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"}),to.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"}),to.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 Ko=5600,pr=2147483002;function Wo(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Vo(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function gr(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 Xo(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 mr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=ur.useState(false),[s,i]=ur.useState(false),[a,u]=ur.useState(null),[p,h]=ur.useState(null),[d,v]=ur.useState(null),w=ur.useRef(0),x=n?48:40,f=Wo(r),F=!!(f&&r?.state==="complete"&&r.unreadCompletedCount>0),N=F?f:p?.key??null,_=!!(r&&r.state==="running"&&r.runningCount>0),S=!!(N&&N!==a&&(F||p)),U=_||S,L=F?r?.label:p?.label,C=S?"Built":r?.label??"Fork this app",P=S?L:r?.detail,R=gr(r?.label??"Fork this app",r?.detail),k=gr(C,P),$=S?Math.min(420,Math.max(326,k,p?.width??0,w.current+40)):k,b=S?46:40,c=U?[C,P].filter(Boolean).join(" "):Xo(r,t)??"Fork this app",T=U?`${C}:${P??""}`:"idle",j=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!U;ur.useEffect(()=>{if(typeof document>"u")return;let Q=document.createElement("div");return Q.setAttribute("data-fork-button-host","true"),Q.style.position="relative",Q.style.zIndex=String(pr),document.body.appendChild(Q),v(Q),()=>{Q.remove(),v(null);}},[]),ur.useEffect(()=>{_&&(w.current=R);},[R,_]),ur.useEffect(()=>{!F||!f||!r?.label||h(Q=>{if(Q?.key===f)return Q;let le=Math.min(420,Math.max(326,gr("Built",r.label),w.current+40));return {key:f,label:r.label,width:le,startedAt:Date.now()}});},[r?.label,f,F]),ur.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&h(null);},[r?.state,r?.unreadCompletedCount]),ur.useEffect(()=>{if(!N||!S||N===a)return;let Q,le=p?.key===N?p.startedAt:Date.now(),Y=()=>{if(Date.now()-le>=Ko&&!Vo()){u(N);return}Q=window.setTimeout(Y,250);};return Q=window.setTimeout(Y,250),()=>{Q!==void 0&&window.clearTimeout(Q);}},[N,a,p?.key,p?.startedAt,S]);let H=U?{position:"fixed",bottom:24,right:24,zIndex:pr,width:`min(${$}px, calc(100vw - 32px))`,height:b,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:S?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:S?"flex-start":"center",gap:S?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:S?"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:pr,width:x,height:x,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?"#1c4587":"rgba(28, 69, 135, 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"},y={minWidth:0,maxWidth:_?286:S?82:P?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},A={minWidth:0,maxWidth:S?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:S?1:0,color:"#64748b",fontSize:_?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},O={minWidth:0,flex:S?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:S?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},G={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:S?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},D=to.jsxs(to.Fragment,{children:[to.jsx("style",{children:`
5
5
  @keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
6
6
  @keyframes __forkButtonTextSwap {
7
7
  from { opacity: 0; transform: translateY(2px); }
@@ -16,7 +16,7 @@
16
16
  70% { opacity: 1; transform: scale(1.18); }
17
17
  100% { opacity: 1; transform: scale(1); }
18
18
  }
19
- `}),Wn.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:N,title:d,"aria-label":d,children:[O&&r?Wn.jsxs(Wn.Fragment,{children:[A?Wn.jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(37, 99, 235, 0.18)",borderTopColor:"#2563eb",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):Wn.jsx("span",{"aria-hidden":true,style:J}),Wn.jsxs("span",{style:B,children:[Wn.jsx("span",{style:x,children:T}),I&&Wn.jsx("span",{style:y,children:I})]},H)]}):Wn.jsx(Wt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),j&&Wn.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#2563eb",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return f?zn.createPortal(D,f):D}var Wo={status:lucideReact.Loader2,agent_message:lucideReact.MessageSquare,tool_use:lucideReact.Wrench,build_start:lucideReact.Package,build_complete:lucideReact.Check,build_error:lucideReact.AlertCircle,complete:lucideReact.Sparkles,error:lucideReact.AlertCircle},Ko={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Xo={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},Vo={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function kr(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 mn({events:e}){let t=ur.useRef(null);return ur.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Wn.jsxs(Wn.Fragment,{children:[Wn.jsx("style",{children:`
19
+ `}),to.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:H,title:c,"aria-label":c,children:[U&&r?to.jsxs(to.Fragment,{children:[_?to.jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(37, 99, 235, 0.18)",borderTopColor:"#2563eb",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):to.jsx("span",{"aria-hidden":true,style:G}),to.jsxs("span",{style:O,children:[to.jsx("span",{style:y,children:C}),P&&to.jsx("span",{style:A,children:P})]},T)]}):to.jsx(Dt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),j&&to.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#2563eb",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return d?eo.createPortal(D,d):D}var ts={status:lucideReact.Loader2,agent_message:lucideReact.MessageSquare,tool_use:lucideReact.Wrench,build_start:lucideReact.Package,build_complete:lucideReact.Check,build_error:lucideReact.AlertCircle,complete:lucideReact.Sparkles,error:lucideReact.AlertCircle},rs={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},ns={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},os={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function yr(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 mn({events:e}){let t=ur.useRef(null);return ur.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),to.jsxs(to.Fragment,{children:[to.jsx("style",{children:`
20
20
  @keyframes __fork-spin {
21
21
  from { transform: rotate(0deg); }
22
22
  to { transform: rotate(360deg); }
@@ -34,7 +34,7 @@
34
34
  .__fork-stream::-webkit-scrollbar-thumb:hover {
35
35
  background: rgba(255, 255, 255, 0.3);
36
36
  }
37
- `}),Wn.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&&Wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Wn.jsx(lucideReact.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=Wo[r.type]||lucideReact.Code,c=Ko[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");l=Xo[g]||lucideReact.Wrench,c=Vo[g]||"#fbbf24";}return i?l=lucideReact.Loader2:!o&&r.type==="status"&&(l=lucideReact.Check,c="#4ade80"),Wn.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Wn.jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:c,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),Wn.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:kr(r)})]},n)})]})]})}var yn=35,rs="Setting up environment",ns="Built Custom Feature",kn=360,wt=350;function os(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 ss(e){return e.length<=yn?e:e.slice(0,yn-3).trimEnd()+"..."}function is({events:e}){let[t,r]=ur.useState("Setting up environment..."),[n,o]=ur.useState(true),s=ur.useRef(t),i=ur.useRef(false);return ur.useEffect(()=>{if(!i.current){for(let c of e)if(c.type==="status"&&String(c.data.message||"").includes("Agent started")){i.current=true;break}}let l="Setting up environment...";if(i.current)for(let c=e.length-1;c>=0;c--){let g=e[c];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){l=ss(kr(g));break}}if(l!==s.current){o(false);let c=setTimeout(()=>{r(l),s.current=l,o(true);},200);return ()=>clearTimeout(c)}},[e]),Wn.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 as({children:e}){let[t,r]=ur.useState(null);return ur.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?zn.createPortal(e,t):null}function Jt({state:e,fork:t,events:r,error:n,slotId:o,targetId:s,targetLabel:i,historyMode:l="slot",onSubmit:c,onUndo:g,onClose:b,baseUrl:f,apiKey:k,userId:R,userHash:C,appId:F,embedded:_=false,completeVariant:U="bubble"}){let[A,w]=ur.useState(""),[O,$]=ur.useState([]),[T,I]=ur.useState(false),[v,p]=ur.useState(false),[P,h]=ur.useState(false),[d,H]=ur.useState(false),[j,N]=ur.useState(false),[x,y]=ur.useState(false),[B,J]=ur.useState(false),[G,Se]=ur.useState(false),[D,te]=ur.useState(false),[ue,Y]=ur.useState(null),[ne,tt]=ur.useState(false),[_e,Ie]=ur.useState([]),[me,Me]=ur.useState(null),[Ke,rt]=ur.useState(false),[$e,Te]=ur.useState(false),[Xe,Ct]=ur.useState(false),[Zt,Et]=ur.useState(null),[ae,Ve]=ur.useState(null),[Ce,fe]=ur.useState(false),[nt,xe]=ur.useState(false),[He,Le]=ur.useState(""),lt=ur.useRef(null),[$t,Ne]=ur.useState(null),[m,u]=ur.useState(false),[M,Z]=ur.useState(null),[W,z]=ur.useState([]),[K,re]=ur.useState(null),[pe,oe]=ur.useState(false),se=ur.useRef(false),le=ur.useRef(null),ce=ur.useRef(null),{resetAllForks:Fe,previewSession:X,currentContainerId:we}=ye(),ke=X?.container_id??we,ve=!!(X&&m),ge=M!==null,Pt=ur.useRef(b);ur.useEffect(()=>{Pt.current=b;});let ct=ur.useRef(null),It=ur.useRef(false),Pr=typeof window<"u"&&"documentPictureInPicture"in window,Hn=async()=>{if(!(!Pr||ge))try{let a=await window.documentPictureInPicture.requestWindow({width:kn,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 S=document.adoptedStyleSheets??[];S.length>0&&(a.document.adoptedStyleSheets=[...S]);}catch{}a.addEventListener("pagehide",()=>{ct.current=null,Z(null),It.current||Pt.current(),It.current=!1;},{once:!0}),ct.current=a,Z(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},Ln=()=>{M&&(It.current=true,M.close());};ur.useEffect(()=>()=>{It.current=true,ct.current?.close();},[]);let ot=s??o??"",Nn=(i||ot).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),Mt=ur.useRef(""),Ir=()=>{let a={Authorization:`Bearer ${k}`,...ee()};return F&&(a["X-Fork-App-Id"]=F),!X&&R&&(a["X-Fork-User-Id"]=R),!X&&C&&(a["X-Fork-User-Hash"]=C),a},st=_?true:v&&!P,Bn=r.find(a=>{let S=a.data;return a.type==="status"&&S.summary})?.data?.summary||t?.summary||rs,Je=r.find(a=>{let S=a.data;return (a.type==="status"||a.type==="complete")&&typeof S?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;ur.useEffect(()=>{if(l==="none"){I(true);return}if(!f||!k)return;if(!K){$([]),I(true);return}let a=new AbortController;return fetch(`${f}/api/v1/forks/${encodeURIComponent(K)}/messages`,{headers:Ir(),signal:a.signal}).then(S=>S.ok?S.json():[]).then(S=>{if(a.signal.aborted)return;let L=[];for(let de of S){let Be=de.forkId??K;de.role==="user"?L.push({type:"user",text:de.content,forkId:Be}):L.push({type:"applied",text:de.content,forkId:Be});}$(L),I(true);}).catch(()=>{a.signal.aborted||I(true);}),()=>{a.abort();}},[k,F,f,l,K,X?.fork_id,X?.preview_session_id,C,R,t?.id,t?.completedAt]),ur.useEffect(()=>{if(l==="none"||!f||!k||!Ke)return;if(!me){z([]);return}let a=new AbortController,S=new URLSearchParams({container_id:me});return fetch(`${f}/api/v1/forks?${S.toString()}`,{headers:Ir(),signal:a.signal}).then(L=>L.ok?L.json():{forks:[]}).then(L=>{a.signal.aborted||z(L.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[k,F,f,l,me,Ke,t?.id,t?.completedAt,X?.fork_id,X?.preview_session_id,C,R]),ur.useEffect(()=>{e==="complete"&&Se(false);},[e]);let Mr=W.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");ur.useEffect(()=>{if(!Mr||!f||!k||!me)return;let a=new URLSearchParams({container_id:me}),S={Authorization:`Bearer ${k}`,...ee()};F&&(S["X-Fork-App-Id"]=F);let de=setInterval(async()=>{try{let Be=await fetch(`${f}/api/v1/forks?${a.toString()}`,{headers:S});if(!Be.ok)return;let Dn=await Be.json();z(Dn.forks??[]);}catch{}},3e3);return ()=>clearInterval(de)},[Mr,f,k,F,me]),ur.useEffect(()=>{if(_&&l==="none"){Ie([]),Me(null),rt(true),u(false);return}if(X){let a=false;return rt(false),u(false),Ne(null),fetch(`${f}/api/v1/preview/${encodeURIComponent(X.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${k}`,...ee()}}).then(S=>{if(!S.ok)throw new Error(`${S.status}`);return S.json()}).then(S=>{a||(Ie(S.containers),Me(S.currentContainerId??X.container_id??null),u(true));}).catch(S=>{a||(u(false),Ne(S instanceof Error?S.message:String(S)),ke?(Ie([{id:ke,name:X.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),Me(ke)):(Ie([]),Me(null)));}).finally(()=>{a||rt(true);}),()=>{a=true;}}ke?(Ie([{id:ke,name:"Primary container",createdAt:""}]),Me(ke)):(Ie([]),Me(null)),rt(true),u(false);},[k,ke,f,_,l,X?.container_id,X?.container_name,X?.preview_session_id]);let Tt=ur.useRef(void 0);ur.useEffect(()=>{if(Ke){if(Tt.current===void 0){Tt.current=me;return}Tt.current!==me&&(Tt.current=me,$([]),I(false));}},[me,Ke]);let Ht=ur.useRef(null);ur.useEffect(()=>{if(!$e)return;let a=L=>{if(!Ht.current)return;let de=typeof L.composedPath=="function"?L.composedPath():[];Ht.current.contains(L.target)||de.includes(Ht.current)||Te(false);},S=L=>{L.key==="Escape"&&Te(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",S,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",S,true);}},[$e]),ur.useEffect(()=>{if(_||!st||P||ge)return;let a=S=>{(typeof S.composedPath=="function"?S.composedPath():[]).some(Be=>Be instanceof Element&&Be.hasAttribute("data-fork-panel-host"))||(h(true),p(false),setTimeout(()=>b(),wt));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[_,st,P,ge,b]),ur.useEffect(()=>{$e||(xe(false),Le(""));},[$e]),ur.useEffect(()=>{nt&&(lt.current?.focus(),lt.current?.select());},[nt]),ur.useEffect(()=>{if(_)return;let a=requestAnimationFrame(()=>p(true));return ()=>cancelAnimationFrame(a)},[_]),ur.useEffect(()=>{let a=_||ge;if((a||st)&&(e==="prompting"||e==="complete")){let S=setTimeout(()=>le.current?.focus(),a?100:wt+100);return ()=>clearTimeout(S)}},[st,_,ge,e]),ur.useEffect(()=>{if(e==="complete"&&Mt.current){let S=r.find(L=>L.type==="complete")?.data?.summary||t?.summary||ns;$(L=>L[L.length-1]?.type==="applied"?L:[...L,{type:"applied",text:S}]),w(""),setTimeout(()=>le.current?.focus(),200);}},[e,Nn,r,t?.summary]),ur.useEffect(()=>{ce.current&&(ce.current.scrollTop=ce.current.scrollHeight);},[O,e]);let Tr=()=>{if(A.trim()){Mt.current=A.trim();let a={},S=pe||!K;S?(a.forceNew=true,se.current=true,pe||oe(true)):a.forkId=K,S||$(L=>[...L,{type:"user",text:A.trim(),forkId:K}]),c(A.trim(),ot,me,a),w("");}};ur.useEffect(()=>{if(se.current){if(e==="error"){se.current=false;return}t?.id&&(re(t.id),oe(false),se.current=false);}},[t?.id,e]),ur.useEffect(()=>{t?.id&&(se.current||e!=="running"&&e!=="complete"||(re(a=>a??t.id),oe(false)));},[t?.id,e]);let Hr=a=>{Ge(a.session.containerId,a.session.containerName),Me(a.session.containerId),Ie(S=>{let L=S.filter(de=>de.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...L.map(de=>({...de,isPrimary:false}))]}),re(null),oe(false),se.current=false,$([]),I(false),Mt.current="";},On=async a=>{if(!(!X||!ve||ae)){Ve(a),Ne(null);try{let S=await fetch(`${f}/api/v1/preview/${encodeURIComponent(X.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${k}`,...ee()}});if(!S.ok){let L=await S.json().catch(()=>({}));throw new Error(L.error||`API error: ${S.status}`)}Hr(await S.json()),Te(!1);}catch(S){Ne(S instanceof Error?S.message:String(S));}finally{Ve(null);}}},Lr=async a=>{if(!X||!ve||ae)return;let S=a.trim();if(S){Ve("__new__"),Ne(null);try{let L=await fetch(`${f}/api/v1/preview/${encodeURIComponent(X.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${k}`,...ee()},body:JSON.stringify({name:S})});if(!L.ok){let de=await L.json().catch(()=>({}));throw new Error(de.error||`API error: ${L.status}`)}Hr(await L.json()),xe(!1),Le(""),Te(!1);}catch(L){Ne(L instanceof Error?L.message:String(L));}finally{Ve(null);}}},Nr=async()=>{if(!(!g||D||!ot)){te(true);try{let a=await g(ot);$(S=>{let L=[...S];return L.length>=2&&L[L.length-1]?.type==="applied"?L.splice(-2,2):L.length>=1&&L[L.length-1]?.type==="applied"&&L.splice(-1,1),L}),a?.removed&&$([]);}catch{}finally{te(false);}}},Br=()=>{if(_){b();return}if(ge){M?.close();return}h(true),p(false),setTimeout(()=>b(),wt);},Un=_||ge?{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:kn,maxWidth:"100vw",background:"#ffffff",boxShadow:st?"-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:st?"translateX(0)":"translateX(100%)",transition:`transform ${wt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${wt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Or=_e.find(a=>a.id===me)?.name??(Ke?"Fork":"Loading..."),dt=pe?[]:K?O.filter(a=>a.forkId===K||a.forkId==null):O,Qt=Wn.jsxs(Wn.Fragment,{children:[Wn.jsx("style",{children:`
37
+ `}),to.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&&to.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[to.jsx(lucideReact.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"),a=ts[r.type]||lucideReact.Code,u=rs[r.type]||"#9ca3af";if(r.type==="tool_use"){let p=String(r.data.category||"");a=ns[p]||lucideReact.Wrench,u=os[p]||"#fbbf24";}return i?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,u="#4ade80"),to.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[to.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:u,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),to.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:yr(r)})]},n)})]})]})}var kn=35,ps="Setting up environment",gs="Built Custom Feature",bn=360,bt=380;function ms(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 hs(e){return e.length<=kn?e:e.slice(0,kn-3).trimEnd()+"..."}function ys({events:e}){let[t,r]=ur.useState("Setting up environment..."),[n,o]=ur.useState(true),s=ur.useRef(t),i=ur.useRef(false);return ur.useEffect(()=>{if(!i.current){for(let u of e)if(u.type==="status"&&String(u.data.message||"").includes("Agent started")){i.current=true;break}}let a="Setting up environment...";if(i.current)for(let u=e.length-1;u>=0;u--){let p=e[u];if(p.type==="tool_use"||p.type==="build_start"||p.type==="build_complete"){a=hs(yr(p));break}}if(a!==s.current){o(false);let u=setTimeout(()=>{r(a),s.current=a,o(true);},200);return ()=>clearTimeout(u)}},[e]),to.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 ks({children:e}){let[t,r]=ur.useState(null);return ur.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?eo.createPortal(e,t):null}function Wt({state:e,fork:t,events:r,error:n,slotId:o,targetId:s,targetLabel:i,historyMode:a="slot",onSubmit:u,onUndo:p,onClose:h,baseUrl:d,apiKey:v,userId:w,userHash:x,appId:f,embedded:F=false,completeVariant:N="bubble"}){let[_,S]=ur.useState(""),[U,L]=ur.useState([]),[C,P]=ur.useState(false),[R,k]=ur.useState(false),[$,b]=ur.useState(false),[c,T]=ur.useState(false),[j,H]=ur.useState(false),[y,A]=ur.useState(false),[O,G]=ur.useState(false),[z,pe]=ur.useState(false),[D,Q]=ur.useState(false),[le,Y]=ur.useState(null),[ie,et]=ur.useState(false),[Fe,Re]=ur.useState([]),[me,$e]=ur.useState(null),[Ue,Ce]=ur.useState(false),[Ee,De]=ur.useState(false),[Gt,Ct]=ur.useState(false),[at,ve]=ur.useState(null),[W,je]=ur.useState(null),[Pe,Et]=ur.useState(false),[ze,tt]=ur.useState(false),[Ie,Ke]=ur.useState(""),g=ur.useRef(null),[m,M]=ur.useState(null),[ee,X]=ur.useState(false),[K,oe]=ur.useState(null),[ae,be]=ur.useState([]),[J,ce]=ur.useState(null),[re,se]=ur.useState(false),ge=ur.useRef(false),de=ur.useRef(null),he=ur.useRef(null),{resetAllForks:He,previewSession:Z,currentContainerId:lt}=ke(),Te=Z?.container_id??lt,rt=!!(Z&&ee),Ae=K!==null,Tr=ur.useRef(h);ur.useEffect(()=>{Tr.current=h;});let Yt=ur.useRef(null),Rt=ur.useRef(false),Mr=typeof window<"u"&&"documentPictureInPicture"in window,Vn=async()=>{if(!(!Mr||Ae))try{let l=await window.documentPictureInPicture.requestWindow({width:bn,height:640});l.document.body.style.margin="0",l.document.body.style.padding="0",l.document.body.style.height="100vh",l.document.body.style.overflow="hidden",l.document.body.style.background="#ffffff";try{let E=document.adoptedStyleSheets??[];E.length>0&&(l.document.adoptedStyleSheets=[...E]);}catch{}l.addEventListener("pagehide",()=>{Yt.current=null,oe(null),Rt.current||Tr.current(),Rt.current=!1;},{once:!0}),Yt.current=l,oe(l);}catch(l){console.warn("[Fork] PiP open failed:",l);}},Xn=()=>{K&&(Rt.current=true,K.close());};ur.useEffect(()=>()=>{Rt.current=true,Yt.current?.close();},[]);let nt=s??o??"",Jn=(i||nt).replace(/[-_]+/g," ").replace(/\b\w/g,l=>l.toUpperCase()),$t=ur.useRef(""),Lr=()=>{let l={Authorization:`Bearer ${v}`,...ne()};return f&&(l["X-Fork-App-Id"]=f),!Z&&w&&(l["X-Fork-User-Id"]=w),!Z&&x&&(l["X-Fork-User-Hash"]=x),l},ot=F?true:R&&!$,qn=r.find(l=>{let E=l.data;return l.type==="status"&&E.summary})?.data?.summary||t?.summary||ps,We=r.find(l=>{let E=l.data;return (l.type==="status"||l.type==="complete")&&typeof E?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;ur.useEffect(()=>{if(a==="none"){P(true);return}if(!d||!v)return;if(!J){L([]),P(true);return}let l=new AbortController;return fetch(`${d}/api/v1/forks/${encodeURIComponent(J)}/messages`,{headers:Lr(),signal:l.signal}).then(E=>E.ok?E.json():[]).then(E=>{if(l.signal.aborted)return;let B=[];for(let fe of E){let Me=fe.forkId??J;fe.role==="user"?B.push({type:"user",text:fe.content,forkId:Me}):B.push({type:"applied",text:fe.content,forkId:Me});}L(B),P(true);}).catch(()=>{l.signal.aborted||P(true);}),()=>{l.abort();}},[v,f,d,a,J,Z?.fork_id,Z?.preview_session_id,x,w,t?.id,t?.completedAt]),ur.useEffect(()=>{if(a==="none"||!d||!v||!Ue)return;if(!me){be([]);return}let l=new AbortController,E=new URLSearchParams({container_id:me});return fetch(`${d}/api/v1/forks?${E.toString()}`,{headers:Lr(),signal:l.signal}).then(B=>B.ok?B.json():{forks:[]}).then(B=>{l.signal.aborted||be(B.forks??[]);}).catch(()=>{}),()=>{l.abort();}},[v,f,d,a,me,Ue,t?.id,t?.completedAt,Z?.fork_id,Z?.preview_session_id,x,w]),ur.useEffect(()=>{e==="complete"&&pe(false);},[e]);let Hr=ae.some(l=>l.status==="pending"||l.status==="running"||l.status==="building");ur.useEffect(()=>{if(!Hr||!d||!v||!me)return;let l=new URLSearchParams({container_id:me}),E={Authorization:`Bearer ${v}`,...ne()};f&&(E["X-Fork-App-Id"]=f);let fe=setInterval(async()=>{try{let Me=await fetch(`${d}/api/v1/forks?${l.toString()}`,{headers:E});if(!Me.ok)return;let Zn=await Me.json();be(Zn.forks??[]);}catch{}},3e3);return ()=>clearInterval(fe)},[Hr,d,v,f,me]),ur.useEffect(()=>{if(F&&a==="none"){Re([]),$e(null),Ce(true),X(false);return}if(Z){let l=false;return Ce(false),X(false),M(null),fetch(`${d}/api/v1/preview/${encodeURIComponent(Z.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${v}`,...ne()}}).then(E=>{if(!E.ok)throw new Error(`${E.status}`);return E.json()}).then(E=>{l||(Re(E.containers),$e(E.currentContainerId??Z.container_id??null),X(true));}).catch(E=>{l||(X(false),M(E instanceof Error?E.message:String(E)),Te?(Re([{id:Te,name:Z.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),$e(Te)):(Re([]),$e(null)));}).finally(()=>{l||Ce(true);}),()=>{l=true;}}Te?(Re([{id:Te,name:"Primary container",createdAt:""}]),$e(Te)):(Re([]),$e(null)),Ce(true),X(false);},[v,Te,d,F,a,Z?.container_id,Z?.container_name,Z?.preview_session_id]);let Pt=ur.useRef(void 0);ur.useEffect(()=>{if(Ue){if(Pt.current===void 0){Pt.current=me;return}Pt.current!==me&&(Pt.current=me,L([]),P(false));}},[me,Ue]);let It=ur.useRef(null);ur.useEffect(()=>{if(!Ee)return;let l=B=>{if(!It.current)return;let fe=typeof B.composedPath=="function"?B.composedPath():[];It.current.contains(B.target)||fe.includes(It.current)||De(false);},E=B=>{B.key==="Escape"&&De(false);};return document.addEventListener("mousedown",l,true),document.addEventListener("keydown",E,true),()=>{document.removeEventListener("mousedown",l,true),document.removeEventListener("keydown",E,true);}},[Ee]),ur.useEffect(()=>{if(F||!ot||$||Ae)return;let l=E=>{(typeof E.composedPath=="function"?E.composedPath():[]).some(Me=>Me instanceof Element&&Me.hasAttribute("data-fork-panel-host"))||(b(true),k(false),setTimeout(()=>h(),bt));};return document.addEventListener("mousedown",l,true),()=>{document.removeEventListener("mousedown",l,true);}},[F,ot,$,Ae,h]),ur.useEffect(()=>{Ee||(tt(false),Ke(""));},[Ee]),ur.useEffect(()=>{ze&&(g.current?.focus(),g.current?.select());},[ze]),ur.useEffect(()=>{if(F)return;let l=requestAnimationFrame(()=>k(true));return ()=>cancelAnimationFrame(l)},[F]),ur.useEffect(()=>{let l=F||Ae;if((l||ot)&&(e==="prompting"||e==="complete")){let E=setTimeout(()=>de.current?.focus(),l?100:bt+100);return ()=>clearTimeout(E)}},[ot,F,Ae,e]),ur.useEffect(()=>{if(e==="complete"&&$t.current){let E=r.find(B=>B.type==="complete")?.data?.summary||t?.summary||gs;L(B=>B[B.length-1]?.type==="applied"?B:[...B,{type:"applied",text:E}]),S(""),setTimeout(()=>de.current?.focus(),200);}},[e,Jn,r,t?.summary]),ur.useEffect(()=>{he.current&&(he.current.scrollTop=he.current.scrollHeight);},[U,e]);let Br=()=>{if(_.trim()){$t.current=_.trim();let l={},E=re||!J;E?(l.forceNew=true,ge.current=true,re||se(true)):l.forkId=J,E||L(B=>[...B,{type:"user",text:_.trim(),forkId:J}]),u(_.trim(),nt,me,l),S("");}};ur.useEffect(()=>{if(ge.current){if(e==="error"){ge.current=false;return}t?.id&&(ce(t.id),se(false),ge.current=false);}},[t?.id,e]),ur.useEffect(()=>{t?.id&&(ge.current||e!=="running"&&e!=="complete"||(ce(l=>l??t.id),se(false)));},[t?.id,e]);let Nr=l=>{Xe(l.session.containerId,l.session.containerName),$e(l.session.containerId),Re(E=>{let B=E.filter(fe=>fe.id!==l.container.id);return [{...l.container,isPrimary:true,hasAccess:true},...B.map(fe=>({...fe,isPrimary:false}))]}),ce(null),se(false),ge.current=false,L([]),P(false),$t.current="";},Gn=async l=>{if(!(!Z||!rt||W)){je(l),M(null);try{let E=await fetch(`${d}/api/v1/preview/${encodeURIComponent(Z.preview_session_id)}/containers/${encodeURIComponent(l)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${v}`,...ne()}});if(!E.ok){let B=await E.json().catch(()=>({}));throw new Error(B.error||`API error: ${E.status}`)}Nr(await E.json()),De(!1);}catch(E){M(E instanceof Error?E.message:String(E));}finally{je(null);}}},Or=async l=>{if(!Z||!rt||W)return;let E=l.trim();if(E){je("__new__"),M(null);try{let B=await fetch(`${d}/api/v1/preview/${encodeURIComponent(Z.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,...ne()},body:JSON.stringify({name:E})});if(!B.ok){let fe=await B.json().catch(()=>({}));throw new Error(fe.error||`API error: ${B.status}`)}Nr(await B.json()),tt(!1),Ke(""),De(!1);}catch(B){M(B instanceof Error?B.message:String(B));}finally{je(null);}}},Ur=async()=>{if(!(!p||D||!nt)){Q(true);try{let l=await p(nt);L(E=>{let B=[...E];return B.length>=2&&B[B.length-1]?.type==="applied"?B.splice(-2,2):B.length>=1&&B[B.length-1]?.type==="applied"&&B.splice(-1,1),B}),l?.removed&&L([]);}catch{}finally{Q(false);}}},Dr=()=>{if(F){h();return}if(Ae){K?.close();return}b(true),k(false),setTimeout(()=>h(),bt);},Yn=F||Ae?{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:bn,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-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:ot?"translateX(0)":"translateX(100%)",transition:`transform ${bt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${bt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},jr=Fe.find(l=>l.id===me)?.name??(Ue?"Fork":"Loading..."),ct=re?[]:J?U.filter(l=>l.forkId===J||l.forkId==null):U,Zt=to.jsxs(to.Fragment,{children:[to.jsx("style",{children:`
38
38
  @keyframes __fork-pulse {
39
39
  0%, 100% { opacity: 1; }
40
40
  50% { opacity: 0.5; }
@@ -56,5 +56,9 @@
56
56
  scrollbar-width: thin;
57
57
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
58
58
  }
59
- `}),Wn.jsxs("div",{className:"__fork-panel",style:Un,children:[Wn.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:[Wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Wn.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!ne&&confirm("Kill all forks in this container?")){tt(true);try{let S=await Fe();`${S?.deleted??0}`,z([]),re(null),oe(!1),w("");}catch(S){console.error("[Fork] Reset failed:",S);}finally{tt(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:Wn.jsx(Wt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?Wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Bn}):_e.length===0&&!ve?Wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):ve?Wn.jsxs("div",{ref:Ht,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Wn.jsxs("button",{type:"button",onClick:()=>{Te(a=>!a);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(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:Xe||$e?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Wn.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Or}),Wn.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:$e?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),$e&&Wn.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:[_e.map(a=>{let S=a.id===me,L=Zt===a.id,de=ae===a.id;return Wn.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Et(a.id),onMouseLeave:()=>Et(null),onClick:()=>{a.id!==me&&On(a.id);},disabled:!!ae,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:L?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ae?"default":"pointer",textAlign:"left",fontWeight:S?600:400,opacity:ae&&!de?.55:1},children:[Wn.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:S&&Wn.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Wn.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:de?"Switching...":a.name})]},a.id)}),Wn.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),nt?Wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[Wn.jsx("input",{ref:lt,type:"text",value:He,placeholder:"Container name",disabled:ae==="__new__",onChange:a=>Le(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Lr(He)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),xe(false),Le(""));},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="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),Wn.jsx("button",{type:"button",onClick:()=>{Lr(He);},disabled:!He.trim()||ae==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!He.trim()||ae==="__new__"?"#e5e7eb":"#1c4587",color:!He.trim()||ae==="__new__"?"#9ca3af":"#ffffff",cursor:!He.trim()||ae==="__new__"?"default":"pointer",flexShrink:0},children:ae==="__new__"?Wn.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):Wn.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):Wn.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>fe(true),onMouseLeave:()=>fe(false),onClick:()=>{ae||(Ne(null),Le(""),xe(true));},disabled:!!ae,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Ce?"#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"}),$t&&Wn.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:$t})]})]}):Wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Or}),e==="running"&&Wn.jsx("span",{title:Je?`Estimated ~${Je} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Je?"#1c4587":"#9ca3af",backgroundColor:Je?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Je?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Je?`~${Je}m`:"~ m"})]}),!_&&Wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Pr&&Wn.jsx("button",{onClick:ge?Ln:Hn,onMouseEnter:()=>N(true),onMouseLeave:()=>N(false),title:ge?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:j?"#4b5563":"#9ca3af",backgroundColor:j?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ge?Wn.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Wn.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Wn.jsx("button",{onClick:Br,onMouseEnter:()=>H(true),onMouseLeave:()=>H(false),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:Wn.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),Wn.jsxs("div",{ref:ce,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(K||pe)&&Wn.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[Wn.jsx("button",{onClick:()=>{re(null),oe(false),se.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 S=(K?W.find(L=>L.id===K)?.targetId:null)??ot;return S?Wn.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 ${S}`,children:["Forking ",Wn.jsx("span",{style:{color:"#6b7280"},children:S})]}):null})()]}),!K&&!pe&&Wn.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[Wn.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:Wn.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),W.length===0&&Wn.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),W.length>0&&Wn.jsx("div",{style:{display:"flex",flexDirection:"column"},children:W.map(a=>{let S=a.summary||"Untitled fork";return Wn.jsxs("button",{onClick:()=>{oe(false),re(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:L=>L.currentTarget.style.background="#fafafa",onMouseLeave:L=>L.currentTarget.style.background="#ffffff",children:[Wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[Wn.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:S}),Wn.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:os(a.updatedAt)})]}),Wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[Wn.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),Wn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),Wn.jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?Wn.jsxs(Wn.Fragment,{children:[Wn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),Wn.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),K&&dt.length>0&&Wn.jsx("div",{style:{padding:"16px 16px 0 16px"},children:dt.map((a,S)=>Wn.jsx("div",{style:{marginBottom:S<dt.length-1?10:0},children:a.type==="user"?Wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Wn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Wn.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Wn.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})]}):U==="item"&&S===dt.length-1?Wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[Wn.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:Wn.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),Wn.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[Wn.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),Wn.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),g&&e!=="running"&&Wn.jsx("button",{onClick:L=>{L.stopPropagation(),Nr();},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"})]}):Wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Wn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Wn.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Wn.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:[Wn.jsx("span",{style:{flex:1},children:a.text}),g&&S===dt.length-1&&e!=="running"&&Wn.jsxs("button",{onClick:L=>{L.stopPropagation(),Nr();},onMouseEnter:()=>Y(S),onMouseLeave:()=>Y(null),disabled:D,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===S?"rgba(0,0,0,0.06)":"transparent",color:ue===S?"#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:[Wn.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ue===S&&Wn.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"})]})]})]})},S))}),e==="running"&&(K||pe)&&Wn.jsx("div",{style:{padding:16},children:Wn.jsxs("div",{onClick:()=>Se(!G),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Wn.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:Wn.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Wn.jsx(is,{events:r})]}),Wn.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:G?"rotate(180deg)":"rotate(0deg)"},children:Wn.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Wn.jsx("div",{style:{maxHeight:G?320:0,opacity:G?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Wn.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Wn.jsx(mn,{events:r})})})]})}),e==="error"&&(K||pe)&&Wn.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Wn.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Wn.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Wn.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),Wn.jsxs("button",{onClick:()=>{let a=t?.prompt||Mt.current;a&&c(a,ot);},onMouseEnter:()=>J(true),onMouseLeave:()=>J(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:B?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Wn.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Wn.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Wn.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:[Wn.jsx("textarea",{ref:le,value:A,onChange:a=>{w(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(),Tr()),a.key==="Escape"&&!_&&Br();},placeholder:K?"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"}}),Wn.jsx("button",{onClick:Tr,disabled:!A.trim(),onMouseEnter:()=>y(true),onMouseLeave:()=>y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:A.trim()?1:.25,transform:x&&A.trim()?"scale(1.1)":"scale(1)",background:A.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:A.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Wn.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return _?Qt:ge&&M?zn.createPortal(Qt,M.document.body):Wn.jsx(as,{children:Qt})}function vn(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 wr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:l,queueBoundaryAnimation:c,trackForkActivity:g,recordForkActivityEvent:b}=ye(),[f,k]=ur.useState("idle"),[R,C]=ur.useState(null),[F,_]=ur.useState([]),[U,A]=ur.useState(null),w=ur.useRef(null),O=ur.useCallback(()=>{k("prompting"),_([]),A(null),C(null);},[]),$=ur.useCallback(()=>{k("idle"),w.current&&(w.current.close(),w.current=null);},[]);ur.useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&k(p=>p==="idle"?"prompting":p);},[i?.preview_session_id,i?.target.id,e]);let T=ur.useCallback(async(p,P,h)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");k("running"),_([]),A(null),C(null);let d;if(i){let N=h?.forkId??i.fork_id??void 0,x=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ee()},body:JSON.stringify({prompt:p,...e?{boundary_id:e}:{},...N&&!h?.forceNew?{fork_id:N}:{},...h?.forceNew?{force_new:!0}:{}})});if(!x.ok){let J=await x.json().catch(()=>({}));throw new Error(J.error||`API error: ${x.status}`)}let y=await x.json();y.container_id&&Ge(y.container_id,y.container_name),ut(y.fork_id),d=await(await fetch(`${o}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...ee()}})).json();}else if(h?.forkId){let N={prompt:p};r&&(N.userId=r),n&&(N.userHash=n);let x=await fetch(`${o}/api/v1/forks/${encodeURIComponent(h.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(N)});if(!x.ok){let y=await x.json().catch(()=>({}));throw new Error(y.error||`API error: ${x.status}`)}d=await x.json();}else {let N={userId:r,prompt:p,boundaryId:e,appId:s};P&&(N.containerId=P),n&&(N.userHash=n),h?.forceNew&&(N.force_new=!0);let x=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(N)});if(!x.ok){let y=await x.json().catch(()=>({}));throw new Error(y.error||`API error: ${x.status}`)}d=await x.json();}C(d),g(d,{targetKind:"module",targetId:e});let H=new URLSearchParams({key:t});i?(H.set("previewSessionId",i.preview_session_id),H.set("previewForkId",d.id)):r&&H.set("userId",r),n&&H.set("userHash",n);let j=new EventSource(`${o}/api/v1/forks/${d.id}/events?${H.toString()}`);w.current=j,j.onmessage=N=>{try{let x=JSON.parse(N.data);if(b(d.id,x),_(y=>[...y,x]),x.type==="complete"){let y=x.data;c(e,d.id),l().catch(()=>{}).finally(()=>{let B={...d,status:"complete",moduleUrl:y.moduleUrl,cssUrls:y.cssUrls,summary:y.summary,completedAt:new Date().toISOString()};C(B),k("complete"),j.close();});}else if(x.type==="error"){let y=x.data;A(y.error||"Unknown error"),k("error"),j.close();}}catch{}},j.onerror=()=>{let N={Authorization:`Bearer ${t}`,...ee()};!i&&r&&(N["X-Fork-User-Id"]=r),!i&&n&&(N["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${d.id}`,{headers:N}).then(x=>x.json()).then(x=>{C(x),x.status==="complete"?(c(e,x.id),l().catch(()=>{}),k("complete")):x.status==="error"&&(A(x.error||"Fork generation failed"),k("error"));}).catch(()=>{A("Connection lost"),k("error");}),j.close();};}catch(d){A(d.message),k("error");}},[t,s,o,e,i,c,l,b,g,n,r]),I=ur.useCallback(async p=>{try{let P={Authorization:`Bearer ${t}`,...ee()};!i&&r&&(P["X-Fork-User-Id"]=r),!i&&n&&(P["X-Fork-User-Hash"]=n);let h=await fetch(`${o}/api/v1/forks/${p}`,{headers:P});if(!h.ok)return;let d=await h.json(),H=d.boundaryId??e;if(g(d,{targetKind:"module",targetId:H}),d.status==="complete"){k("complete"),C(d),A(null),_([]);return}if(d.status==="error"){k("error"),C(d),A(d.error||"Fork generation failed"),_([]);return}if(d.status!=="pending"&&d.status!=="running"&&d.status!=="building")return;k("running"),C(d),A(null),_([]);let j=new URLSearchParams({key:t});i?(j.set("previewSessionId",i.preview_session_id),j.set("previewForkId",d.id)):r&&j.set("userId",r),n&&j.set("userHash",n);let N=new EventSource(`${o}/api/v1/forks/${d.id}/events?${j.toString()}`);w.current&&w.current.close(),w.current=N,N.onmessage=x=>{try{let y=JSON.parse(x.data);if(b(d.id,y),_(B=>[...B,y]),y.type==="complete"){let B=y.data;c(e,d.id),l().catch(()=>{}).finally(()=>{let J={...d,status:"complete",moduleUrl:B.moduleUrl,cssUrls:B.cssUrls,summary:B.summary,completedAt:new Date().toISOString()};C(J),k("complete"),N.close();});}else if(y.type==="error"){let B=y.data;A(B.error||"Unknown error"),k("error"),N.close();}}catch{}},N.onerror=()=>{N.close();};}catch{}},[t,o,e,i,c,b,l,g,n,r]),v=ur.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let p={userId:r,boundaryId:e,appId:s};n&&(p.userHash=n);let P=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(p)});if(!P.ok){let d=await P.json().catch(()=>({}));throw new Error(d.error||`API error: ${P.status}`)}let h=await P.json();return await l().catch(()=>{}),h.removed?(C(null),k("prompting")):h.fork&&(C(h.fork),k("complete")),h}catch(p){throw A(p.message),p}},[t,s,o,e,l,n,r]);return {state:f,fork:R,events:F,error:U,open:O,close:$,startFork:T,undoFork:v,adoptRunningFork:I}}function Sn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:l,undoFork:c,adoptRunningFork:g}=wr(e),[b,f]=ur.useState(false),k=ur.useCallback(()=>{f(true),s();},[s]),R=ur.useCallback(()=>{f(false),i();},[i]),C=ur.useCallback(async F=>{f(true),await g(F);},[g]);return {state:t,fork:r,events:n,error:o,isOpen:b,open:k,close:R,submit:l,undo:c,adoptRunningFork:C}}function Sr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:l,trackForkActivity:c,recordForkActivityEvent:g}=ye(),[b,f]=ur.useState("idle"),[k,R]=ur.useState(null),[C,F]=ur.useState([]),[_,U]=ur.useState(null),A=ur.useRef(null),w=ur.useCallback(()=>{f("prompting"),F([]),U(null),R(null);},[]),O=ur.useCallback(()=>{f("idle"),A.current&&(A.current.close(),A.current=null);},[]);ur.useEffect(()=>{o&&o.target.kind==="slot"&&f(v=>v==="idle"?"prompting":v);},[o?.preview_session_id,o?.target.kind]);let $=ur.useCallback(async(v,p,P,h)=>{try{f("running"),F([]),U(null),R(null);let d;if(o){let x=h?.forkId??o.fork_id??void 0,y=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ee()},body:JSON.stringify({prompt:v,...p?{slot_id:p}:{},...x&&!h?.forceNew?{fork_id:x}:{},...h?.forceNew?{force_new:!0}:{}})});if(!y.ok){let G=await y.json().catch(()=>({}));throw new Error(G.error||`API error: ${y.status}`)}let B=await y.json();B.container_id&&Ge(B.container_id,B.container_name),ut(B.fork_id),d=await(await fetch(`${n}/api/v1/forks/${B.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...ee()}})).json();}else if(h?.forkId){let x={prompt:v};t&&(x.userId=t),r&&(x.userHash=r);let y=await fetch(`${n}/api/v1/forks/${encodeURIComponent(h.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!y.ok){let B=await y.json().catch(()=>({}));throw new Error(B.error||`API error: ${y.status}`)}d=await y.json();}else {let x={userId:t,prompt:v};p&&(x.slotId=p),P&&(x.containerId=P),r&&(x.userHash=r),h?.forceNew&&(x.force_new=!0);let y=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!y.ok){let B=await y.json().catch(()=>({}));throw new Error(B.error||`API error: ${y.status}`)}d=await y.json();}R(d);let H=p??d.slotId;H&&c(d,{targetKind:"slot",targetId:H});let j=new URLSearchParams({key:e});o?(j.set("previewSessionId",o.preview_session_id),j.set("previewForkId",d.id)):t&&j.set("userId",t),r&&j.set("userHash",r);let N=new EventSource(`${n}/api/v1/forks/${d.id}/events?${j.toString()}`);A.current=N,N.onmessage=x=>{try{let y=JSON.parse(x.data);if(g(d.id,y),F(B=>[...B,y]),y.type==="complete"){let B=y.data,J={...d,status:"complete",bundleUrl:B.bundleUrl,summary:B.summary,completedAt:new Date().toISOString()};R(J),f("complete"),p&&B.bundleUrl&&s(p,J),N.close();}else if(y.type==="error"){let B=y.data;U(B.error||"Unknown error"),f("error"),N.close();}}catch{}},N.onerror=()=>{let x={Authorization:`Bearer ${e}`,...ee()};!o&&t&&(x["X-Fork-User-Id"]=t),!o&&r&&(x["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${d.id}`,{headers:x}).then(y=>y.json()).then(y=>{R(y),y.status==="complete"?(f("complete"),p&&y.bundleUrl&&s(p,y)):y.status==="error"&&(U(y.error||"Fork generation failed"),f("error"));}).catch(()=>{U("Connection lost"),f("error");}),N.close();};}catch(d){U(d.message),f("error");}},[e,n,o,g,s,c,r,t]),T=ur.useCallback(async v=>{try{let p={Authorization:`Bearer ${e}`,...ee()};!o&&t&&(p["X-Fork-User-Id"]=t),!o&&r&&(p["X-Fork-User-Hash"]=r);let P=await fetch(`${n}/api/v1/forks/${v}`,{headers:p});if(!P.ok)return;let h=await P.json();if(h.slotId&&c(h,{targetKind:"slot",targetId:h.slotId}),h.status==="complete"){f("complete"),R(h),U(null),F([]);return}if(h.status==="error"){f("error"),R(h),U(h.error||"Fork generation failed"),F([]);return}if(h.status!=="pending"&&h.status!=="running"&&h.status!=="building")return;f("running"),R(h),U(null),F([]);let d=new URLSearchParams({key:e});o?(d.set("previewSessionId",o.preview_session_id),d.set("previewForkId",h.id)):t&&d.set("userId",t),r&&d.set("userHash",r);let H=new EventSource(`${n}/api/v1/forks/${h.id}/events?${d.toString()}`);A.current&&A.current.close(),A.current=H;let j=h.slotId;H.onmessage=N=>{try{let x=JSON.parse(N.data);if(g(h.id,x),F(y=>[...y,x]),x.type==="complete"){let y=x.data,B={...h,status:"complete",bundleUrl:y.bundleUrl,summary:y.summary,completedAt:new Date().toISOString()};R(B),f("complete"),j&&y.bundleUrl&&s(j,B),H.close();}else if(x.type==="error"){let y=x.data;U(y.error||"Unknown error"),f("error"),H.close();}}catch{}},H.onerror=()=>{H.close();};}catch{}},[e,n,o,g,s,c,r,t]),I=ur.useCallback(async v=>{try{let p={userId:t,slotId:v};r&&(p.userHash=r);let P=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(p)});if(!P.ok){let d=await P.json().catch(()=>({}));throw new Error(d.error||`API error: ${P.status}`)}let h=await P.json();return l(v),h.removed?(i(v),R(null),f("prompting")):h.fork&&(s(v,h.fork),R(h.fork)),h}catch(p){throw U(p.message),p}},[e,t,r,n,i,s]);return {state:b,fork:k,events:C,error:_,open:w,close:O,startFork:$,undoFork:I,adoptRunningFork:T}}function xn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:l,adoptRunningFork:c}=Sr(),[g,b]=ur.useState(false),f=ur.useCallback(()=>{b(true),o();},[o]),k=ur.useCallback(()=>{b(false),s();},[s]),R=ur.useCallback(async C=>{b(true),await c(C);},[c]);return {state:e,fork:t,events:r,error:n,isOpen:g,open:f,close:k,submit:i,undo:l,adoptRunningFork:R}}var ms=new Set(["pending","running","building"]);function Ar(e){let t=vn(e),r=xn(),n=Sn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:l,appId:c,activitySummary:g,forkActivities:b,markForkActivitySeen:f}=ye(),k=t.type==="slot"?r:n,R=t.type==="slot"?"slot":"boundary",C=t.id,F=t.title,_=t.type==="slot"?"slot":"module",U=b.find(T=>T.targetKind===_&&T.targetId===t.id&&ms.has(T.status)),A=b.find(T=>T.targetKind===_&&T.targetId===t.id&&T.status==="complete"&&T.unread),w=ur.useCallback(()=>{f();let T=U??A;if(T){k.adoptRunningFork(T.id);return}k.open();},[k,f,U,A]),O=ur.useCallback((T,I,v,p)=>t.type==="slot"?r.submit(T,I??t.id,v,p):n.submit(T,v,p),[n,r,t]),$=ur.useCallback(T=>t.type==="slot"?r.undo(T??t.id):n.undo(),[n,r,t]);return {...k,open:w,target:t,targetId:C,targetLabel:F,historyMode:R,submit:O,undo:$,buttonProps:{onClick:w,hasNotification:g.unreadCompletedCount>0,activity:g},panelProps:{state:k.state,fork:k.fork,events:k.events,error:k.error,...t.type==="slot"?{slotId:C,targetLabel:F,historyMode:R}:{targetId:C,targetLabel:F,historyMode:R},onSubmit:O,onUndo:$,onClose:k.close,baseUrl:o,apiKey:s,userId:i,userHash:l,appId:c}}}function xt(e){let{embedded:t,completeVariant:r}=e,n=Ar(e);return t?Wn.jsx(Jt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?Wn.jsx(Jt,{...n.panelProps,completeVariant:r}):Wn.jsx(hr,{...n.buttonProps})}function gs({boundaryId:e,title:t}){return Wn.jsx(xt,{boundaryId:e,title:t})}function Pe(e){return (e??"").replace(/\s+/g," ").trim().toLowerCase()}function We(e){return Math.max(0,e.width)*Math.max(0,e.height)}function ys(e,t){return t.top>=e.top&&t.left>=e.left&&t.right<=e.right&&t.bottom<=e.bottom}function ks(e,t){let r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),n=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top));return r*n}function bs(e){if(e.hasAttribute("data-fork-highlights")||e.closest("[data-fork-highlights]"))return false;let t=e.getBoundingClientRect();if(t.width<8||t.height<8||t.bottom<0||t.right<0||t.top>window.innerHeight||t.left>window.innerWidth)return false;let r=getComputedStyle(e);return !(r.display==="none"||r.visibility==="hidden"||Number(r.opacity)===0)}function ws(e){if(!bs(e))return null;let t=getComputedStyle(e);return {rect:e.getBoundingClientRect(),borderRadius:parseFloat(t.borderTopLeftRadius)||0}}function vs(e){return !!(e.text||e.ariaLabel||e.selector||e.role||e.tagName||e.classIncludes?.length||e.dataAttributes&&Object.keys(e.dataAttributes).length>0)}function Fn(e,t,r=false){let n=r?14:0,o=Pe(e.innerText||e.textContent||""),s=Pe(t.text);s&&(o===s?n+=12:o.includes(s)?n+=9:n-=2,o.length>s.length*5&&(n-=2));let i=Pe(e.getAttribute("aria-label")),l=Pe(t.ariaLabel);l&&(i===l?n+=12:i.includes(l)?n+=9:n-=2),t.role&&Pe(e.getAttribute("role"))===Pe(t.role)&&(n+=3),t.tagName&&e.tagName.toLowerCase()===t.tagName.toLowerCase()&&(n+=2);for(let g of t.classIncludes??[]){let b=Pe(g);if(!b)continue;Pe(typeof e.className=="string"?e.className:"").includes(b)&&(n+=5);}for(let[g,b]of Object.entries(t.dataAttributes??{})){let f=e.getAttribute(g);f&&Pe(f)===Pe(b)&&(n+=9);}let c=We(e.getBoundingClientRect())/Math.max(1,window.innerWidth*window.innerHeight);return c>.45?n-=8:c>.25&&(n-=4),n}function An(e,t,r){let n=ws(t);if(!n||r<5)return;let o=e.get(t);o&&o.score>=r||e.set(t,{element:t,score:r,rect:n.rect,borderRadius:n.borderRadius});}function Ss(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Array.isArray(t.candidates)?t.candidates.filter(n=>n&&typeof n=="object"&&vs(n)):[];return r.length===0?null:{version:t.version,label:typeof t.label=="string"?t.label.slice(0,48):void 0,description:typeof t.description=="string"?t.description.slice(0,140):void 0,candidates:r,source:typeof t.source=="string"?t.source:void 0}}function xs(e,t){let r=Math.max(1,window.innerWidth*window.innerHeight),n=[...e].filter(({rect:s})=>s.width>=8&&s.height>=8).filter(({rect:s})=>We(s)<=r*.6).sort((s,i)=>We(s.rect)-We(i.rect)),o=[];for(let s of n){let i=We(s.rect);if(!(i<=0||o.some(c=>{let g=ks(c.rect,s.rect),b=Math.min(We(c.rect),i);return g/Math.max(1,b)>.72||ys(s.rect,c.rect)}))&&(o.push(s),o.length>=t))break}return o}function _n(e,t){let r=Ss(t);if(!r)return null;let n=[e,...Array.from(e.querySelectorAll("*"))].filter(i=>i instanceof HTMLElement),o=new Map;for(let i of r.candidates??[]){if(i.selector)try{let l=e.querySelectorAll(i.selector);for(let c of l)c instanceof HTMLElement&&An(o,c,Fn(c,i,!0));}catch{}for(let l of n)An(o,l,Fn(l,i));}let s=[...o.values()].sort((i,l)=>l.score!==i.score?l.score-i.score:We(i.rect)-We(l.rect))[0];return s?{plan:r,rects:[{rect:s.rect,borderRadius:s.borderRadius}]}:{plan:r,rects:[]}}function _r(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 Cn(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 Cr(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 En(e,t){let r=[];for(let n of t)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.push({rect:n.rect,borderRadius:n.borderRadius});return xs(r,3)}function $n(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 Pn(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 Fs(e,t,r){return Math.min(r,Math.max(t,e))}function Rn(e){let t=e?.trim();return t?`New: ${t.slice(0,48)}`:"New feature"}function Yt(e,t={}){let r="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText='position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;';let o=document.createElementNS(r,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let s=document.createElementNS(r,"defs");o.appendChild(s);let i=[];for(let f=0;f<Math.min(e.length,2);f+=1){let{rect:k,borderRadius:R}=e[f],C=4,F=k.left-C,_=k.top-C,U=k.width+C*2,A=k.height+C*2,w=Math.min(R+C,U/2,A/2),O=Pn(F,_,U,A,w),$=`__fork-glow-${f}`,T=document.createElementNS(r,"filter");T.setAttribute("id",$),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let I=document.createElementNS(r,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","5"),T.appendChild(I),s.appendChild(T);let v=document.createElementNS(r,"path");v.setAttribute("d",O),v.setAttribute("fill","none"),v.setAttribute("stroke","rgba(37, 99, 235, 0.34)"),v.setAttribute("stroke-width","9"),v.setAttribute("stroke-linecap","round"),v.setAttribute("filter",`url(#${$})`),v.setAttribute("opacity","0"),o.appendChild(v);let p=document.createElementNS(r,"path");p.setAttribute("d",O),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(37, 99, 235, 0.72)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("stroke-linejoin","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(p.animate([{opacity:0,strokeWidth:2,offset:0},{opacity:.95,strokeWidth:2.25,offset:.12},{opacity:.42,strokeWidth:2,offset:.34},{opacity:.88,strokeWidth:2.25,offset:.54},{opacity:.38,strokeWidth:2,offset:.76},{opacity:0,strokeWidth:2,offset:1}],{duration:7200,easing:"ease-in-out",fill:"forwards"})),i.push(v.animate([{opacity:0,strokeWidth:8,offset:0},{opacity:.72,strokeWidth:12,offset:.12},{opacity:.18,strokeWidth:8,offset:.34},{opacity:.58,strokeWidth:12,offset:.54},{opacity:.16,strokeWidth:8,offset:.76},{opacity:0,strokeWidth:8,offset:1}],{duration:7200,easing:"ease-in-out",fill:"forwards"}));}n.appendChild(o);let l=e[0]?.rect;if(l){let f=document.createElement("div");f.textContent=Rn(t.label),f.style.cssText=["position:absolute","display:inline-flex","align-items:center","max-width:min(280px,calc(100vw - 24px))","min-height:28px","padding:0 10px","border-radius:7px","background:rgba(255,255,255,0.98)","border:1px solid rgba(37,99,235,0.28)","box-shadow:0 10px 24px -18px rgba(15,23,42,0.55),0 4px 12px -8px rgba(37,99,235,0.38)","color:#0f172a","font-size:12px","font-weight:650","line-height:16px","letter-spacing:0","white-space:nowrap","overflow:hidden","text-overflow:ellipsis"].join(";"),n.appendChild(f);let k=Math.max(96,window.innerWidth-24),R=Math.min(280,k,Math.max(120,Rn(t.label).length*7+36)),C=Fs(l.left+l.width/2-R/2,12,Math.max(12,window.innerWidth-R-12)),F=l.top>=42,_=F?l.top-36:Math.min(window.innerHeight-40,l.bottom+8);f.style.width=`${R}px`,f.style.left=`${C}px`,f.style.top=`${Math.max(10,_)}px`,i.push(f.animate([{opacity:0,transform:F?"translateY(4px)":"translateY(-4px)",offset:0},{opacity:1,transform:"translateY(0)",offset:.14},{opacity:1,transform:"translateY(0)",offset:.82},{opacity:0,offset:1}],{duration:7200,easing:"ease-in-out",fill:"forwards"}));}document.body.appendChild(n);let c=false,g=()=>{if(c)return;c=true,clearTimeout(b);for(let k of i)try{k.cancel();}catch{}let f=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>n.remove(),window.removeEventListener("click",g);},b=setTimeout(g,7600);return setTimeout(()=>{c||window.addEventListener("click",g);},500),g}function In(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:c}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Pn(l.left,l.top,l.width,l.height,c)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.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}var Rt=new Map,_t=new Map,Er=new Map;function Rs(e){for(let t of e)_t.set(t,(_t.get(t)??0)+1);}function _s(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),Rt.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Cs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Tn(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 Es(e){if(!e||typeof document>"u")return Promise.resolve();let t=Rt.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",c),s();},c=()=>{r.removeEventListener("load",l),r.removeEventListener("error",c),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",c,{once:true});});return Rt.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 Rt.delete(e),o});return Rt.set(e,n),n}var At=null;function $s(){if(At)return At;try{At=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{At=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return At}function Ps(e){let t=Er.get(e);if(t)return t;let r=$s()(e).catch(n=>{throw Er.delete(e),n});return Er.set(e,r),r}async function Is(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>Es(s)));let o=await Ps(e.moduleUrl);return Tn(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 Tn(n,r)}function Ms(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:l,getBoundaryOverride:c,consumeBoundaryAnimation:g}=ye(),[b,f]=ur.useState(null),[k,R]=ur.useState(null),C=ur.useRef(null),F=ur.useRef(null),_=ur.useRef(null),U=ur.useRef(false),A=ur.useRef(null),w=ur.useRef(null),O=ur.useRef(null),$=c(e.id),T=$?`${$.id}:${$.createdAt??$.moduleUrl}`:"original",I=$?`override:${T}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(ur.useEffect(()=>()=>{O.current&&(clearTimeout(O.current),O.current=null),w.current&&(w.current.remove(),w.current=null);},[]),ur.useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,v]),ur.useEffect(()=>{let p=$?.cssUrls??[];if(p.length!==0)return Rs(p),()=>_s(p)},[$?.cssUrls.join("|")]),ur.useEffect(()=>{if(o&&!s&&!b||F.current===I&&b)return;let p=false;return R(null),Is($,e.original,e.exportName).then(P=>{if(!p){if($?.id&&g(e.id,$.id,T)&&C.current){let h=_r(C.current);if(h){let d=Cr(h);_.current=d.length>0?d:null,U.current=true,A.current=$.metadata?.featureHighlight??null,O.current&&(clearTimeout(O.current),O.current=null),w.current&&w.current.remove(),w.current=A.current||d.length===0?null:Cn(h);}}F.current=I,ur.startTransition(()=>{f(()=>P);});}}).catch(P=>{p||R(Cs(P));}),()=>{p=true;}},[g,I,o,s,i,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,b]),ur.useEffect(()=>{if(!U.current||!b||!C.current)return;let p=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(p||!C.current)return;let P=_.current,h=_r(C.current),d=A.current;if(_.current=null,U.current=false,A.current=null,!h){w.current&&(w.current.remove(),w.current=null);return}let H=d?_n(h,d):null;if(H?.rects.length){w.current&&(w.current.remove(),w.current=null),Yt(H.rects,{label:H.plan.label,description:H.plan.description});return}if(!P){w.current&&(w.current.remove(),w.current=null);return}let j=Cr(h),N=En(P,j),x=$n(P,j),y=w.current;if(x.length>0&&y){let B=In(x);O.current=setTimeout(()=>{O.current=null;let J=400;y.animate([{opacity:1},{opacity:0}],{duration:J,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:J,fill:"forwards"}),setTimeout(()=>{y.remove(),B.remove(),w.current===y&&(w.current=null),N.length>0&&Yt(N,H?.plan?{label:H.plan.label,description:H.plan.description}:{});},J);},3500);}else y&&(y.remove(),w.current===y&&(w.current=null)),N.length>0&&Yt(N,H?.plan?{label:H.plan.label,description:H.plan.description}:{});});}),()=>{p=true;}},[b]),k)throw k;return b?Wn.jsx("div",{ref:C,style:{display:"contents"},children:Wn.jsx(b,{...r})}):Wn.jsx(Wn.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Hs({slotId:e,title:t,slotLabel:r}){return Wn.jsx(xt,{slotId:e,title:t,slotLabel:r})}
60
- exports.ForkBoundaryUI=gs;exports.ForkButton=hr;exports.ForkChatInterface=xt;exports.ForkPanel=Jt;exports.ForkProvider=go;exports.ForkSlot=Co;exports.ForkUI=Hs;exports.clearCachedManifest=eo;exports.forkable=Ms;exports.loadManifest=Ut;exports.manifestDiffers=to;exports.readCachedManifest=Zn;exports.registerForkShared=tr;exports.useBoundaryFork=wr;exports.useFork=Sr;exports.useForkChatPanel=Ar;exports.usePreviewSession=Ot;exports.writeCachedManifest=Qn;
59
+ `}),to.jsxs("div",{className:"__fork-panel",style:Yn,children:[to.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:[to.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[to.jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!ie&&confirm("Kill all forks in this container?")){et(true);try{let E=await He();`${E?.deleted??0}`,be([]),ce(null),se(!1),S("");}catch(E){console.error("[Fork] Reset failed:",E);}finally{et(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:to.jsx(Dt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?to.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:qn}):Fe.length===0&&!rt?to.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):rt?to.jsxs("div",{ref:It,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[to.jsxs("button",{type:"button",onClick:()=>{De(l=>!l);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(false),"aria-haspopup":"menu","aria-expanded":Ee,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Gt||Ee?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[to.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:jr}),to.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Ee?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Ee&&to.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:[Fe.map(l=>{let E=l.id===me,B=at===l.id,fe=W===l.id;return to.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>ve(l.id),onMouseLeave:()=>ve(null),onClick:()=>{l.id!==me&&Gn(l.id);},disabled:!!W,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:B?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:W?"default":"pointer",textAlign:"left",fontWeight:E?600:400,opacity:W&&!fe?.55:1},children:[to.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:E&&to.jsx(lucideReact.Check,{style:{width:12,height:12}})}),to.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:fe?"Switching...":l.name})]},l.id)}),to.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),ze?to.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[to.jsx("input",{ref:g,type:"text",value:Ie,placeholder:"Container name",disabled:W==="__new__",onChange:l=>Ke(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),Or(Ie)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),tt(false),Ke(""));},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:l=>{l.currentTarget.style.borderColor="#1c4587",l.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none";}}),to.jsx("button",{type:"button",onClick:()=>{Or(Ie);},disabled:!Ie.trim()||W==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Ie.trim()||W==="__new__"?"#e5e7eb":"#1c4587",color:!Ie.trim()||W==="__new__"?"#9ca3af":"#ffffff",cursor:!Ie.trim()||W==="__new__"?"default":"pointer",flexShrink:0},children:W==="__new__"?to.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):to.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):to.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Et(true),onMouseLeave:()=>Et(false),onClick:()=>{W||(M(null),Ke(""),tt(true));},disabled:!!W,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Pe?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:W?"default":"pointer",textAlign:"left",opacity:W&&W!=="__new__"?.55:1},children:"+ New container"}),m&&to.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:m})]})]}):to.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:jr}),e==="running"&&to.jsx("span",{title:We?`Estimated ~${We} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:We?"#1c4587":"#9ca3af",backgroundColor:We?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:We?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:We?`~${We}m`:"~ m"})]}),!F&&to.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Mr&&to.jsx("button",{onClick:Ae?Xn:Vn,onMouseEnter:()=>H(true),onMouseLeave:()=>H(false),title:Ae?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:j?"#4b5563":"#9ca3af",backgroundColor:j?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ae?to.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):to.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),to.jsx("button",{onClick:Dr,onMouseEnter:()=>T(true),onMouseLeave:()=>T(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:to.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),to.jsxs("div",{ref:he,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(J||re)&&to.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[to.jsx("button",{onClick:()=>{ce(null),se(false),ge.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 E=(J?ae.find(B=>B.id===J)?.targetId:null)??nt;return E?to.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 ${E}`,children:["Forking ",to.jsx("span",{style:{color:"#6b7280"},children:E})]}):null})()]}),!J&&!re&&to.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[to.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:to.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),ae.length===0&&to.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),ae.length>0&&to.jsx("div",{style:{display:"flex",flexDirection:"column"},children:ae.map(l=>{let E=l.summary||"Untitled fork";return to.jsxs("button",{onClick:()=>{se(false),ce(l.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:B=>B.currentTarget.style.background="#fafafa",onMouseLeave:B=>B.currentTarget.style.background="#ffffff",children:[to.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[to.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:E}),to.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:ms(l.updatedAt)})]}),to.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[to.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),to.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),to.jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?to.jsxs(to.Fragment,{children:[to.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),to.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},l.id)})})]}),J&&ct.length>0&&to.jsx("div",{style:{padding:"16px 16px 0 16px"},children:ct.map((l,E)=>to.jsx("div",{style:{marginBottom:E<ct.length-1?10:0},children:l.type==="user"?to.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[to.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:to.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),to.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:l.text})]}):N==="item"&&E===ct.length-1?to.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[to.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:to.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),to.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[to.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),to.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),p&&e!=="running"&&to.jsx("button",{onClick:B=>{B.stopPropagation(),Ur();},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"})]}):to.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[to.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:to.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),to.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:[to.jsx("span",{style:{flex:1},children:l.text}),p&&E===ct.length-1&&e!=="running"&&to.jsxs("button",{onClick:B=>{B.stopPropagation(),Ur();},onMouseEnter:()=>Y(E),onMouseLeave:()=>Y(null),disabled:D,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:le===E?"rgba(0,0,0,0.06)":"transparent",color:le===E?"#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:[to.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),le===E&&to.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"})]})]})]})},E))}),e==="running"&&(J||re)&&to.jsx("div",{style:{padding:16},children:to.jsxs("div",{onClick:()=>pe(!z),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[to.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[to.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[to.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:to.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),to.jsx(ys,{events:r})]}),to.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:z?"rotate(180deg)":"rotate(0deg)"},children:to.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),to.jsx("div",{style:{maxHeight:z?320:0,opacity:z?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:to.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:to.jsx(mn,{events:r})})})]})}),e==="error"&&(J||re)&&to.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[to.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:to.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),to.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),to.jsxs("button",{onClick:()=>{let l=t?.prompt||$t.current;l&&u(l,nt);},onMouseEnter:()=>G(true),onMouseLeave:()=>G(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:O?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[to.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&to.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:to.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:[to.jsx("textarea",{ref:de,value:_,onChange:l=>{S(l.target.value),l.target.style.height="auto",l.target.style.height=Math.min(l.target.scrollHeight,160)+"px";},onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Br()),l.key==="Escape"&&!F&&Dr();},placeholder:J?"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"}}),to.jsx("button",{onClick:Br,disabled:!_.trim(),onMouseEnter:()=>A(true),onMouseLeave:()=>A(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:_.trim()?1:.25,transform:y&&_.trim()?"scale(1.1)":"scale(1)",background:_.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:_.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:to.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return F?Zt:Ae&&K?eo.createPortal(Zt,K.document.body):to.jsx(ks,{children:Zt})}function Sn(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 br(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:p,recordForkActivityEvent:h}=ke(),[d,v]=ur.useState("idle"),[w,x]=ur.useState(null),[f,F]=ur.useState([]),[N,_]=ur.useState(null),S=ur.useRef(null),U=ur.useCallback(()=>{v("prompting"),F([]),_(null),x(null);},[]),L=ur.useCallback(()=>{v("idle"),S.current&&(S.current.close(),S.current=null);},[]);ur.useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&v(k=>k==="idle"?"prompting":k);},[i?.preview_session_id,i?.target.id,e]);let C=ur.useCallback(async(k,$,b)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");v("running"),F([]),_(null),x(null);let c;if(i){let H=b?.forkId??i.fork_id??void 0,y=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ne()},body:JSON.stringify({prompt:k,...e?{boundary_id:e}:{},...H&&!b?.forceNew?{fork_id:H}:{},...b?.forceNew?{force_new:!0}:{}})});if(!y.ok){let G=await y.json().catch(()=>({}));throw new Error(G.error||`API error: ${y.status}`)}let A=await y.json();A.container_id&&Xe(A.container_id,A.container_name),ut(A.fork_id),c=await(await fetch(`${o}/api/v1/forks/${A.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...ne()}})).json();}else if(b?.forkId){let H={prompt:k};r&&(H.userId=r),n&&(H.userHash=n);let y=await fetch(`${o}/api/v1/forks/${encodeURIComponent(b.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(H)});if(!y.ok){let A=await y.json().catch(()=>({}));throw new Error(A.error||`API error: ${y.status}`)}c=await y.json();}else {let H={userId:r,prompt:k,boundaryId:e,appId:s};$&&(H.containerId=$),n&&(H.userHash=n),b?.forceNew&&(H.force_new=!0);let y=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(H)});if(!y.ok){let A=await y.json().catch(()=>({}));throw new Error(A.error||`API error: ${y.status}`)}c=await y.json();}x(c),p(c,{targetKind:"module",targetId:e});let T=new URLSearchParams({key:t});i?(T.set("previewSessionId",i.preview_session_id),T.set("previewForkId",c.id)):r&&T.set("userId",r),n&&T.set("userHash",n);let j=new EventSource(`${o}/api/v1/forks/${c.id}/events?${T.toString()}`);S.current=j,j.onmessage=H=>{try{let y=JSON.parse(H.data);if(h(c.id,y),F(A=>[...A,y]),y.type==="complete"){let A=y.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let O={...c,status:"complete",moduleUrl:A.moduleUrl,cssUrls:A.cssUrls,summary:A.summary,completedAt:new Date().toISOString()};x(O),v("complete"),j.close();});}else if(y.type==="error"){let A=y.data;_(A.error||"Unknown error"),v("error"),j.close();}}catch{}},j.onerror=()=>{let H={Authorization:`Bearer ${t}`,...ne()};!i&&r&&(H["X-Fork-User-Id"]=r),!i&&n&&(H["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:H}).then(y=>y.json()).then(y=>{x(y),y.status==="complete"?(u(e,y.id),a().catch(()=>{}),v("complete")):y.status==="error"&&(_(y.error||"Fork generation failed"),v("error"));}).catch(()=>{_("Connection lost"),v("error");}),j.close();};}catch(c){_(c.message),v("error");}},[t,s,o,e,i,u,a,h,p,n,r]),P=ur.useCallback(async k=>{try{let $={Authorization:`Bearer ${t}`,...ne()};!i&&r&&($["X-Fork-User-Id"]=r),!i&&n&&($["X-Fork-User-Hash"]=n);let b=await fetch(`${o}/api/v1/forks/${k}`,{headers:$});if(!b.ok)return;let c=await b.json(),T=c.boundaryId??e;if(p(c,{targetKind:"module",targetId:T}),c.status==="complete"){v("complete"),x(c),_(null),F([]);return}if(c.status==="error"){v("error"),x(c),_(c.error||"Fork generation failed"),F([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;v("running"),x(c),_(null),F([]);let j=new URLSearchParams({key:t});i?(j.set("previewSessionId",i.preview_session_id),j.set("previewForkId",c.id)):r&&j.set("userId",r),n&&j.set("userHash",n);let H=new EventSource(`${o}/api/v1/forks/${c.id}/events?${j.toString()}`);S.current&&S.current.close(),S.current=H,H.onmessage=y=>{try{let A=JSON.parse(y.data);if(h(c.id,A),F(O=>[...O,A]),A.type==="complete"){let O=A.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let G={...c,status:"complete",moduleUrl:O.moduleUrl,cssUrls:O.cssUrls,summary:O.summary,completedAt:new Date().toISOString()};x(G),v("complete"),H.close();});}else if(A.type==="error"){let O=A.data;_(O.error||"Unknown error"),v("error"),H.close();}}catch{}},H.onerror=()=>{H.close();};}catch{}},[t,o,e,i,u,h,a,p,n,r]),R=ur.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 $=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(k)});if(!$.ok){let c=await $.json().catch(()=>({}));throw new Error(c.error||`API error: ${$.status}`)}let b=await $.json();return await a().catch(()=>{}),b.removed?(x(null),v("prompting")):b.fork&&(x(b.fork),v("complete")),b}catch(k){throw _(k.message),k}},[t,s,o,e,a,n,r]);return {state:d,fork:w,events:f,error:N,open:U,close:L,startFork:C,undoFork:R,adoptRunningFork:P}}var Ss=0;function An(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:p}=br(e),[h,d]=ur.useState(false),v=ur.useRef(null),w=ur.useRef(t),x=ur.useCallback(()=>{v.current!==null&&(clearTimeout(v.current),v.current=null);},[]),f=ur.useCallback(()=>{x(),d(true),s();},[x,s]),F=ur.useCallback(()=>{x(),d(false),i();},[x,i]),N=ur.useCallback(async _=>{x(),d(true),await p(_);},[p,x]);return ur.useEffect(()=>{let _=w.current;w.current=t,t==="complete"&&_!=="complete"&&h&&(x(),v.current=setTimeout(()=>{v.current=null,d(false),i();},Ss)),(t==="running"||t==="prompting")&&x();},[t,h,x,i]),ur.useEffect(()=>x,[x]),{state:t,fork:r,events:n,error:o,isOpen:h,open:f,close:F,submit:a,undo:u,adoptRunningFork:N}}function wr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:p}=ke(),[h,d]=ur.useState("idle"),[v,w]=ur.useState(null),[x,f]=ur.useState([]),[F,N]=ur.useState(null),_=ur.useRef(null),S=ur.useCallback(()=>{d("prompting"),f([]),N(null),w(null);},[]),U=ur.useCallback(()=>{d("idle"),_.current&&(_.current.close(),_.current=null);},[]);ur.useEffect(()=>{o&&o.target.kind==="slot"&&d(R=>R==="idle"?"prompting":R);},[o?.preview_session_id,o?.target.kind]);let L=ur.useCallback(async(R,k,$,b)=>{try{d("running"),f([]),N(null),w(null);let c;if(o){let y=b?.forkId??o.fork_id??void 0,A=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ne()},body:JSON.stringify({prompt:R,...k?{slot_id:k}:{},...y&&!b?.forceNew?{fork_id:y}:{},...b?.forceNew?{force_new:!0}:{}})});if(!A.ok){let z=await A.json().catch(()=>({}));throw new Error(z.error||`API error: ${A.status}`)}let O=await A.json();O.container_id&&Xe(O.container_id,O.container_name),ut(O.fork_id),c=await(await fetch(`${n}/api/v1/forks/${O.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...ne()}})).json();}else if(b?.forkId){let y={prompt:R};t&&(y.userId=t),r&&(y.userHash=r);let A=await fetch(`${n}/api/v1/forks/${encodeURIComponent(b.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(y)});if(!A.ok){let O=await A.json().catch(()=>({}));throw new Error(O.error||`API error: ${A.status}`)}c=await A.json();}else {let y={userId:t,prompt:R};k&&(y.slotId=k),$&&(y.containerId=$),r&&(y.userHash=r),b?.forceNew&&(y.force_new=!0);let A=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(y)});if(!A.ok){let O=await A.json().catch(()=>({}));throw new Error(O.error||`API error: ${A.status}`)}c=await A.json();}w(c);let T=k??c.slotId;T&&u(c,{targetKind:"slot",targetId:T});let j=new URLSearchParams({key:e});o?(j.set("previewSessionId",o.preview_session_id),j.set("previewForkId",c.id)):t&&j.set("userId",t),r&&j.set("userHash",r);let H=new EventSource(`${n}/api/v1/forks/${c.id}/events?${j.toString()}`);_.current=H,H.onmessage=y=>{try{let A=JSON.parse(y.data);if(p(c.id,A),f(O=>[...O,A]),A.type==="complete"){let O=A.data,G={...c,status:"complete",bundleUrl:O.bundleUrl,summary:O.summary,completedAt:new Date().toISOString()};w(G),d("complete"),k&&O.bundleUrl&&s(k,G),H.close();}else if(A.type==="error"){let O=A.data;N(O.error||"Unknown error"),d("error"),H.close();}}catch{}},H.onerror=()=>{let y={Authorization:`Bearer ${e}`,...ne()};!o&&t&&(y["X-Fork-User-Id"]=t),!o&&r&&(y["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:y}).then(A=>A.json()).then(A=>{w(A),A.status==="complete"?(d("complete"),k&&A.bundleUrl&&s(k,A)):A.status==="error"&&(N(A.error||"Fork generation failed"),d("error"));}).catch(()=>{N("Connection lost"),d("error");}),H.close();};}catch(c){N(c.message),d("error");}},[e,n,o,p,s,u,r,t]),C=ur.useCallback(async R=>{try{let k={Authorization:`Bearer ${e}`,...ne()};!o&&t&&(k["X-Fork-User-Id"]=t),!o&&r&&(k["X-Fork-User-Hash"]=r);let $=await fetch(`${n}/api/v1/forks/${R}`,{headers:k});if(!$.ok)return;let b=await $.json();if(b.slotId&&u(b,{targetKind:"slot",targetId:b.slotId}),b.status==="complete"){d("complete"),w(b),N(null),f([]);return}if(b.status==="error"){d("error"),w(b),N(b.error||"Fork generation failed"),f([]);return}if(b.status!=="pending"&&b.status!=="running"&&b.status!=="building")return;d("running"),w(b),N(null),f([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",b.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let T=new EventSource(`${n}/api/v1/forks/${b.id}/events?${c.toString()}`);_.current&&_.current.close(),_.current=T;let j=b.slotId;T.onmessage=H=>{try{let y=JSON.parse(H.data);if(p(b.id,y),f(A=>[...A,y]),y.type==="complete"){let A=y.data,O={...b,status:"complete",bundleUrl:A.bundleUrl,summary:A.summary,completedAt:new Date().toISOString()};w(O),d("complete"),j&&A.bundleUrl&&s(j,O),T.close();}else if(y.type==="error"){let A=y.data;N(A.error||"Unknown error"),d("error"),T.close();}}catch{}},T.onerror=()=>{T.close();};}catch{}},[e,n,o,p,s,u,r,t]),P=ur.useCallback(async R=>{try{let k={userId:t,slotId:R};r&&(k.userHash=r);let $=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(k)});if(!$.ok){let c=await $.json().catch(()=>({}));throw new Error(c.error||`API error: ${$.status}`)}let b=await $.json();return a(R),b.removed?(i(R),w(null),d("prompting")):b.fork&&(s(R,b.fork),w(b.fork)),b}catch(k){throw N(k.message),k}},[e,t,r,n,i,s]);return {state:h,fork:v,events:x,error:F,open:S,close:U,startFork:L,undoFork:P,adoptRunningFork:C}}var _s=0;function En(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=wr(),[p,h]=ur.useState(false),d=ur.useRef(null),v=ur.useRef(e),w=ur.useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),x=ur.useCallback(()=>{w(),h(true),o();},[w,o]),f=ur.useCallback(()=>{w(),h(false),s();},[w,s]),F=ur.useCallback(async N=>{w(),h(true),await u(N);},[u,w]);return ur.useEffect(()=>{let N=v.current;v.current=e,e==="complete"&&N!=="complete"&&p&&(w(),d.current=setTimeout(()=>{d.current=null,h(false),s();},_s)),(e==="running"||e==="prompting")&&w();},[e,p,w,s]),ur.useEffect(()=>w,[w]),{state:e,fork:t,events:r,error:n,isOpen:p,open:x,close:f,submit:i,undo:a,adoptRunningFork:F}}var Cs=new Set(["pending","running","building"]);function Sr(e){let t=Sn(e),r=En(),n=An(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:p,forkActivities:h,markForkActivitySeen:d}=ke(),v=t.type==="slot"?r:n,w=t.type==="slot"?"slot":"boundary",x=t.id,f=t.title,F=t.type==="slot"?"slot":"module",N=h.find(C=>C.targetKind===F&&C.targetId===t.id&&Cs.has(C.status)),_=h.find(C=>C.targetKind===F&&C.targetId===t.id&&C.status==="complete"&&C.unread),S=ur.useCallback(()=>{d();let C=N??_;if(C){v.adoptRunningFork(C.id);return}v.open();},[v,d,N,_]),U=ur.useCallback((C,P,R,k)=>t.type==="slot"?r.submit(C,P??t.id,R,k):n.submit(C,R,k),[n,r,t]),L=ur.useCallback(C=>t.type==="slot"?r.undo(C??t.id):n.undo(),[n,r,t]);return {...v,open:S,target:t,targetId:x,targetLabel:f,historyMode:w,submit:U,undo:L,buttonProps:{onClick:S,hasNotification:p.unreadCompletedCount>0,activity:p},panelProps:{state:v.state,fork:v.fork,events:v.events,error:v.error,...t.type==="slot"?{slotId:x,targetLabel:f,historyMode:w}:{targetId:x,targetLabel:f,historyMode:w},onSubmit:U,onUndo:L,onClose:v.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function St(e){let{embedded:t,completeVariant:r}=e,n=Sr(e);return t?to.jsx(Wt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?to.jsx(Wt,{...n.panelProps,completeVariant:r}):to.jsx(mr,{...n.buttonProps})}function Es({boundaryId:e,title:t}){return to.jsx(St,{boundaryId:e,title:t})}function Fr(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 Rn(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 Ar(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 $n(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 a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Pn(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 a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function In(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:d,borderRadius:v}=e[h],w=d.left-.5,x=d.top-.5,f=d.width+1,F=d.height+1,N=Math.min(v+.5,f/2,F/2),_=In(w,x,f,F,N),S=`__fork-glow-${h}`,U=document.createElementNS(t,"filter");U.setAttribute("id",S),U.setAttribute("x","-100%"),U.setAttribute("y","-100%"),U.setAttribute("width","300%"),U.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),U.appendChild(L),o.appendChild(U);let C=`__fork-mask-${h}`,P=document.createElementNS(t,"mask");P.setAttribute("id",C),P.setAttribute("maskUnits","userSpaceOnUse"),P.setAttribute("x",String(w-200)),P.setAttribute("y",String(x-200)),P.setAttribute("width",String(f+400)),P.setAttribute("height",String(F+400));let R=document.createElementNS(t,"rect");R.setAttribute("x",String(w-200)),R.setAttribute("y",String(x-200)),R.setAttribute("width",String(f+400)),R.setAttribute("height",String(F+400)),R.setAttribute("fill","white"),P.appendChild(R);let k=document.createElementNS(t,"path");k.setAttribute("d",_),k.setAttribute("fill","black"),P.appendChild(k),o.appendChild(P);let $=document.createElementNS(t,"g");$.setAttribute("mask",`url(#${C})`),$.setAttribute("opacity","0");let b=document.createElementNS(t,"g");b.setAttribute("filter",`url(#${S})`);let c=document.createElementNS(t,"path");c.setAttribute("d",_),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),b.appendChild(c),$.appendChild(b),n.appendChild($);let T=document.createElementNS(t,"path");T.setAttribute("d",_),T.setAttribute("fill","none"),T.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),T.setAttribute("stroke-width","2"),T.setAttribute("stroke-linecap","round"),T.setAttribute("opacity","0"),n.appendChild(T),s.push(c,T),c.__group=$;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let h=0;h<s.length;h+=2){let d=s[h],v=s[h+1],w=d.__group;if(!w)continue;let x=v.getTotalLength(),f=d.getTotalLength();if(x<=0)continue;let F=x*.35;v.setAttribute("stroke-dasharray",`${F} ${x-F}`),v.setAttribute("stroke-dashoffset","0"),i.push(v.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let N=f*.35;d.setAttribute("stroke-dasharray",`${N} ${f-N}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*f,offset:.06},{strokeDashoffset:-2*f,offset:.92},{strokeDashoffset:-2.25*f,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(w.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 a=false,u=()=>{if(a)return;a=true,clearTimeout(p);for(let d of i)try{d.cancel();}catch{}let h=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});h.onfinish=()=>r.remove(),window.removeEventListener("click",u);},p=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Tn(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:a,borderRadius:u}of e){let p=document.createElementNS(t,"path");p.setAttribute("d",In(a.left,a.top,a.width,a.height,u)),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),p.setAttribute("stroke-width","1.5"),p.setAttribute("stroke-dasharray","8 4"),p.setAttribute("stroke-linecap","round"),p.setAttribute("filter","url(#__fork-removed-shadow)"),p.setAttribute("opacity","0"),n.appendChild(p),p.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 Hn(e,t){if($s(t.selector))return Ln(e,t);let n=Ln(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(Mn(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=Er(e,h=>h===s);if(i)return i;let a=s.toLowerCase(),u=Er(e,h=>h.toLowerCase()===a);if(u)return u;let p=Er(e,h=>h.toLowerCase().includes(a));if(p)return p}}let o=Ps(t.selector);if(o&&o!==t.selector&&Mn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function Mn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Ln(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Cr(t.label),o=Cr(t.textHint);return r.find(i=>{let a=Cr(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function $s(e){return e.trim()==="[data-fork-new]"}function Cr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ps(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Er(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 a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let u=a.width*a.height;u<n&&(r=s,n=u);}return r}var Rr=2147483600,Is=1600,Ts=3e4,Ms=300,Oe=10;function Ls(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 a=e.getBoundingClientRect(),u=Math.min(a.width,a.height);return Math.max(4,i/100*u)}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 Hs(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+Oe+8?a="bottom":a==="bottom"&&i-t.bottom<n+Oe+8?a="top":a==="left"&&t.left<r+Oe+8?a="right":a==="right"&&s-t.right<r+Oe+8&&(a="left");let u=0,p=0;return a==="top"?(u=t.top-n-Oe,p=t.left+t.width/2-r/2):a==="bottom"?(u=t.bottom+Oe,p=t.left+t.width/2-r/2):a==="left"?(u=t.top+t.height/2-n/2,p=t.left-r-Oe):(u=t.top+t.height/2-n/2,p=t.right+Oe),p=Math.max(8,Math.min(p,s-r-8)),u=Math.max(8,Math.min(u,i-n-8)),{top:u,left:p,placement:a}}function Bs(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Rr}`,"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:${Rr-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:${Rr+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 Ns(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
60
+ @keyframes __fork-highlight-pulse {
61
+ 0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
62
+ 50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
63
+ }
64
+ `,document.head.appendChild(e);}function Bn(e,t,r="top"){Ns();let{outline:n,glow:o,tooltip:s}=Bs(t),i=Ls(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${Is}ms ease-in-out infinite`,document.body.append(o,n,s);let a=()=>{let f=e.getBoundingClientRect();if(f.width===0&&f.height===0)return;n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,n.style.width=`${f.width}px`,n.style.height=`${f.height}px`,o.style.top=`${f.top-1}px`,o.style.left=`${f.left-1}px`,o.style.width=`${f.width+2}px`,o.style.height=`${f.height+2}px`;let F=s.getBoundingClientRect(),N=F.width||s.offsetWidth||80,_=F.height||s.offsetHeight||26,S=Hs(r,f,N,_);s.style.top=`${S.top}px`,s.style.left=`${S.left}px`;};a(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(a);});let u=false,p=new ResizeObserver(a);p.observe(e);let h=()=>a(),d=()=>a();window.addEventListener("scroll",h,true),window.addEventListener("resize",d);let v=()=>{u||(u=true,clearTimeout(x),p.disconnect(),window.removeEventListener("scroll",h,true),window.removeEventListener("resize",d),window.removeEventListener("click",w,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();},Ms));},w=()=>v();setTimeout(()=>{u||window.addEventListener("click",w,{once:true,capture:true});},250);let x=setTimeout(v,Ts);return v}var Os="fork:highlight:v1:seen";function Nn(e){return `${Os}:${e}`}function On(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 Us(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var Un=new Set;function Dn(e,t,r){return `${r}::${e}:${t}`}function $r(e,t,r){let n=Dn(e,t,r);return Un.has(n)?true:On(Nn(r)).has(`${e}:${t}`)}function jn(e,t,r){let n=Dn(e,t,r);Un.add(n);let o=Nn(r),s=`${e}:${t}`,i=On(o);i.has(s)||(i.add(s),Us(o,i));}var At=new Map,_t=new Map,Pr=new Map;function js(e){for(let t of e)_t.set(t,(_t.get(t)??0)+1);}function zs(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),At.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Ks(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Kn(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 Wn(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 Ws(e){if(!e||typeof document>"u")return Promise.resolve();let t=At.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 a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",u),s();},u=()=>{r.removeEventListener("load",a),r.removeEventListener("error",u),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",u,{once:true});});return At.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 At.delete(e),o});return At.set(e,n),n}var Ft=null;function Vs(){if(Ft)return Ft;try{Ft=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{Ft=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return Ft}function Xs(e){let t=Pr.get(e);if(t)return t;let r=Vs()(e).catch(n=>{throw Pr.delete(e),n});return Pr.set(e,r),r}async function Js(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>Ws(s)));let o=await Xs(e.moduleUrl);return Wn(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 Wn(n,r)}function qs(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:a,getBoundaryOverride:u,consumeBoundaryAnimation:p,highlightScope:h}=ke(),[d,v]=ur.useState(null),[w,x]=ur.useState(null),f=ur.useRef(null),F=ur.useRef(null),N=ur.useRef(null),_=ur.useRef(false),S=ur.useRef(null),U=ur.useRef(null),L=ur.useRef(null),C=u(e.id),P=C?`override:${C.id}`:"original",R=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(ur.useEffect(()=>()=>{U.current&&(clearTimeout(U.current),U.current=null),S.current&&(S.current.remove(),S.current=null),L.current&&(L.current(),L.current=null);},[]),ur.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,R]),ur.useEffect(()=>{let k=C?.cssUrls??[];if(k.length!==0)return js(k),()=>zs(k)},[C?.cssUrls.join("|")]),ur.useEffect(()=>{if(o&&!s&&!d||F.current===P&&d)return;let k=false;return x(null),Js(C,e.original,e.exportName).then($=>{if(!k){if(C?.id&&p(e.id,C.id)&&f.current){let b=Fr(f.current);if(b){let c=Ar(b);c.length>0&&(N.current=c,_.current=true,U.current&&(clearTimeout(U.current),U.current=null),S.current&&S.current.remove(),S.current=Rn(b));}}F.current=P,ur.startTransition(()=>{v(()=>$);});}}).catch($=>{k||x(Ks($));}),()=>{k=true;}},[p,P,o,s,i,C?.id,C?.moduleUrl,C?.integrity,C?.cssUrls.join("|"),e.exportName,e.original,d]),ur.useEffect(()=>{if(!d||!f.current)return;let k=false,$=null,b=()=>{if(k||!f.current)return false;let c=C?.highlightHint,T=C?.id,j=C?.createdAt?String(C.createdAt):"";if(!c||!T||$r(T,j,h))return false;let H=Array.from(f.current.querySelectorAll("[data-fork-new]"));H.length,H.map(A=>A.getAttribute("data-fork-new")),c.label,c.textHint,c.selector;let y=Hn(f.current,c);return y?.tagName,y?.getAttribute("data-fork-new"),y?.getAttribute("aria-label"),y?.textContent?.trim().slice(0,60),!y||!Kn(y)?(y&&Kn(y),y?.getBoundingClientRect(),false):(jn(T,j,h),S.current&&(S.current.remove(),S.current=null),L.current&&L.current(),L.current=Bn(y,c.label,c.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!f.current)return;let c=b();if(!c&&C?.highlightHint&&C?.id&&!$r(C.id,String(C.createdAt??""),h)){let pe=[150,400,800],D=0,Q=()=>{if(k||D>=pe.length)return;let le=pe[D];D+=1,$=setTimeout(()=>{if(b()){c=true;return}Q();},le);};Q();}let T=_.current,j=!!C?.highlightHint,H=N.current;if(N.current=null,_.current=false,c||j||!T){S.current&&(S.current.remove(),S.current=null);return}let y=Fr(f.current);if(!H||!y){S.current&&(S.current.remove(),S.current=null);return}let A=Ar(y),O=$n(H,A),G=Pn(H,A),z=S.current;if(G.length>0&&z){let pe=Tn(G);U.current=setTimeout(()=>{U.current=null;let D=400;z.animate([{opacity:1},{opacity:0}],{duration:D,fill:"forwards"}),pe.animate([{opacity:1},{opacity:0}],{duration:D,fill:"forwards"}),setTimeout(()=>{z.remove(),pe.remove(),S.current===z&&(S.current=null),O.length>0&&_r(O);},D);},3500);}else z&&(z.remove(),S.current===z&&(S.current=null)),O.length>0&&_r(O);});}),()=>{k=true,$!==null&&(clearTimeout($),$=null);}},[d,C?.id,C?.createdAt,C?.highlightHint,h]),w)throw w;return d?to.jsx("div",{ref:f,"data-fork-boundary":e.id,style:{display:"contents"},children:to.jsx(d,{...r})}):to.jsx(to.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Ys({slotId:e,title:t,slotLabel:r}){return to.jsx(St,{slotId:e,title:t,slotLabel:r})}exports.ForkBoundaryUI=Es;exports.ForkButton=mr;exports.ForkChatInterface=St;exports.ForkPanel=Wt;exports.ForkProvider=_o;exports.ForkSlot=Oo;exports.ForkUI=Ys;exports.clearCachedManifest=fo;exports.forkable=qs;exports.loadManifest=Bt;exports.manifestDiffers=po;exports.readCachedManifest=co;exports.registerForkShared=er;exports.useBoundaryFork=br;exports.useFork=wr;exports.useForkChatPanel=Sr;exports.usePreviewSession=Ht;exports.writeCachedManifest=uo;