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