@fork-api/chat-sdk 0.1.133 → 0.1.134

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var kt=require('react'),Nr=require('react-dom'),Dr=require('react/jsx-runtime'),jr=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 kt__namespace=/*#__PURE__*/_interopNamespace(kt);var Nr__namespace=/*#__PURE__*/_interopNamespace(Nr);var Dr__namespace=/*#__PURE__*/_interopNamespace(Dr);var jr__namespace=/*#__PURE__*/_interopNamespace(jr);var ce="__FORK_SHARED__";function lt(){var t,r,n,o;let e=globalThis;return e[ce]||(e[ce]={}),(t=e[ce]).react||(t.react=kt__namespace),(r=e[ce])["react-dom"]||(r["react-dom"]=Nr__namespace),(n=e[ce])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Dr__namespace),(o=e[ce])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=jr__namespace),e[ce]}function ct(e){return Object.assign(lt(),e)}var zr="__fork_preview_session__";function Ne(e){return `${zr}${e}`}var W={apiKey:null,session:null},ut=new Set;function dt(){for(let e of ut)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Dt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Wr(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Ne(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Dt(r)?(window.sessionStorage.removeItem(Ne(e)),null):r}catch{return null}}function jt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Ne(e),JSON.stringify(t)):window.sessionStorage.removeItem(Ne(e));}catch{}}function be(e){W.apiKey!==e&&(W.apiKey=e,W.session=Wr(e),dt());}function ue(){return W.session?Dt(W.session)?(ft(null),null):W.session:null}function ft(e){W.session=e,W.apiKey&&jt(W.apiKey,e),dt();}function we(e){W.session&&W.session.fork_id!==e&&(W.session={...W.session,fork_id:e},W.apiKey&&jt(W.apiKey,W.session),dt());}function pt(e){return ut.add(e),()=>{ut.delete(e);}}var zt="__fork_preview";function Wt(){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(zt);return typeof r=="string"&&r.length>0?r:null}function gt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return Gt()!==null}function Kt(){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(zt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var de=null;function Gt(){if(de)return de;let e=Wt();return e?(de=e,Kt(),de):null}async function mt(e,t){be(e);let r=ue();if(r)return de=null,r;let n=de??Wt();if(de=null,!n)return null;Kt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let 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,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ft(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function Gr(){return ue()}function Vr(){return null}function De(){return kt.useSyncExternalStore(pt,Gr,Vr)}function X(){let e=ue();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function je(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[a,f]of Object.entries(i.modules)){let g=f.moduleUrl??f.bundleUrl??null,c=f.legacyModuleUrl??f.legacyBundleUrl??null;s[a]={forkId:f.forkId,moduleUrl:g,legacyModuleUrl:c,bundleUrl:f.bundleUrl??g,legacyBundleUrl:f.legacyBundleUrl??c,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 qr="fork:manifest:v1";function ht(e,t,r){return `${qr}:${e}:${t}:${r}`}function Jr(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(ht(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Xr(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(ht(e,t,r),JSON.stringify(n));}catch{}}function Yr(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(ht(e,t,r));}catch{}}function Zr(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,a]of r){let f=t.slots[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let f=t.modules[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}return false}var Jt=kt.createContext(null);function Se(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function tn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Se(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Se(e,i)):[]};return r}function Vt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Se(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function qt(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:Se(e,i),cssUrls:(o.cssUrls??[]).map(s=>Se(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function rn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[f]=kt.useState(()=>(be(t),gt(t))),[g,c]=kt.useState({}),[x,T]=kt.useState(s?{userId:s,userHash:void 0}:null),[F,v]=kt.useState(!!s||f),[y,k]=kt.useState({}),[C,w]=kt.useState(!o),[I,$]=kt.useState(0),[A,R]=kt.useState(null),h=kt.useRef(new Map),l=kt.useRef(new Map),[E,S]=kt.useState(0),u=kt.useRef(new Set),p=kt.useRef(new Map),m=kt.useRef(void 0);lt(),kt.useEffect(()=>{return mt(t,r).then(()=>{}),()=>{}},[]);let M=De();i&&m.current!==i&&(ct(i),m.current=i),kt.useEffect(()=>{a&&(f||(v(false),fetch(a,{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");T({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{v(true);})));},[a,f]),kt.useEffect(()=>{!a&&s&&(T({userId:s,userHash:void 0}),v(true));},[s,a]);let z=x?.userId??"",Y=x?.userHash,H=M?M.target_user_id:z,j=M?void 0:Y,Z=!!o,N=kt.useCallback(async()=>{if(!Z){R(null),k({}),w(true),$(b=>b+1);return}if(!F){w(false);return}if(!H||!o){R(null),k({}),w(true),$(b=>b+1);return}if(w(false),!M){try{let b=await je({baseUrl:r,apiKey:t,appId:o,userId:H,userHash:j});b&&(R(b.containerId),c(Vt(r,b,H,o)),k(qt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch fork manifest:",b.message),R(null),c({}),k({});}finally{$(b=>b+1),w(true);}return}if(R(M.container_id??null),M.container_id){try{let b=await je({baseUrl:r,apiKey:t,appId:o,userId:H,containerId:M.container_id,extraHeaders:X()});b&&(c(Vt(r,b,H,o)),k(qt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch preview container manifest:",b.message),c({}),k({});}finally{$(b=>b+1),w(true);}return}let _=new URLSearchParams({appId:o,userId:H});j&&_.set("userHash",j);try{let b=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...X()}});if(!b.ok)throw new Error(`${b.status}`);let U=await b.json();k(tn(r,U));}catch(b){console.error("[ForkProvider] Failed to fetch module override manifest:",b.message),k({});}finally{$(b=>b+1),w(true);}},[t,o,r,F,Z,j,H,M?.preview_session_id,M?.fork_id,M?.container_id]);kt.useEffect(()=>{if(!H||o&&(!M||M.container_id))return;let _=new URLSearchParams({userId:H});j&&_.set("userHash",j),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...X()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{b&&typeof b=="object"&&c(b);}).catch(()=>{});},[t,o,H,j,r,M?.preview_session_id,M?.fork_id]),kt.useEffect(()=>{N();},[N]);let te=kt.useCallback((_,b)=>{c(U=>({...U,[_]:b}));},[]),J=kt.useCallback(_=>{c(b=>{let U={...b};return delete U[_],U});},[]),ie=kt.useCallback(_=>{u.current.add(_);},[]),K=kt.useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),$e=kt.useCallback((_,b)=>{p.current.set(_,b);},[]),ke=kt.useCallback((_,b)=>p.current.get(_)!==b?false:(p.current.delete(_),true),[]),_e=kt.useCallback(_=>{if(!o)return;let b=JSON.stringify(_);h.current.get(_.id)===b||l.current.get(_.id)?.signature===b||(l.current.set(_.id,{boundary:_,signature:b}),S(G=>G+1));},[o]);kt.useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let b=Array.from(l.current.values());b.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:b.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of b)l.current.get(U.boundary.id)?.signature===U.signature&&(l.current.delete(U.boundary.id),h.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(_);}},[t,o,r,E]);let rt=kt.useCallback(_=>y[_],[y]),Ae=kt.useCallback(async()=>{if(!H)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:H});j&&_.set("userHash",j);let b=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...X()}});if(!b.ok){let G=await b.json().catch(()=>({}));throw new Error(G.error||`API error: ${b.status}`)}let U=await b.json().catch(()=>({}));c({}),k({}),w(true),$(G=>G+1),u.current.clear(),p.current.clear();try{for(let G=sessionStorage.length-1;G>=0;G-=1){let re=sessionStorage.key(G);re&&re.startsWith("__fork_animated_")&&sessionStorage.removeItem(re);}}catch{}return U},[t,r,j,H]);return Dr.jsx(Jt.Provider,{value:{apiKey:t,userId:H,userHash:j,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Z,moduleManifestReady:C,moduleManifestVersion:I,currentContainerId:A,previewSession:M,setSlotFork:te,clearSlotFork:J,skipAnimationForSlot:ie,shouldSkipAnimation:K,queueBoundaryAnimation:$e,consumeBoundaryAnimation:ke,registerBoundary:_e,getBoundaryOverride:rt,refreshModuleManifest:N,resetAllForks:Ae},children:n})}function V(){let e=kt.useContext(Jt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ze(e){return V().forks[e]}var xe=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 bt(e,t){let r;try{r=kt.Children.only(e);}catch{let o=kt.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 Yt=new Set;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 ln(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function cn(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function er(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 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 c=0;c<e.length;c++){let{rect:x,borderRadius:T}=e[c],F=x.left-.5,v=x.top-.5,y=x.width+1,k=x.height+1,C=Math.min(T+.5,y/2,k/2),w=er(F,v,y,k,C),I=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",I),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let A=document.createElementNS(t,"feGaussianBlur");A.setAttribute("in","SourceGraphic"),A.setAttribute("stdDeviation","8"),$.appendChild(A),o.appendChild($);let R=`__fork-mask-${c}`,h=document.createElementNS(t,"mask");h.setAttribute("id",R),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(F-200)),h.setAttribute("y",String(v-200)),h.setAttribute("width",String(y+400)),h.setAttribute("height",String(k+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(F-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(k+400)),l.setAttribute("fill","white"),h.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",w),E.setAttribute("fill","black"),h.appendChild(E),o.appendChild(h);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${R})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${I})`);let p=document.createElementNS(t,"path");p.setAttribute("d",w),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let m=document.createElementNS(t,"path");m.setAttribute("d",w),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(p,m),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let x=i[c],T=i[c+1],F=x.__group,v=T.getTotalLength(),y=x.getTotalLength();if(v<=0)continue;let k=v*.35;T.setAttribute("stroke-dasharray",`${k} ${v-k}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;x.setAttribute("stroke-dasharray",`${C} ${y-C}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(F.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",f);},g=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function un(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:a,borderRadius:f}of e){let g=a.left,c=a.top,x=a.width,T=a.height,F=Math.min(f,x/2,T/2),v=er(g,c,x,T,F),y=document.createElementNS(t,"path");y.setAttribute("d",v),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.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 dn(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 fn=kt__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return Dr.jsx("div",{ref:r,style:n,children:Dr.jsx(t,{...o})})},(e,t)=>e.component===t.component&&dn(e.hostProps,t.hostProps)),yt=class extends kt__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 tr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){bt(t,e);let i=ze(e),{baseUrl:s,apiKey:a,appId:f,shouldSkipAnimation:g}=V(),[c,x]=kt.useState(null),T=kt.useRef(null),F=kt.useRef(null),v=kt.useRef(null),y=kt.useRef(false),k=kt.useRef(null),C=kt.useRef(null),w=!!(n||o),I=kt.useRef(null);w&&!I.current&&(I.current=new xe(e));let $=kt.useRef(o);if($.current=o,kt.useEffect(()=>{if(w)return ()=>{I.current?.destroy(),I.current=null;}},[w,e]),w&&I.current&&n)for(let[E,S]of Object.entries(n))I.current.set(E,S);kt.useEffect(()=>{if(!w)return;I.current||(I.current=new xe(e));let E=I.current,S=Object.keys($.current||{}).map(u=>E.on(u,(...p)=>$.current?.[u]?.(...p)));return ()=>S.forEach(u=>u())},[w,e]),kt.useEffect(()=>{if(Yt.has(e))return;Yt.add(e);let E={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 ${a}`,"Content-Type":"application/json"},body:JSON.stringify(E)}).catch(()=>{});},[e,s,a,r,f]);let A=i?.id||null;kt.useEffect(()=>{if(i?.bundleUrl,T.current,F.current,!i?.bundleUrl||!A){return}let E=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,u=sessionStorage.getItem(S),p=g(e),m=!p&&u!==A;if(p&&A&&sessionStorage.setItem(S,A),m&&F.current){let j=Zt(F.current);v.current=j,y.current=true,`${e}${j.length}`;}window.__FORK_REACT__=kt__namespace.default,window.__FORK_REACT_DOM__=Nr__namespace,window.__FORK_REACT_JSX__=Dr__namespace;let M=Date.now(),z=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${M}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=z,Y.dataset.forkSlot=e,document.head.appendChild(Y);let H=document.createElement("script");return H.src=E+"?t="+M,H.onload=()=>{let j=window.__FORK_EXPORT__;if(j?.default){if(F.current&&v.current&&y.current){let Z=F.current.getBoundingClientRect(),N=F.current.cloneNode(true);N.style.position="fixed",N.style.top=`${Z.top}px`,N.style.left=`${Z.left}px`,N.style.width=`${Z.width}px`,N.style.height=`${Z.height}px`,N.style.flex="none",N.style.minHeight="auto",N.style.zIndex="9998",N.style.pointerEvents="none",N.style.overflow="hidden";let te=getComputedStyle(F.current).backgroundColor;N.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(N);let J=F.current.querySelectorAll("*"),ie=N.querySelectorAll("*");for(let K=0;K<J.length;K++)J[K].scrollTop!==0&&(ie[K].scrollTop=J[K].scrollTop),J[K].scrollLeft!==0&&(ie[K].scrollLeft=J[K].scrollLeft);k.current=N;}x(()=>j.default),T.current=A;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},H.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(H),()=>{H.remove(),Y.remove(),C.current&&(clearTimeout(C.current),C.current=null),k.current&&(k.current.remove(),k.current=null);}},[A,s,e]),kt.useEffect(()=>{if(!y.current||!c||!F.current){`${e}${y.current}`,F.current;return}let E=v.current;if(!E){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!F.current)return;let S=Zt(F.current),u=ln(E,S),p=cn(E,S),m=k.current;if(`${e}${u.length}${p.length}`,p.length>0&&m){let M=un(p);C.current=setTimeout(()=>{C.current=null;let z=400;m.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),M.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{m.remove(),M.remove(),k.current=null,u.length>0&&(Qt(u));},z);},3500);}else m&&(m.remove(),k.current=null),u.length>0&&(Qt(u));v.current=null,y.current=false,A&&(sessionStorage.setItem(`__fork_animated_${e}`,A),`${e}`);});});},[c]);let R={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Dr.jsx("div",{ref:F,style:R,children:t});if(!c)return Dr.jsx("div",{ref:F,style:R,children:t});let l=t?.props??{};return Dr.jsx(yt,{slotId:e,resetKey:A,fallback:Dr.jsx("div",{ref:F,style:R,children:t}),children:Dr.jsx(fn,{component:c,containerRef:F,wrapperStyle:R,hostProps:l})})}var nr=new Set;function mn(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 or(e,t=new Set){return kt.Children.forEach(e,r=>{if(!kt.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&&or(n.children,t);}),t}function hn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:f}){if(bt(r,e),s==="direct")return Dr.jsx(tr,{slotId:e,githubRepo:o,shared:a,events:f,children:r});let g=ze(e),{baseUrl:c,apiKey:x,appId:T}=V(),F=kt.useRef(null),v=kt.useRef(false),y=kt.useRef(null),k=kt.useRef(i);k.current=i;let C=kt.useRef(t);C.current=t;let w=kt.useRef(n);w.current=n,kt.useEffect(()=>{if(typeof process<"u")return;let R=or(r),h=new Set(i?Object.keys(i):[]),l=[...R].filter(E=>!h.has(E));l.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:
1
+ 'use strict';var ht=require('react'),Or=require('react-dom'),Br=require('react/jsx-runtime'),Hr=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 ht__namespace=/*#__PURE__*/_interopNamespace(ht);var Or__namespace=/*#__PURE__*/_interopNamespace(Or);var Br__namespace=/*#__PURE__*/_interopNamespace(Br);var Hr__namespace=/*#__PURE__*/_interopNamespace(Hr);var ue="__FORK_SHARED__";function it(){var t,r,n,o;let e=globalThis;return e[ue]||(e[ue]={}),(t=e[ue]).react||(t.react=ht__namespace),(r=e[ue])["react-dom"]||(r["react-dom"]=Or__namespace),(n=e[ue])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Br__namespace),(o=e[ue])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Hr__namespace),e[ue]}function at(e){return Object.assign(it(),e)}var Nr="__fork_preview_session__";function Oe(e){return `${Nr}${e}`}var K={apiKey:null,session:null},lt=new Set;function ct(){for(let e of lt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Bt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Dr(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Oe(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Bt(r)?(window.sessionStorage.removeItem(Oe(e)),null):r}catch{return null}}function Ht(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Oe(e),JSON.stringify(t)):window.sessionStorage.removeItem(Oe(e));}catch{}}function we(e){K.apiKey!==e&&(K.apiKey=e,K.session=Dr(e),ct());}function de(){return K.session?Bt(K.session)?(ut(null),null):K.session:null}function ut(e){K.session=e,K.apiKey&&Ht(K.apiKey,e),ct();}function ve(e){K.session&&K.session.fork_id!==e&&(K.session={...K.session,fork_id:e},K.apiKey&&Ht(K.apiKey,K.session),ct());}function dt(e){return lt.add(e),()=>{lt.delete(e);}}var Nt="__fork_preview";function Dt(){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(Nt);return typeof r=="string"&&r.length>0?r:null}function ft(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return zt()!==null}function jt(){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(Nt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var fe=null;function zt(){if(fe)return fe;let e=Dt();return e?(fe=e,jt(),fe):null}async function pt(e,t){we(e);let r=de();if(r)return fe=null,r;let n=fe??Dt();if(fe=null,!n)return null;jt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let 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,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ut(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function zr(){return de()}function Wr(){return null}function Be(){return ht.useSyncExternalStore(dt,zr,Wr)}function Z(){let e=de();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 He(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[a,d]of Object.entries(i.modules)){let f=d.moduleUrl??d.bundleUrl??null,c=d.legacyModuleUrl??d.legacyBundleUrl??null;s[a]={forkId:d.forkId,moduleUrl:f,legacyModuleUrl:c,bundleUrl:d.bundleUrl??f,legacyBundleUrl:d.legacyBundleUrl??c,cssUrls:d.cssUrls??[],integrity:d.integrity,metadata:d.metadata,buildId:d.buildId,updatedAt:d.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Kr="fork:manifest:v1";function gt(e,t,r){return `${Kr}:${e}:${t}:${r}`}function Gr(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(gt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Vr(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(gt(e,t,r),JSON.stringify(n));}catch{}}function qr(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(gt(e,t,r));}catch{}}function Jr(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,a]of r){let d=t.slots[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let d=t.modules[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}return false}var Gt=ht.createContext(null);function xe(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Zr(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:xe(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>xe(e,i)):[]};return r}function Wt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:xe(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function Kt(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:xe(e,i),cssUrls:(o.cssUrls??[]).map(s=>xe(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Qr(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[d]=ht.useState(()=>(we(t),ft(t))),[f,c]=ht.useState({}),[F,P]=ht.useState(s?{userId:s,userHash:void 0}:null),[x,v]=ht.useState(!!s||d),[y,h]=ht.useState({}),[C,R]=ht.useState(!o),[T,$]=ht.useState(0),[M,w]=ht.useState(null),k=ht.useRef(new Map),l=ht.useRef(new Map),[E,S]=ht.useState(0),u=ht.useRef(new Set),p=ht.useRef(new Map),g=ht.useRef(void 0);it(),ht.useEffect(()=>{return pt(t,r).then(()=>{}),()=>{}},[]);let I=Be();i&&g.current!==i&&(at(i),g.current=i),ht.useEffect(()=>{a&&(d||(v(false),fetch(a,{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");P({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{v(true);})));},[a,d]),ht.useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),v(true));},[s,a]);let z=F?.userId??"",Y=F?.userHash,H=I?I.target_user_id:z,D=I?void 0:Y,V=!!o,N=ht.useCallback(async()=>{if(!V){w(null),h({}),R(true),$(b=>b+1);return}if(!x){R(false);return}if(!H||!o){w(null),h({}),R(true),$(b=>b+1);return}if(R(false),!I){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,userHash:D});b&&(w(b.containerId),c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch fork manifest:",b.message),w(null),c({}),h({});}finally{$(b=>b+1),R(true);}return}if(w(I.container_id??null),I.container_id){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,containerId:I.container_id,extraHeaders:Z()});b&&(c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch preview container manifest:",b.message),c({}),h({});}finally{$(b=>b+1),R(true);}return}let _=new URLSearchParams({appId:o,userId:H});D&&_.set("userHash",D);try{let b=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok)throw new Error(`${b.status}`);let O=await b.json();h(Zr(r,O));}catch(b){console.error("[ForkProvider] Failed to fetch module override manifest:",b.message),h({});}finally{$(b=>b+1),R(true);}},[t,o,r,x,V,D,H,I?.preview_session_id,I?.fork_id,I?.container_id]);ht.useEffect(()=>{if(!H||o&&(!I||I.container_id))return;let _=new URLSearchParams({userId:H});D&&_.set("userHash",D),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{b&&typeof b=="object"&&c(b);}).catch(()=>{});},[t,o,H,D,r,I?.preview_session_id,I?.fork_id]),ht.useEffect(()=>{N();},[N]);let Q=ht.useCallback((_,b)=>{c(O=>({...O,[_]:b}));},[]),ee=ht.useCallback(_=>{c(b=>{let O={...b};return delete O[_],O});},[]),ie=ht.useCallback(_=>{u.current.add(_);},[]),q=ht.useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),Qe=ht.useCallback((_,b)=>{p.current.set(_,b);},[]),_e=ht.useCallback((_,b)=>p.current.get(_)!==b?false:(p.current.delete(_),true),[]),ke=ht.useCallback(_=>{if(!o)return;let b=JSON.stringify(_);k.current.get(_.id)===b||l.current.get(_.id)?.signature===b||(l.current.set(_.id,{boundary:_,signature:b}),S(W=>W+1));},[o]);ht.useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let b=Array.from(l.current.values());b.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:b.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of b)l.current.get(O.boundary.id)?.signature===O.signature&&(l.current.delete(O.boundary.id),k.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,E]);let be=ht.useCallback(_=>y[_],[y]),J=ht.useCallback(async()=>{if(!H)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:H});D&&_.set("userHash",D);let b=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok){let W=await b.json().catch(()=>({}));throw new Error(W.error||`API error: ${b.status}`)}let O=await b.json().catch(()=>({}));c({}),h({}),R(true),$(W=>W+1),u.current.clear(),p.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let ae=sessionStorage.key(W);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return O},[t,r,D,H]);return Br.jsx(Gt.Provider,{value:{apiKey:t,userId:H,userHash:D,baseUrl:r,appId:o,forks:f,moduleOverridesEnabled:V,moduleManifestReady:C,moduleManifestVersion:T,currentContainerId:M,previewSession:I,setSlotFork:Q,clearSlotFork:ee,skipAnimationForSlot:ie,shouldSkipAnimation:q,queueBoundaryAnimation:Qe,consumeBoundaryAnimation:_e,registerBoundary:ke,getBoundaryOverride:be,refreshModuleManifest:N,resetAllForks:J},children:n})}function G(){let e=ht.useContext(Gt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ne(e){return G().forks[e]}var Fe=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 yt(e,t){let r;try{r=ht.Children.only(e);}catch{let o=ht.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 qt=new Set;function Jt(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 on(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(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(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yt(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 Xt(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 c=0;c<e.length;c++){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=Yt(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group,v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function an(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:a,borderRadius:d}of e){let f=a.left,c=a.top,F=a.width,P=a.height,x=Math.min(d,F/2,P/2),v=Yt(f,c,F,P,x),y=document.createElementNS(t,"path");y.setAttribute("d",v),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.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 ln(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 cn=ht__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return Br.jsx("div",{ref:r,style:n,children:Br.jsx(t,{...o})})},(e,t)=>e.component===t.component&&ln(e.hostProps,t.hostProps)),mt=class extends ht__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 Zt({slotId:e,children:t,githubRepo:r,shared:n,events:o}){yt(t,e);let i=Ne(e),{baseUrl:s,apiKey:a,appId:d,shouldSkipAnimation:f}=G(),[c,F]=ht.useState(null),P=ht.useRef(null),x=ht.useRef(null),v=ht.useRef(null),y=ht.useRef(false),h=ht.useRef(null),C=ht.useRef(null),R=!!(n||o),T=ht.useRef(null);R&&!T.current&&(T.current=new Fe(e));let $=ht.useRef(o);if($.current=o,ht.useEffect(()=>{if(R)return ()=>{T.current?.destroy(),T.current=null;}},[R,e]),R&&T.current&&n)for(let[E,S]of Object.entries(n))T.current.set(E,S);ht.useEffect(()=>{if(!R)return;T.current||(T.current=new Fe(e));let E=T.current,S=Object.keys($.current||{}).map(u=>E.on(u,(...p)=>$.current?.[u]?.(...p)));return ()=>S.forEach(u=>u())},[R,e]),ht.useEffect(()=>{if(qt.has(e))return;qt.add(e);let E={id:e,appId:d,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 ${a}`,"Content-Type":"application/json"},body:JSON.stringify(E)}).catch(()=>{});},[e,s,a,r,d]);let M=i?.id||null;ht.useEffect(()=>{if(i?.bundleUrl,P.current,x.current,!i?.bundleUrl||!M){return}let E=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,u=sessionStorage.getItem(S),p=f(e),g=!p&&u!==M;if(p&&M&&sessionStorage.setItem(S,M),g&&x.current){let D=Jt(x.current);v.current=D,y.current=true,`${e}${D.length}`;}window.__FORK_REACT__=ht__namespace.default,window.__FORK_REACT_DOM__=Or__namespace,window.__FORK_REACT_JSX__=Br__namespace;let I=Date.now(),z=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${I}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=z,Y.dataset.forkSlot=e,document.head.appendChild(Y);let H=document.createElement("script");return H.src=E+"?t="+I,H.onload=()=>{let D=window.__FORK_EXPORT__;if(D?.default){if(x.current&&v.current&&y.current){let V=x.current.getBoundingClientRect(),N=x.current.cloneNode(true);N.style.position="fixed",N.style.top=`${V.top}px`,N.style.left=`${V.left}px`,N.style.width=`${V.width}px`,N.style.height=`${V.height}px`,N.style.flex="none",N.style.minHeight="auto",N.style.zIndex="9998",N.style.pointerEvents="none",N.style.overflow="hidden";let Q=getComputedStyle(x.current).backgroundColor;N.style.backgroundColor=Q&&Q!=="rgba(0, 0, 0, 0)"&&Q!=="transparent"?Q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(N);let ee=x.current.querySelectorAll("*"),ie=N.querySelectorAll("*");for(let q=0;q<ee.length;q++)ee[q].scrollTop!==0&&(ie[q].scrollTop=ee[q].scrollTop),ee[q].scrollLeft!==0&&(ie[q].scrollLeft=ee[q].scrollLeft);h.current=N;}F(()=>D.default),P.current=M;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},H.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(H),()=>{H.remove(),Y.remove(),C.current&&(clearTimeout(C.current),C.current=null),h.current&&(h.current.remove(),h.current=null);}},[M,s,e]),ht.useEffect(()=>{if(!y.current||!c||!x.current){`${e}${y.current}`,x.current;return}let E=v.current;if(!E){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!x.current)return;let S=Jt(x.current),u=on(E,S),p=sn(E,S),g=h.current;if(`${e}${u.length}${p.length}`,p.length>0&&g){let I=an(p);C.current=setTimeout(()=>{C.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),h.current=null,u.length>0&&(Xt(u));},z);},3500);}else g&&(g.remove(),h.current=null),u.length>0&&(Xt(u));v.current=null,y.current=false,M&&(sessionStorage.setItem(`__fork_animated_${e}`,M),`${e}`);});});},[c]);let w={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Br.jsx("div",{ref:x,style:w,children:t});if(!c)return Br.jsx("div",{ref:x,style:w,children:t});let l=t?.props??{};return Br.jsx(mt,{slotId:e,resetKey:M,fallback:Br.jsx("div",{ref:x,style:w,children:t}),children:Br.jsx(cn,{component:c,containerRef:x,wrapperStyle:w,hostProps:l})})}var er=new Set;function fn(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 ht.Children.forEach(e,r=>{if(!ht.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 pn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:d}){if(yt(r,e),s==="direct")return Br.jsx(Zt,{slotId:e,githubRepo:o,shared:a,events:d,children:r});let f=Ne(e),{baseUrl:c,apiKey:F,appId:P}=G(),x=ht.useRef(null),v=ht.useRef(false),y=ht.useRef(null),h=ht.useRef(i);h.current=i;let C=ht.useRef(t);C.current=t;let R=ht.useRef(n);R.current=n,ht.useEffect(()=>{if(typeof process<"u")return;let w=tr(r),k=new Set(i?Object.keys(i):[]),l=[...w].filter(E=>!k.has(E));l.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
2
  `+l.map(E=>` - ${E}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),kt.useEffect(()=>{nr.has(e)||(nr.add(e),fetch(`${c}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${x}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:T,label:e,propsShape:t?mn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,c,x,o,T]);let I=kt.useCallback(R=>{let h=F.current;if(h?.contentWindow&&v.current){let l=k.current?Object.keys(k.current):[];h.contentWindow.postMessage({type:"slot:props",props:R,callbackNames:l},"*"),y.current=null;}else y.current=R;},[]),$=kt.useCallback((R,h)=>{let l=w.current;return !l||l.length===0?false:l.some(E=>{let[S,u]=E.split(" "),p=h.split("?")[0];return R.toUpperCase()===S.toUpperCase()&&p.startsWith(u)})},[]);if(kt.useEffect(()=>{if(!g?.bundleUrl)return;let R=async h=>{if(h.source===F.current?.contentWindow){if(h.data?.type==="slot:ready")v.current=true,F.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:w.current||[]},"*"),w.current,y.current?I(y.current):I(C.current||{});else if(h.data?.type==="slot:event"){let l=h.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(h.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(h.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(h.data?.type==="slot:callback"){let{name:l,args:E}=h.data,S=k.current?.[l];S?(S(...E||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(h.data?.type==="slot:fetch"){let{id:l,method:E,url:S,body:u}=h.data,p=F.current?.contentWindow;if(!p)return;let m=E||"GET";if(!$(m,S)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${m} ${S} \u2014 not in allowedFetches`),p.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${m} ${S}`},"*");return}try{let M={method:m};u&&m!=="GET"&&(M.headers={"Content-Type":"application/json"},M.body=JSON.stringify(u));let z=await fetch(S,M),Y=await z.json();`${e}${l}${z.status}`,p.postMessage({type:"slot:fetch-response",id:l,data:Y,status:z.status},"*");}catch(M){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,M.message),p.postMessage({type:"slot:fetch-response",id:l,error:M.message},"*");}}}};return window.addEventListener("message",R),()=>{window.removeEventListener("message",R),v.current=false;}},[g?.bundleUrl,e,I,$]),kt.useEffect(()=>{g?.bundleUrl&&v.current&&I(t||{});},[t,g?.bundleUrl,I]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,Dr.jsx(Dr.Fragment,{children:r});`${e}${g.bundleUrl}`;let A=`${c}${g.bundleUrl.replace("/bundle.js","/host")}`;return Dr.jsx("iframe",{ref:F,src:A,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Ke({style:e={width:20,height:20},...t}){return Dr.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Dr.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"}),Dr.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Dr.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"}),Dr.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"}),Dr.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"})]})}function vt({onClick:e}){let[t,r]=kt.useState(false),[n,o]=kt.useState(false),i=t?48:40;return Dr.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:Dr.jsx(Ke,{style:{width:24,height:24}})})}var En={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},$n={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},_n={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},An={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function xt(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 fr({events:e}){let t=kt.useRef(null);return kt.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Dr.jsxs(Dr.Fragment,{children:[Dr.jsx("style",{children:`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),ht.useEffect(()=>{er.has(e)||(er.add(e),fetch(`${c}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?fn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,c,F,o,P]);let T=ht.useCallback(w=>{let k=x.current;if(k?.contentWindow&&v.current){let l=h.current?Object.keys(h.current):[];k.contentWindow.postMessage({type:"slot:props",props:w,callbackNames:l},"*"),y.current=null;}else y.current=w;},[]),$=ht.useCallback((w,k)=>{let l=R.current;return !l||l.length===0?false:l.some(E=>{let[S,u]=E.split(" "),p=k.split("?")[0];return w.toUpperCase()===S.toUpperCase()&&p.startsWith(u)})},[]);if(ht.useEffect(()=>{if(!f?.bundleUrl)return;let w=async k=>{if(k.source===x.current?.contentWindow){if(k.data?.type==="slot:ready")v.current=true,x.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,y.current?T(y.current):T(C.current||{});else if(k.data?.type==="slot:event"){let l=k.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(k.data?.type==="slot:callback"){let{name:l,args:E}=k.data,S=h.current?.[l];S?(S(...E||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(k.data?.type==="slot:fetch"){let{id:l,method:E,url:S,body:u}=k.data,p=x.current?.contentWindow;if(!p)return;let g=E||"GET";if(!$(g,S)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${g} ${S} \u2014 not in allowedFetches`),p.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${g} ${S}`},"*");return}try{let I={method:g};u&&g!=="GET"&&(I.headers={"Content-Type":"application/json"},I.body=JSON.stringify(u));let z=await fetch(S,I),Y=await z.json();`${e}${l}${z.status}`,p.postMessage({type:"slot:fetch-response",id:l,data:Y,status:z.status},"*");}catch(I){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,I.message),p.postMessage({type:"slot:fetch-response",id:l,error:I.message},"*");}}}};return window.addEventListener("message",w),()=>{window.removeEventListener("message",w),v.current=false;}},[f?.bundleUrl,e,T,$]),ht.useEffect(()=>{f?.bundleUrl&&v.current&&T(t||{});},[t,f?.bundleUrl,T]),!f||f.status!=="complete"||!f.bundleUrl)return `${e}${f?.status||"none"}${f?.bundleUrl||"none"}`,Br.jsx(Br.Fragment,{children:r});`${e}${f.bundleUrl}`;let M=`${c}${f.bundleUrl.replace("/bundle.js","/host")}`;return Br.jsx("iframe",{ref:x,src:M,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function je({style:e={width:20,height:20},...t}){return Br.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Br.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"}),Br.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Br.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"}),Br.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"}),Br.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"})]})}function bt({onClick:e}){let[t,r]=ht.useState(false),[n,o]=ht.useState(false),i=t?48:40;return Br.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:Br.jsx(je,{style:{width:24,height:24}})})}var xn={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},Fn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Rn={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},En={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function vt(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 cr({events:e}){let t=ht.useRef(null);return ht.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Br.jsxs(Br.Fragment,{children:[Br.jsx("style",{children:`
4
4
  @keyframes __fork-spin {
5
5
  from { transform: rotate(0deg); }
6
6
  to { transform: rotate(360deg); }
@@ -18,7 +18,7 @@
18
18
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
19
  background: rgba(255, 255, 255, 0.3);
20
20
  }
21
- `}),Dr.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&&Dr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Dr.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"),a=En[r.type]||lucideReact.Code,f=$n[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");a=_n[g]||lucideReact.Wrench,f=An[g]||"#fbbf24";}return s?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,f="#4ade80"),Dr.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Dr.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Dr.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:xt(r)})]},n)})]})]})}var On=["Dark mode redesign","New workflow for adding to this page","Data-dense analytics view"],hr=35,Bn="Working on Feature",Hn="Built Custom Feature",yr=360,qe=350;function Nn(e){return e.length<=hr?e:e.slice(0,hr-3).trimEnd()+"..."}function Dn({events:e}){let[t,r]=kt.useState("Setting up environment..."),[n,o]=kt.useState(true),i=kt.useRef(t),s=kt.useRef(false);return kt.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 a="Setting up environment...";if(s.current)for(let f=e.length-1;f>=0;f--){let g=e[f];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){a=Nn(xt(g));break}}if(a!==i.current){o(false);let f=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(f)}},[e]),Dr.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 jn({children:e}){let[t,r]=kt.useState(null);return kt.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?Nr.createPortal(e,t):null}function Je({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",examplePrompts:f=On,onSubmit:g,onUndo:c,onClose:x,baseUrl:T,apiKey:F,userId:v,userHash:y,appId:k,embedded:C=false}){let[w,I]=kt.useState(""),[$,A]=kt.useState([]),[R,h]=kt.useState(false),[l,E]=kt.useState(false),[S,u]=kt.useState(false),[p,m]=kt.useState(false),[M,z]=kt.useState(false),[Y,H]=kt.useState(false),[j,Z]=kt.useState(false),[N,te]=kt.useState(null),[J,ie]=kt.useState(false),[K,$e]=kt.useState(false),[ke,_e]=kt.useState(null),[rt,Ae]=kt.useState(false),[_,b]=kt.useState([]),[U,G]=kt.useState(null),[re,Mt]=kt.useState(false),[pe,Pe]=kt.useState(false),[Pr,It]=kt.useState(false),[Cr,Lt]=kt.useState(null),[ge,Ut]=kt.useState(null),Ce=kt.useRef(null),Te=kt.useRef(null),{resetAllForks:Tr,previewSession:Me,currentContainerId:Mr}=V(),Ie=Me?.container_id??Mr,Ot=!!Me,ne=ge!==null,Bt=kt.useRef(x);kt.useEffect(()=>{Bt.current=x;});let nt=kt.useRef(null),Le=kt.useRef(false),Ht=typeof window<"u"&&"documentPictureInPicture"in window,Ir=async()=>{if(!(!Ht||ne))try{let d=await window.documentPictureInPicture.requestWindow({width:yr,height:640});d.document.body.style.margin="0",d.document.body.style.padding="0",d.document.body.style.height="100vh",d.document.body.style.overflow="hidden",d.document.body.style.background="#ffffff";try{let L=document.adoptedStyleSheets??[];L.length>0&&(d.document.adoptedStyleSheets=[...L]);}catch{}d.addEventListener("pagehide",()=>{nt.current=null,Ut(null),Le.current||Bt.current(),Le.current=!1;},{once:!0}),nt.current=d,Ut(d);}catch(d){console.warn("[Fork] PiP open failed:",d);}},Lr=()=>{ge&&(Le.current=true,ge.close());};kt.useEffect(()=>()=>{Le.current=true,nt.current?.close();},[]);let oe=i??o??"",Ue=(s||oe).replace(/[-_]+/g," ").replace(/\b\w/g,d=>d.toUpperCase()),ot=kt.useRef(""),Oe=C?true:l&&!S,Ur=r.find(d=>{let L=d.data;return d.type==="status"&&L.summary})?.data?.summary||t?.summary||Bn,le=r.find(d=>{let L=d.data;return (d.type==="status"||d.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;kt.useEffect(()=>{if(a==="none"){h(true);return}if(!T||!F||!v||!oe||R||!re)return;let d=new URLSearchParams({userId:v});if(y&&d.set("userHash",y),U&&d.set("containerId",U),a==="slot")d.set("slotId",oe);else if(a==="boundary"){if(!k){h(true);return}d.set("boundaryId",oe),d.set("appId",k);}fetch(`${T}/api/v1/forks/history?${d.toString()}`,{headers:{Authorization:`Bearer ${F}`}}).then(L=>L.ok?L.json():[]).then(L=>{let O=[];for(let He of L)He.role==="user"?O.push({type:"user",text:He.content}):O.push({type:"applied",text:He.content});A(O),h(true);}).catch(()=>h(true));},[F,k,T,R,a,oe,y,v,U,re]),kt.useEffect(()=>{e==="complete"&&ie(false);},[e]),kt.useEffect(()=>{if(C&&a==="none"){b([]),G(null),Mt(true);return}Ie?(b([{id:Ie,name:Ot?Me?.container_name||"Preview container":"Primary container",createdAt:""}]),G(Ie)):(b([]),G(null)),Mt(true);},[Ie,C,a,Ot,Me?.container_name]);let Be=kt.useRef(void 0);kt.useEffect(()=>{if(re){if(Be.current===void 0){Be.current=U;return}Be.current!==U&&(Be.current=U,A([]),h(false));}},[U,re]);let st=kt.useRef(null);kt.useEffect(()=>{if(!pe)return;let d=O=>{st.current&&(st.current.contains(O.target)||Pe(false));},L=O=>{O.key==="Escape"&&Pe(false);};return document.addEventListener("mousedown",d,true),document.addEventListener("keydown",L,true),()=>{document.removeEventListener("mousedown",d,true),document.removeEventListener("keydown",L,true);}},[pe]),kt.useEffect(()=>{if(C)return;let d=requestAnimationFrame(()=>E(true));return ()=>cancelAnimationFrame(d)},[C]),kt.useEffect(()=>{let d=C||ne;if((d||Oe)&&(e==="prompting"||e==="complete")){let L=setTimeout(()=>Ce.current?.focus(),d?100:qe+100);return ()=>clearTimeout(L)}},[Oe,C,ne,e]),kt.useEffect(()=>{if(e==="complete"&&ot.current){let L=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||Hn;A(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:L}]),I(""),setTimeout(()=>Ce.current?.focus(),200);}},[e,Ue,r,t?.summary]),kt.useEffect(()=>{Te.current&&(Te.current.scrollTop=Te.current.scrollHeight);},[$,e]);let Nt=()=>{w.trim()&&(ot.current=w.trim(),A(d=>[...d,{type:"user",text:w.trim()}]),g(w.trim(),oe,U),I(""));},Or=async()=>{if(!(!c||K||!oe)){$e(true);try{let d=await c(oe);A(L=>{let O=[...L];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),d?.removed&&A([]);}catch{}finally{$e(false);}}},it=()=>{if(C){x();return}if(ne){ge?.close();return}u(true),E(false),setTimeout(()=>x(),qe);},Br=C||ne?{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:yr,maxWidth:"100vw",background:"#ffffff",boxShadow:Oe?"-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:Oe?"translateX(0)":"translateX(100%)",transition:`transform ${qe}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${qe}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},at=Dr.jsxs(Dr.Fragment,{children:[Dr.jsx("style",{children:`
21
+ `}),Br.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&&Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Br.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"),a=xn[r.type]||lucideReact.Code,d=Fn[r.type]||"#9ca3af";if(r.type==="tool_use"){let f=String(r.data.category||"");a=Rn[f]||lucideReact.Wrench,d=En[f]||"#fbbf24";}return s?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,d="#4ade80"),Br.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Br.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:d,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Br.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:vt(r)})]},n)})]})]})}var pr=35,In="Working on Feature",Ln="Built Custom Feature",gr=360,Ke=350;function Un(e){return e.length<=pr?e:e.slice(0,pr-3).trimEnd()+"..."}function On({events:e}){let[t,r]=ht.useState("Setting up environment..."),[n,o]=ht.useState(true),i=ht.useRef(t),s=ht.useRef(false);return ht.useEffect(()=>{if(!s.current){for(let d of e)if(d.type==="status"&&String(d.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let d=e.length-1;d>=0;d--){let f=e[d];if(f.type==="tool_use"||f.type==="build_start"||f.type==="build_complete"){a=Un(vt(f));break}}if(a!==i.current){o(false);let d=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(d)}},[e]),Br.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 Bn({children:e}){let[t,r]=ht.useState(null);return ht.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?Or.createPortal(e,t):null}function Ge({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:d,onUndo:f,onClose:c,baseUrl:F,apiKey:P,userId:x,userHash:v,appId:y,embedded:h=false}){let[C,R]=ht.useState(""),[T,$]=ht.useState([]),[M,w]=ht.useState(false),[k,l]=ht.useState(false),[E,S]=ht.useState(false),[u,p]=ht.useState(false),[g,I]=ht.useState(false),[z,Y]=ht.useState(false),[H,D]=ht.useState(false),[V,N]=ht.useState(false),[Q,ee]=ht.useState(false),[ie,q]=ht.useState(null),[Qe,_e]=ht.useState(false),[ke,be]=ht.useState([]),[J,_]=ht.useState(null),[b,O]=ht.useState(false),[W,ae]=ht.useState(false),[$r,Ct]=ht.useState(false),[_r,Tt]=ht.useState(null),[ge,Mt]=ht.useState(null),et=ht.useRef(null),Ae=ht.useRef(null),{resetAllForks:Ar,previewSession:Pe,currentContainerId:Pr}=G(),Ce=Pe?.container_id??Pr,It=!!Pe,ne=ge!==null,Lt=ht.useRef(c);ht.useEffect(()=>{Lt.current=c;});let tt=ht.useRef(null),Te=ht.useRef(false),Ut=typeof window<"u"&&"documentPictureInPicture"in window,Cr=async()=>{if(!(!Ut||ne))try{let m=await window.documentPictureInPicture.requestWindow({width:gr,height:640});m.document.body.style.margin="0",m.document.body.style.padding="0",m.document.body.style.height="100vh",m.document.body.style.overflow="hidden",m.document.body.style.background="#ffffff";try{let L=document.adoptedStyleSheets??[];L.length>0&&(m.document.adoptedStyleSheets=[...L]);}catch{}m.addEventListener("pagehide",()=>{tt.current=null,Mt(null),Te.current||Lt.current(),Te.current=!1;},{once:!0}),tt.current=m,Mt(m);}catch(m){console.warn("[Fork] PiP open failed:",m);}},Tr=()=>{ge&&(Te.current=true,ge.close());};ht.useEffect(()=>()=>{Te.current=true,tt.current?.close();},[]);let oe=i??o??"",Me=(s||oe).replace(/[-_]+/g," ").replace(/\b\w/g,m=>m.toUpperCase()),rt=ht.useRef(""),Ie=h?true:k&&!E,Mr=r.find(m=>{let L=m.data;return m.type==="status"&&L.summary})?.data?.summary||t?.summary||In,ce=r.find(m=>{let L=m.data;return (m.type==="status"||m.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;ht.useEffect(()=>{if(a==="none"){w(true);return}if(!F||!P||!x||!oe||M||!b)return;let m=new URLSearchParams({userId:x});if(v&&m.set("userHash",v),J&&m.set("containerId",J),a==="slot")m.set("slotId",oe);else if(a==="boundary"){if(!y){w(true);return}m.set("boundaryId",oe),m.set("appId",y);}fetch(`${F}/api/v1/forks/history?${m.toString()}`,{headers:{Authorization:`Bearer ${P}`}}).then(L=>L.ok?L.json():[]).then(L=>{let U=[];for(let Ue of L)Ue.role==="user"?U.push({type:"user",text:Ue.content}):U.push({type:"applied",text:Ue.content});$(U),w(true);}).catch(()=>w(true));},[P,y,F,M,a,oe,v,x,J,b]),ht.useEffect(()=>{e==="complete"&&N(false);},[e]),ht.useEffect(()=>{if(h&&a==="none"){be([]),_(null),O(true);return}Ce?(be([{id:Ce,name:It?Pe?.container_name||"Preview container":"Primary container",createdAt:""}]),_(Ce)):(be([]),_(null)),O(true);},[Ce,h,a,It,Pe?.container_name]);let Le=ht.useRef(void 0);ht.useEffect(()=>{if(b){if(Le.current===void 0){Le.current=J;return}Le.current!==J&&(Le.current=J,$([]),w(false));}},[J,b]);let nt=ht.useRef(null);ht.useEffect(()=>{if(!W)return;let m=U=>{nt.current&&(nt.current.contains(U.target)||ae(false));},L=U=>{U.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",m,true),document.addEventListener("keydown",L,true),()=>{document.removeEventListener("mousedown",m,true),document.removeEventListener("keydown",L,true);}},[W]),ht.useEffect(()=>{if(h)return;let m=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(m)},[h]),ht.useEffect(()=>{let m=h||ne;if((m||Ie)&&(e==="prompting"||e==="complete")){let L=setTimeout(()=>et.current?.focus(),m?100:Ke+100);return ()=>clearTimeout(L)}},[Ie,h,ne,e]),ht.useEffect(()=>{if(e==="complete"&&rt.current){let L=r.find(U=>U.type==="complete")?.data?.summary||t?.summary||Ln;$(U=>U[U.length-1]?.type==="applied"?U:[...U,{type:"applied",text:L}]),R(""),setTimeout(()=>et.current?.focus(),200);}},[e,Me,r,t?.summary]),ht.useEffect(()=>{Ae.current&&(Ae.current.scrollTop=Ae.current.scrollHeight);},[T,e]);let Ot=()=>{C.trim()&&(rt.current=C.trim(),$(m=>[...m,{type:"user",text:C.trim()}]),d(C.trim(),oe,J),R(""));},Ir=async()=>{if(!(!f||Q||!oe)){ee(true);try{let m=await f(oe);$(L=>{let U=[...L];return U.length>=2&&U[U.length-1]?.type==="applied"?U.splice(-2,2):U.length>=1&&U[U.length-1]?.type==="applied"&&U.splice(-1,1),U}),m?.removed&&$([]);}catch{}finally{ee(false);}}},ot=()=>{if(h){c();return}if(ne){ge?.close();return}S(true),l(false),setTimeout(()=>c(),Ke);},Lr=h||ne?{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:gr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ie?"-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:Ie?"translateX(0)":"translateX(100%)",transition:`transform ${Ke}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Ke}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},st=Br.jsxs(Br.Fragment,{children:[Br.jsx("style",{children:`
22
22
  @keyframes __fork-pulse {
23
23
  0%, 100% { opacity: 1; }
24
24
  50% { opacity: 0.5; }
@@ -40,5 +40,5 @@
40
40
  scrollbar-width: thin;
41
41
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
42
  }
43
- `}),Dr.jsxs("div",{className:"__fork-panel",style:Br,children:[Dr.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:[Dr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Dr.jsx(Ke,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async d=>{if(d.stopPropagation(),!rt&&confirm("Reset all forks? This will remove all forked components.")){Ae(true);try{let L=await Tr();`${L?.deleted??0}`,A([]),I(""),ie(!1),it();}catch(L){console.error("[Fork] Reset failed:",L);}finally{Ae(false);}}}}),e==="running"?Dr.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Ur}):_.length===0?Dr.jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Ue]}):Dr.jsxs("div",{ref:st,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Dr.jsxs("button",{type:"button",onClick:()=>{Pe(d=>!d);},onMouseEnter:()=>It(true),onMouseLeave:()=>It(false),"aria-haspopup":"menu","aria-expanded":pe,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Pr||pe?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Dr.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:_.find(d=>d.id===U)?.name??(re?`Fork ${Ue}`:"Loading\u2026")}),Dr.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),pe&&Dr.jsx("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:_.map(d=>{let L=d.id===U,O=Cr===d.id;return Dr.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Lt(d.id),onMouseLeave:()=>Lt(null),onClick:()=>{Pe(false),d.id!==U&&G(d.id);},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:"pointer",textAlign:"left",fontWeight:L?600:400},children:[Dr.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:L&&Dr.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Dr.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.name})]},d.id)})})]}),e==="running"&&Dr.jsx("span",{title:le?`Estimated ~${le} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:le?"#1c4587":"#9ca3af",backgroundColor:le?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:le?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:le?`~${le}m`:"~ m"}),e==="complete"&&Dr.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!C&&Dr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Ht&&Dr.jsx("button",{onClick:ne?Lr:Ir,onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),title:ne?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:M?"#4b5563":"#9ca3af",backgroundColor:M?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ne?Dr.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Dr.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Dr.jsx("button",{onClick:it,onMouseEnter:()=>m(true),onMouseLeave:()=>m(false),style:{padding:6,borderRadius:6,color:p?"#4b5563":"#9ca3af",backgroundColor:p?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Dr.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),Dr.jsxs("div",{ref:Te,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&$.length===0&&Dr.jsxs("div",{style:{padding:"24px 20px",textAlign:"center"},children:[Dr.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."}),Dr.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"},children:f.map((d,L)=>Dr.jsx("button",{onClick:()=>{I(d),Ce.current?.focus();},onMouseEnter:()=>te(L),onMouseLeave:()=>te(null),style:{fontSize:12,padding:"5px 12px",borderRadius:9999,color:N===L?"#1f2937":"#6b7280",backgroundColor:N===L?"#f9fafb":"transparent",border:N===L?"1px solid #d1d5db":"1px solid #e5e7eb",cursor:"pointer",transition:"color 0.15s, background-color 0.15s, border-color 0.15s",fontFamily:"inherit"},children:d},d))})]}),$.length>0&&Dr.jsx("div",{style:{padding:"16px 16px 0 16px"},children:$.map((d,L)=>Dr.jsx("div",{style:{marginBottom:L<$.length-1?10:0},children:d.type==="user"?Dr.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Dr.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Dr.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Dr.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:d.text})]}):Dr.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Dr.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Dr.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Dr.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:[Dr.jsx("span",{style:{flex:1},children:d.text}),c&&L===$.length-1&&e!=="running"&&Dr.jsxs("button",{onClick:O=>{O.stopPropagation(),Or();},onMouseEnter:()=>_e(L),onMouseLeave:()=>_e(null),disabled:K,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ke===L?"rgba(0,0,0,0.06)":"transparent",color:ke===L?"#6b7280":"#d1d5db",cursor:K?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:K?.4:1,flexShrink:0},children:[Dr.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ke===L&&Dr.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"})]})]})]})},L))}),e==="running"&&Dr.jsx("div",{style:{padding:16},children:Dr.jsxs("div",{onClick:()=>ie(!J),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Dr.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Dr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Dr.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:Dr.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Dr.jsx(Dn,{events:r})]}),Dr.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:J?"rotate(180deg)":"rotate(0deg)"},children:Dr.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Dr.jsx("div",{style:{maxHeight:J?320:0,opacity:J?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Dr.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Dr.jsx(fr,{events:r})})})]})}),e==="error"&&Dr.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Dr.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Dr.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Dr.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),Dr.jsxs("button",{onClick:()=>{let d=t?.prompt||ot.current;d&&g(d,oe);},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:j?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Dr.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Dr.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Dr.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:[Dr.jsx("textarea",{ref:Ce,value:w,onChange:d=>{I(d.target.value),d.target.style.height="auto",d.target.style.height=Math.min(d.target.scrollHeight,160)+"px";},onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),Nt()),d.key==="Escape"&&!C&&it();},placeholder:$.length>0?"Ask for another change...":`Describe your ideal ${Ue.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"}}),Dr.jsx("button",{onClick:Nt,disabled:!w.trim(),onMouseEnter:()=>H(true),onMouseLeave:()=>H(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:w.trim()?1:.25,transform:Y&&w.trim()?"scale(1.1)":"scale(1)",background:w.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:w.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Dr.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return C?at:ne&&ge?Nr.createPortal(at,ge.document.body):Dr.jsx(jn,{children:at})}function br(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 Ft(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:f}=V(),[g,c]=kt.useState("idle"),[x,T]=kt.useState(null),[F,v]=kt.useState([]),[y,k]=kt.useState(null),C=kt.useRef(null),w=kt.useCallback(()=>{c("prompting"),v([]),k(null),T(null);},[]),I=kt.useCallback(()=>{c("idle"),C.current&&(C.current.close(),C.current=null);},[]);kt.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&c(R=>R==="idle"?"prompting":R);},[s?.preview_session_id,s?.target.id,e]);let $=kt.useCallback(async(R,h)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");c("running"),v([]),k(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...X()},body:JSON.stringify({prompt:R,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let M=await u.json().catch(()=>({}));throw new Error(M.error||`API error: ${u.status}`)}let p=await u.json();we(p.fork_id),l=await(await fetch(`${o}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...X()}})).json();}else {let u={userId:r,prompt:R,boundaryId:e,appId:i};h&&(u.containerId=h),n&&(u.userHash=n);let p=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!p.ok){let m=await p.json().catch(()=>({}));throw new Error(m.error||`API error: ${p.status}`)}l=await p.json();}T(l);let E=new URLSearchParams({key:t});n&&(E.set("userId",r),E.set("userHash",n));let S=new EventSource(`${o}/api/v1/forks/${l.id}/events?${E.toString()}`);C.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(v(m=>[...m,p]),p.type==="complete"){let m=p.data;f(e,l.id),a().catch(()=>{}).finally(()=>{let M={...l,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};T(M),c("complete"),S.close();});}else if(p.type==="error"){let m=p.data;k(m.error||"Unknown error"),c("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{T(u),u.status==="complete"?(f(e,u.id),a().catch(()=>{}),c("complete")):u.status==="error"&&(k(u.error||"Fork generation failed"),c("error"));}).catch(()=>{k("Connection lost"),c("error");}),S.close();};}catch(l){k(l.message),c("error");}},[t,i,o,e,s,f,a,n,r]),A=kt.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let R={userId:r,boundaryId:e,appId:i};n&&(R.userHash=n);let h=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(R)});if(!h.ok){let E=await h.json().catch(()=>({}));throw new Error(E.error||`API error: ${h.status}`)}let l=await h.json();return await a().catch(()=>{}),l.removed?(T(null),c("prompting")):l.fork&&(T(l.fork),c("complete")),l}catch(R){throw k(R.message),R}},[t,i,o,e,a,n,r]);return {state:g,fork:x,events:F,error:y,open:w,close:I,startFork:$,undoFork:A}}function wr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:f}=Ft(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:f}}function Rt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=V(),[f,g]=kt.useState("idle"),[c,x]=kt.useState(null),[T,F]=kt.useState([]),[v,y]=kt.useState(null),k=kt.useRef(null),C=kt.useCallback(()=>{g("prompting"),F([]),y(null),x(null);},[]),w=kt.useCallback(()=>{g("idle"),k.current&&(k.current.close(),k.current=null);},[]);kt.useEffect(()=>{o&&o.target.kind==="slot"&&g(A=>A==="idle"?"prompting":A);},[o?.preview_session_id,o?.target.kind]);let I=kt.useCallback(async(A,R,h)=>{try{g("running"),F([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...X()},body:JSON.stringify({prompt:A,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let M=await u.json().catch(()=>({}));throw new Error(M.error||`API error: ${u.status}`)}let p=await u.json();we(p.fork_id),l=await(await fetch(`${n}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...X()}})).json();}else {let u={userId:t,prompt:A};R&&(u.slotId=R),h&&(u.containerId=h),r&&(u.userHash=r);let p=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!p.ok){let m=await p.json().catch(()=>({}));throw new Error(m.error||`API error: ${p.status}`)}l=await p.json();}x(l);let E=new URLSearchParams({key:e});r&&(E.set("userId",t),E.set("userHash",r));let S=new EventSource(`${n}/api/v1/forks/${l.id}/events?${E.toString()}`);k.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(F(m=>[...m,p]),p.type==="complete"){let m=p.data,M={...l,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};x(M),g("complete"),R&&m.bundleUrl&&i(R,M),S.close();}else if(p.type==="error"){let m=p.data;y(m.error||"Unknown error"),g("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{x(u),u.status==="complete"?(g("complete"),R&&u.bundleUrl&&i(R,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),g("error"));}).catch(()=>{y("Connection lost"),g("error");}),S.close();};}catch(l){y(l.message),g("error");}},[e,t,r,n,o,i]),$=kt.useCallback(async A=>{try{let R={userId:t,slotId:A};r&&(R.userHash=r);let h=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(R)});if(!h.ok){let E=await h.json().catch(()=>({}));throw new Error(E.error||`API error: ${h.status}`)}let l=await h.json();return a(A),l.removed?(s(A),x(null),g("prompting")):l.fork&&(i(A,l.fork),x(l.fork)),l}catch(R){throw y(R.message),R}},[e,t,r,n,s,i]);return {state:f,fork:c,events:T,error:v,open:C,close:w,startFork:I,undoFork:$}}function vr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=Rt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Et(e){let t=br(e),r=vr(),n=wr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}=V(),g=t.type==="slot"?r:n,c=t.type==="slot"?"slot":"boundary",x=t.id,T=t.title,F=kt.useCallback((y,k,C)=>t.type==="slot"?r.submit(y,k??t.id,C):n.submit(y,C),[n,r,t]),v=kt.useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:x,targetLabel:T,historyMode:c,submit:F,undo:v,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:x,targetLabel:T,historyMode:c}:{targetId:x,targetLabel:T,historyMode:c},onSubmit:F,onUndo:v,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}}}function Ee(e){let{examplePrompts:t,embedded:r}=e,n=Et(e);return r?Dr.jsx(Je,{...n.panelProps,examplePrompts:t,embedded:true}):n.isOpen?Dr.jsx(Je,{...n.panelProps,examplePrompts:t}):Dr.jsx(vt,{...n.buttonProps})}function qn({boundaryId:e,title:t,examplePrompts:r}){return Dr.jsx(Ee,{boundaryId:e,title:t,examplePrompts:r})}function _t(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 xr(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 At(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 Fr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Rr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Er(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 Pt(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 c=0;c<e.length;c+=1){let{rect:x,borderRadius:T}=e[c],F=x.left-.5,v=x.top-.5,y=x.width+1,k=x.height+1,C=Math.min(T+.5,y/2,k/2),w=Er(F,v,y,k,C),I=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",I),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let A=document.createElementNS(t,"feGaussianBlur");A.setAttribute("in","SourceGraphic"),A.setAttribute("stdDeviation","8"),$.appendChild(A),o.appendChild($);let R=`__fork-mask-${c}`,h=document.createElementNS(t,"mask");h.setAttribute("id",R),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(F-200)),h.setAttribute("y",String(v-200)),h.setAttribute("width",String(y+400)),h.setAttribute("height",String(k+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(F-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(k+400)),l.setAttribute("fill","white"),h.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",w),E.setAttribute("fill","black"),h.appendChild(E),o.appendChild(h);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${R})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${I})`);let p=document.createElementNS(t,"path");p.setAttribute("d",w),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let m=document.createElementNS(t,"path");m.setAttribute("d",w),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(p,m),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let x=i[c],T=i[c+1],F=x.__group;if(!F)continue;let v=T.getTotalLength(),y=x.getTotalLength();if(v<=0)continue;let k=v*.35;T.setAttribute("stroke-dasharray",`${k} ${v-k}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;x.setAttribute("stroke-dasharray",`${C} ${y-C}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(F.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",f);},g=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function $r(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:a,borderRadius:f}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Er(a.left,a.top,a.width,a.height,f)),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 tt=new Map,Ct=new Map;function Yn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Ar(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 Zn(e){if(!e||typeof document>"u")return Promise.resolve();let t=tt.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),i();},f=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",f,{once:true});});return tt.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 tt.delete(e),o});return tt.set(e,n),n}function Qn(e){let t=Ct.get(e);if(t)return t;let r=import(e).catch(n=>{throw Ct.delete(e),n});return Ct.set(e,r),r}async function eo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Zn(i)));let o=await Qn(e.moduleUrl);return Ar(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 Ar(n,r)}function to(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:f,consumeBoundaryAnimation:g}=V(),[c,x]=kt.useState(null),[T,F]=kt.useState(null),v=kt.useRef(null),y=kt.useRef(null),k=kt.useRef(null),C=kt.useRef(false),w=kt.useRef(null),I=kt.useRef(null),$=f(e.id),A=$?`override:${$.id}`:"original",R=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(kt.useEffect(()=>()=>{I.current&&(clearTimeout(I.current),I.current=null),w.current&&(w.current.remove(),w.current=null);},[]),kt.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,R]),kt.useEffect(()=>{if(o&&!i&&!c||y.current===A&&c)return;let h=false;return F(null),eo($,e.original,e.exportName).then(l=>{if(!h){if($?.id&&g(e.id,$.id)&&v.current){let E=_t(v.current);if(E){let S=At(E);S.length>0&&(k.current=S,C.current=true,I.current&&(clearTimeout(I.current),I.current=null),w.current&&w.current.remove(),w.current=xr(E));}}y.current=A,kt.startTransition(()=>{x(()=>l);});}}).catch(l=>{h||F(Yn(l));}),()=>{h=true;}},[g,A,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,c]),kt.useEffect(()=>{if(!C.current||!c||!v.current)return;let h=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(h||!v.current)return;let l=k.current,E=_t(v.current);if(k.current=null,C.current=false,!l||!E){w.current&&(w.current.remove(),w.current=null);return}let S=At(E),u=Fr(l,S),p=Rr(l,S),m=w.current;if(p.length>0&&m){let M=$r(p);I.current=setTimeout(()=>{I.current=null;let z=400;m.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),M.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{m.remove(),M.remove(),w.current===m&&(w.current=null),u.length>0&&Pt(u);},z);},3500);}else m&&(m.remove(),w.current===m&&(w.current=null)),u.length>0&&Pt(u);});}),()=>{h=true;}},[c]),T)throw T;return c?Dr.jsx("div",{ref:v,style:{display:"contents"},children:Dr.jsx(c,{...r})}):Dr.jsx(Dr.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function no({slotId:e,title:t,slotLabel:r,examplePrompts:n}){return Dr.jsx(Ee,{slotId:e,title:t,slotLabel:r,examplePrompts:n})}
44
- exports.ForkBoundaryUI=qn;exports.ForkButton=vt;exports.ForkChatInterface=Ee;exports.ForkPanel=Je;exports.ForkProvider=rn;exports.ForkSlot=hn;exports.ForkUI=no;exports.clearCachedManifest=Yr;exports.forkable=to;exports.loadManifest=je;exports.manifestDiffers=Zr;exports.readCachedManifest=Jr;exports.registerForkShared=ct;exports.useBoundaryFork=Ft;exports.useFork=Rt;exports.useForkChatPanel=Et;exports.usePreviewSession=De;exports.writeCachedManifest=Xr;
43
+ `}),Br.jsxs("div",{className:"__fork-panel",style:Lr,children:[Br.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:[Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Br.jsx(je,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async m=>{if(m.stopPropagation(),!Qe&&confirm("Reset all forks? This will remove all forked components.")){_e(true);try{let L=await Ar();`${L?.deleted??0}`,$([]),R(""),N(!1),ot();}catch(L){console.error("[Fork] Reset failed:",L);}finally{_e(false);}}}}),e==="running"?Br.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Mr}):ke.length===0?Br.jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Me]}):Br.jsxs("div",{ref:nt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Br.jsxs("button",{type:"button",onClick:()=>{ae(m=>!m);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(false),"aria-haspopup":"menu","aria-expanded":W,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:$r||W?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Br.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ke.find(m=>m.id===J)?.name??(b?`Fork ${Me}`:"Loading\u2026")}),Br.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:W?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),W&&Br.jsx("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:ke.map(m=>{let L=m.id===J,U=_r===m.id;return Br.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Tt(m.id),onMouseLeave:()=>Tt(null),onClick:()=>{ae(false),m.id!==J&&_(m.id);},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:U?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:"pointer",textAlign:"left",fontWeight:L?600:400},children:[Br.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:L&&Br.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Br.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]},m.id)})})]}),e==="running"&&Br.jsx("span",{title:ce?`Estimated ~${ce} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ce?"#1c4587":"#9ca3af",backgroundColor:ce?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ce?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ce?`~${ce}m`:"~ m"}),e==="complete"&&Br.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!h&&Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Ut&&Br.jsx("button",{onClick:ne?Tr:Cr,onMouseEnter:()=>I(true),onMouseLeave:()=>I(false),title:ne?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:g?"#4b5563":"#9ca3af",backgroundColor:g?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ne?Br.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Br.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Br.jsx("button",{onClick:ot,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Br.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),Br.jsxs("div",{ref:Ae,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&T.length===0&&Br.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:Br.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."})}),T.length>0&&Br.jsx("div",{style:{padding:"16px 16px 0 16px"},children:T.map((m,L)=>Br.jsx("div",{style:{marginBottom:L<T.length-1?10:0},children:m.type==="user"?Br.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Br.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Br.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Br.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:m.text})]}):Br.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Br.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Br.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Br.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:[Br.jsx("span",{style:{flex:1},children:m.text}),f&&L===T.length-1&&e!=="running"&&Br.jsxs("button",{onClick:U=>{U.stopPropagation(),Ir();},onMouseEnter:()=>q(L),onMouseLeave:()=>q(null),disabled:Q,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ie===L?"rgba(0,0,0,0.06)":"transparent",color:ie===L?"#6b7280":"#d1d5db",cursor:Q?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:Q?.4:1,flexShrink:0},children:[Br.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ie===L&&Br.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"})]})]})]})},L))}),e==="running"&&Br.jsx("div",{style:{padding:16},children:Br.jsxs("div",{onClick:()=>N(!V),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Br.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Br.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:Br.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Br.jsx(On,{events:r})]}),Br.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:Br.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Br.jsx("div",{style:{maxHeight:V?320:0,opacity:V?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Br.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Br.jsx(cr,{events:r})})})]})}),e==="error"&&Br.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Br.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Br.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Br.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),Br.jsxs("button",{onClick:()=>{let m=t?.prompt||rt.current;m&&d(m,oe);},onMouseEnter:()=>D(true),onMouseLeave:()=>D(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:[Br.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Br.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Br.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:[Br.jsx("textarea",{ref:et,value:C,onChange:m=>{R(m.target.value),m.target.style.height="auto",m.target.style.height=Math.min(m.target.scrollHeight,160)+"px";},onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),Ot()),m.key==="Escape"&&!h&&ot();},placeholder:T.length>0?"Ask for another change...":`Describe your ideal ${Me.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"}}),Br.jsx("button",{onClick:Ot,disabled:!C.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:C.trim()?1:.25,transform:z&&C.trim()?"scale(1.1)":"scale(1)",background:C.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:C.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Br.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return h?st:ne&&ge?Or.createPortal(st,ge.document.body):Br.jsx(Bn,{children:st})}function hr(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 St(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:d}=G(),[f,c]=ht.useState("idle"),[F,P]=ht.useState(null),[x,v]=ht.useState([]),[y,h]=ht.useState(null),C=ht.useRef(null),R=ht.useCallback(()=>{c("prompting"),v([]),h(null),P(null);},[]),T=ht.useCallback(()=>{c("idle"),C.current&&(C.current.close(),C.current=null);},[]);ht.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&c(w=>w==="idle"?"prompting":w);},[s?.preview_session_id,s?.target.id,e]);let $=ht.useCallback(async(w,k)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");c("running"),v([]),h(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...Z()},body:JSON.stringify({prompt:w,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${o}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...Z()}})).json();}else {let u={userId:r,prompt:w,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n);let p=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}P(l);let E=new URLSearchParams({key:t});n&&(E.set("userId",r),E.set("userHash",n));let S=new EventSource(`${o}/api/v1/forks/${l.id}/events?${E.toString()}`);C.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(v(g=>[...g,p]),p.type==="complete"){let g=p.data;d(e,l.id),a().catch(()=>{}).finally(()=>{let I={...l,status:"complete",moduleUrl:g.moduleUrl,cssUrls:g.cssUrls,summary:g.summary,completedAt:new Date().toISOString()};P(I),c("complete"),S.close();});}else if(p.type==="error"){let g=p.data;h(g.error||"Unknown error"),c("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(d(e,u.id),a().catch(()=>{}),c("complete")):u.status==="error"&&(h(u.error||"Fork generation failed"),c("error"));}).catch(()=>{h("Connection lost"),c("error");}),S.close();};}catch(l){h(l.message),c("error");}},[t,i,o,e,s,d,a,n,r]),M=ht.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let w={userId:r,boundaryId:e,appId:i};n&&(w.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return await a().catch(()=>{}),l.removed?(P(null),c("prompting")):l.fork&&(P(l.fork),c("complete")),l}catch(w){throw h(w.message),w}},[t,i,o,e,a,n,r]);return {state:f,fork:F,events:x,error:y,open:R,close:T,startFork:$,undoFork:M}}function yr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:d}=St(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:d}}function xt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=G(),[d,f]=ht.useState("idle"),[c,F]=ht.useState(null),[P,x]=ht.useState([]),[v,y]=ht.useState(null),h=ht.useRef(null),C=ht.useCallback(()=>{f("prompting"),x([]),y(null),F(null);},[]),R=ht.useCallback(()=>{f("idle"),h.current&&(h.current.close(),h.current=null);},[]);ht.useEffect(()=>{o&&o.target.kind==="slot"&&f(M=>M==="idle"?"prompting":M);},[o?.preview_session_id,o?.target.kind]);let T=ht.useCallback(async(M,w,k)=>{try{f("running"),x([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...Z()},body:JSON.stringify({prompt:M,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${n}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...Z()}})).json();}else {let u={userId:t,prompt:M};w&&(u.slotId=w),k&&(u.containerId=k),r&&(u.userHash=r);let p=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}F(l);let E=new URLSearchParams({key:e});r&&(E.set("userId",t),E.set("userHash",r));let S=new EventSource(`${n}/api/v1/forks/${l.id}/events?${E.toString()}`);h.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(x(g=>[...g,p]),p.type==="complete"){let g=p.data,I={...l,status:"complete",bundleUrl:g.bundleUrl,summary:g.summary,completedAt:new Date().toISOString()};F(I),f("complete"),w&&g.bundleUrl&&i(w,I),S.close();}else if(p.type==="error"){let g=p.data;y(g.error||"Unknown error"),f("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{F(u),u.status==="complete"?(f("complete"),w&&u.bundleUrl&&i(w,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),f("error"));}).catch(()=>{y("Connection lost"),f("error");}),S.close();};}catch(l){y(l.message),f("error");}},[e,t,r,n,o,i]),$=ht.useCallback(async M=>{try{let w={userId:t,slotId:M};r&&(w.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return a(M),l.removed?(s(M),F(null),f("prompting")):l.fork&&(i(M,l.fork),F(l.fork)),l}catch(w){throw y(w.message),w}},[e,t,r,n,s,i]);return {state:d,fork:c,events:P,error:v,open:C,close:R,startFork:T,undoFork:$}}function kr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=xt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Ft(e){let t=hr(e),r=kr(),n=yr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}=G(),f=t.type==="slot"?r:n,c=t.type==="slot"?"slot":"boundary",F=t.id,P=t.title,x=ht.useCallback((y,h,C)=>t.type==="slot"?r.submit(y,h??t.id,C):n.submit(y,C),[n,r,t]),v=ht.useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...f,target:t,targetId:F,targetLabel:P,historyMode:c,submit:x,undo:v,buttonProps:{onClick:f.open},panelProps:{state:f.state,fork:f.fork,events:f.events,error:f.error,...t.type==="slot"?{slotId:F,targetLabel:P,historyMode:c}:{targetId:F,targetLabel:P,historyMode:c},onSubmit:x,onUndo:v,onClose:f.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}}}function $e(e){let{embedded:t}=e,r=Ft(e);return t?Br.jsx(Ge,{...r.panelProps,embedded:true}):r.isOpen?Br.jsx(Ge,{...r.panelProps}):Br.jsx(bt,{...r.buttonProps})}function Wn({boundaryId:e,title:t}){return Br.jsx($e,{boundaryId:e,title:t})}function Et(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 wr(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 $t(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 vr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Sr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function xr(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 _t(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 c=0;c<e.length;c+=1){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=xr(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group;if(!x)continue;let v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function Fr(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:a,borderRadius:d}of e){let f=document.createElementNS(t,"path");f.setAttribute("d",xr(a.left,a.top,a.width,a.height,d)),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),f.setAttribute("stroke-width","1.5"),f.setAttribute("stroke-dasharray","8 4"),f.setAttribute("stroke-linecap","round"),f.setAttribute("filter","url(#__fork-removed-shadow)"),f.setAttribute("opacity","0"),n.appendChild(f),f.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var Ze=new Map,At=new Map;function Vn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Er(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 qn(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ze.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 a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),i();},d=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",d,{once:true});});return Ze.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 Ze.delete(e),o});return Ze.set(e,n),n}function Jn(e){let t=At.get(e);if(t)return t;let r=import(e).catch(n=>{throw At.delete(e),n});return At.set(e,r),r}async function Xn(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>qn(i)));let o=await Jn(e.moduleUrl);return Er(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 Er(n,r)}function Yn(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:d,consumeBoundaryAnimation:f}=G(),[c,F]=ht.useState(null),[P,x]=ht.useState(null),v=ht.useRef(null),y=ht.useRef(null),h=ht.useRef(null),C=ht.useRef(false),R=ht.useRef(null),T=ht.useRef(null),$=d(e.id),M=$?`override:${$.id}`:"original",w=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(ht.useEffect(()=>()=>{T.current&&(clearTimeout(T.current),T.current=null),R.current&&(R.current.remove(),R.current=null);},[]),ht.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,w]),ht.useEffect(()=>{if(o&&!i&&!c||y.current===M&&c)return;let k=false;return x(null),Xn($,e.original,e.exportName).then(l=>{if(!k){if($?.id&&f(e.id,$.id)&&v.current){let E=Et(v.current);if(E){let S=$t(E);S.length>0&&(h.current=S,C.current=true,T.current&&(clearTimeout(T.current),T.current=null),R.current&&R.current.remove(),R.current=wr(E));}}y.current=M,ht.startTransition(()=>{F(()=>l);});}}).catch(l=>{k||x(Vn(l));}),()=>{k=true;}},[f,M,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,c]),ht.useEffect(()=>{if(!C.current||!c||!v.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!v.current)return;let l=h.current,E=Et(v.current);if(h.current=null,C.current=false,!l||!E){R.current&&(R.current.remove(),R.current=null);return}let S=$t(E),u=vr(l,S),p=Sr(l,S),g=R.current;if(p.length>0&&g){let I=Fr(p);T.current=setTimeout(()=>{T.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),R.current===g&&(R.current=null),u.length>0&&_t(u);},z);},3500);}else g&&(g.remove(),R.current===g&&(R.current=null)),u.length>0&&_t(u);});}),()=>{k=true;}},[c]),P)throw P;return c?Br.jsx("div",{ref:v,style:{display:"contents"},children:Br.jsx(c,{...r})}):Br.jsx(Br.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Qn({slotId:e,title:t,slotLabel:r}){return Br.jsx($e,{slotId:e,title:t,slotLabel:r})}
44
+ exports.ForkBoundaryUI=Wn;exports.ForkButton=bt;exports.ForkChatInterface=$e;exports.ForkPanel=Ge;exports.ForkProvider=Qr;exports.ForkSlot=pn;exports.ForkUI=Qn;exports.clearCachedManifest=qr;exports.forkable=Yn;exports.loadManifest=He;exports.manifestDiffers=Jr;exports.readCachedManifest=Gr;exports.registerForkShared=at;exports.useBoundaryFork=St;exports.useFork=xt;exports.useForkChatPanel=Ft;exports.usePreviewSession=Be;exports.writeCachedManifest=Vr;
package/dist/index.d.cts CHANGED
@@ -87,7 +87,6 @@ type ForkChatTargetInput = {
87
87
  };
88
88
  type ForkChatPanelOptions = ForkChatTargetInput;
89
89
  type ForkChatInterfaceProps = ForkChatTargetInput & {
90
- examplePrompts?: string[];
91
90
  /**
92
91
  * When true, render the panel flat inside its container instead of as a
93
92
  * fixed-position side drawer. Suppresses the body-margin push and the
@@ -186,9 +185,8 @@ declare function ForkChatInterface(props: ForkChatInterfaceProps): react_jsx_run
186
185
  interface ForkBoundaryUIProps {
187
186
  boundaryId: string;
188
187
  title?: string;
189
- examplePrompts?: string[];
190
188
  }
191
- declare function ForkBoundaryUI({ boundaryId, title, examplePrompts }: ForkBoundaryUIProps): react_jsx_runtime.JSX.Element;
189
+ declare function ForkBoundaryUI({ boundaryId, title }: ForkBoundaryUIProps): react_jsx_runtime.JSX.Element;
192
190
 
193
191
  declare function forkable<TProps extends object>(definition: ForkBoundaryDefinition<TProps>): {
194
192
  (props: TProps): react_jsx_runtime.JSX.Element;
@@ -201,9 +199,8 @@ interface ForkUIProps {
201
199
  slotId: string;
202
200
  title?: string;
203
201
  slotLabel?: string;
204
- examplePrompts?: string[];
205
202
  }
206
- declare function ForkUI({ slotId, title, slotLabel, examplePrompts }: ForkUIProps): react_jsx_runtime.JSX.Element;
203
+ declare function ForkUI({ slotId, title, slotLabel }: ForkUIProps): react_jsx_runtime.JSX.Element;
207
204
 
208
205
  declare function ForkButton({ onClick }: {
209
206
  onClick?: () => void;
@@ -218,7 +215,6 @@ interface ForkPanelProps {
218
215
  targetId?: string;
219
216
  targetLabel?: string;
220
217
  historyMode?: "slot" | "boundary" | "none";
221
- examplePrompts?: string[];
222
218
  onSubmit: (prompt: string, targetId: string, containerId?: string | null) => void;
223
219
  onUndo?: (targetId: string) => Promise<any>;
224
220
  onClose: () => void;
@@ -235,7 +231,7 @@ interface ForkPanelProps {
235
231
  */
236
232
  embedded?: boolean;
237
233
  }
238
- declare function ForkPanel({ state, fork, events, error, slotId, targetId, targetLabel, historyMode, examplePrompts, onSubmit, onUndo, onClose, baseUrl, apiKey, userId, userHash, appId, embedded, }: ForkPanelProps): react_jsx_runtime.JSX.Element;
234
+ declare function ForkPanel({ state, fork, events, error, slotId, targetId, targetLabel, historyMode, onSubmit, onUndo, onClose, baseUrl, apiKey, userId, userHash, appId, embedded, }: ForkPanelProps): react_jsx_runtime.JSX.Element;
239
235
 
240
236
  declare function useFork(): {
241
237
  state: ForkState;
package/dist/index.d.ts CHANGED
@@ -87,7 +87,6 @@ type ForkChatTargetInput = {
87
87
  };
88
88
  type ForkChatPanelOptions = ForkChatTargetInput;
89
89
  type ForkChatInterfaceProps = ForkChatTargetInput & {
90
- examplePrompts?: string[];
91
90
  /**
92
91
  * When true, render the panel flat inside its container instead of as a
93
92
  * fixed-position side drawer. Suppresses the body-margin push and the
@@ -186,9 +185,8 @@ declare function ForkChatInterface(props: ForkChatInterfaceProps): react_jsx_run
186
185
  interface ForkBoundaryUIProps {
187
186
  boundaryId: string;
188
187
  title?: string;
189
- examplePrompts?: string[];
190
188
  }
191
- declare function ForkBoundaryUI({ boundaryId, title, examplePrompts }: ForkBoundaryUIProps): react_jsx_runtime.JSX.Element;
189
+ declare function ForkBoundaryUI({ boundaryId, title }: ForkBoundaryUIProps): react_jsx_runtime.JSX.Element;
192
190
 
193
191
  declare function forkable<TProps extends object>(definition: ForkBoundaryDefinition<TProps>): {
194
192
  (props: TProps): react_jsx_runtime.JSX.Element;
@@ -201,9 +199,8 @@ interface ForkUIProps {
201
199
  slotId: string;
202
200
  title?: string;
203
201
  slotLabel?: string;
204
- examplePrompts?: string[];
205
202
  }
206
- declare function ForkUI({ slotId, title, slotLabel, examplePrompts }: ForkUIProps): react_jsx_runtime.JSX.Element;
203
+ declare function ForkUI({ slotId, title, slotLabel }: ForkUIProps): react_jsx_runtime.JSX.Element;
207
204
 
208
205
  declare function ForkButton({ onClick }: {
209
206
  onClick?: () => void;
@@ -218,7 +215,6 @@ interface ForkPanelProps {
218
215
  targetId?: string;
219
216
  targetLabel?: string;
220
217
  historyMode?: "slot" | "boundary" | "none";
221
- examplePrompts?: string[];
222
218
  onSubmit: (prompt: string, targetId: string, containerId?: string | null) => void;
223
219
  onUndo?: (targetId: string) => Promise<any>;
224
220
  onClose: () => void;
@@ -235,7 +231,7 @@ interface ForkPanelProps {
235
231
  */
236
232
  embedded?: boolean;
237
233
  }
238
- declare function ForkPanel({ state, fork, events, error, slotId, targetId, targetLabel, historyMode, examplePrompts, onSubmit, onUndo, onClose, baseUrl, apiKey, userId, userHash, appId, embedded, }: ForkPanelProps): react_jsx_runtime.JSX.Element;
234
+ declare function ForkPanel({ state, fork, events, error, slotId, targetId, targetLabel, historyMode, onSubmit, onUndo, onClose, baseUrl, apiKey, userId, userHash, appId, embedded, }: ForkPanelProps): react_jsx_runtime.JSX.Element;
239
235
 
240
236
  declare function useFork(): {
241
237
  state: ForkState;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as kt from'react';import kt__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Nr from'react-dom';import {createPortal}from'react-dom';import*as Dr from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as jr from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X as X$1,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var ce="__FORK_SHARED__";function lt(){var t,r,n,o;let e=globalThis;return e[ce]||(e[ce]={}),(t=e[ce]).react||(t.react=kt),(r=e[ce])["react-dom"]||(r["react-dom"]=Nr),(n=e[ce])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Dr),(o=e[ce])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=jr),e[ce]}function ct(e){return Object.assign(lt(),e)}var zr="__fork_preview_session__";function Ne(e){return `${zr}${e}`}var W={apiKey:null,session:null},ut=new Set;function dt(){for(let e of ut)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Dt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Wr(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Ne(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Dt(r)?(window.sessionStorage.removeItem(Ne(e)),null):r}catch{return null}}function jt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Ne(e),JSON.stringify(t)):window.sessionStorage.removeItem(Ne(e));}catch{}}function be(e){W.apiKey!==e&&(W.apiKey=e,W.session=Wr(e),dt());}function ue(){return W.session?Dt(W.session)?(ft(null),null):W.session:null}function ft(e){W.session=e,W.apiKey&&jt(W.apiKey,e),dt();}function we(e){W.session&&W.session.fork_id!==e&&(W.session={...W.session,fork_id:e},W.apiKey&&jt(W.apiKey,W.session),dt());}function pt(e){return ut.add(e),()=>{ut.delete(e);}}var zt="__fork_preview";function Wt(){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(zt);return typeof r=="string"&&r.length>0?r:null}function gt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return Gt()!==null}function Kt(){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(zt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var de=null;function Gt(){if(de)return de;let e=Wt();return e?(de=e,Kt(),de):null}async function mt(e,t){be(e);let r=ue();if(r)return de=null,r;let n=de??Wt();if(de=null,!n)return null;Kt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let 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,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ft(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function Gr(){return ue()}function Vr(){return null}function De(){return useSyncExternalStore(pt,Gr,Vr)}function X(){let e=ue();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function je(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[a,f]of Object.entries(i.modules)){let g=f.moduleUrl??f.bundleUrl??null,c=f.legacyModuleUrl??f.legacyBundleUrl??null;s[a]={forkId:f.forkId,moduleUrl:g,legacyModuleUrl:c,bundleUrl:f.bundleUrl??g,legacyBundleUrl:f.legacyBundleUrl??c,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 qr="fork:manifest:v1";function ht(e,t,r){return `${qr}:${e}:${t}:${r}`}function Jr(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(ht(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Xr(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(ht(e,t,r),JSON.stringify(n));}catch{}}function Yr(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(ht(e,t,r));}catch{}}function Zr(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,a]of r){let f=t.slots[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let f=t.modules[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}return false}var Jt=createContext(null);function Se(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function tn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Se(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Se(e,i)):[]};return r}function Vt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Se(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function qt(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:Se(e,i),cssUrls:(o.cssUrls??[]).map(s=>Se(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function rn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[f]=useState(()=>(be(t),gt(t))),[g,c]=useState({}),[x,T]=useState(s?{userId:s,userHash:void 0}:null),[F,v]=useState(!!s||f),[y,k]=useState({}),[C,w]=useState(!o),[I,$]=useState(0),[A,R]=useState(null),h=useRef(new Map),l=useRef(new Map),[E,S]=useState(0),u=useRef(new Set),p=useRef(new Map),m=useRef(void 0);lt(),useEffect(()=>{return mt(t,r).then(()=>{}),()=>{}},[]);let M=De();i&&m.current!==i&&(ct(i),m.current=i),useEffect(()=>{a&&(f||(v(false),fetch(a,{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");T({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{v(true);})));},[a,f]),useEffect(()=>{!a&&s&&(T({userId:s,userHash:void 0}),v(true));},[s,a]);let z=x?.userId??"",Y=x?.userHash,H=M?M.target_user_id:z,j=M?void 0:Y,Z=!!o,N=useCallback(async()=>{if(!Z){R(null),k({}),w(true),$(b=>b+1);return}if(!F){w(false);return}if(!H||!o){R(null),k({}),w(true),$(b=>b+1);return}if(w(false),!M){try{let b=await je({baseUrl:r,apiKey:t,appId:o,userId:H,userHash:j});b&&(R(b.containerId),c(Vt(r,b,H,o)),k(qt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch fork manifest:",b.message),R(null),c({}),k({});}finally{$(b=>b+1),w(true);}return}if(R(M.container_id??null),M.container_id){try{let b=await je({baseUrl:r,apiKey:t,appId:o,userId:H,containerId:M.container_id,extraHeaders:X()});b&&(c(Vt(r,b,H,o)),k(qt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch preview container manifest:",b.message),c({}),k({});}finally{$(b=>b+1),w(true);}return}let _=new URLSearchParams({appId:o,userId:H});j&&_.set("userHash",j);try{let b=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...X()}});if(!b.ok)throw new Error(`${b.status}`);let U=await b.json();k(tn(r,U));}catch(b){console.error("[ForkProvider] Failed to fetch module override manifest:",b.message),k({});}finally{$(b=>b+1),w(true);}},[t,o,r,F,Z,j,H,M?.preview_session_id,M?.fork_id,M?.container_id]);useEffect(()=>{if(!H||o&&(!M||M.container_id))return;let _=new URLSearchParams({userId:H});j&&_.set("userHash",j),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...X()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{b&&typeof b=="object"&&c(b);}).catch(()=>{});},[t,o,H,j,r,M?.preview_session_id,M?.fork_id]),useEffect(()=>{N();},[N]);let te=useCallback((_,b)=>{c(U=>({...U,[_]:b}));},[]),J=useCallback(_=>{c(b=>{let U={...b};return delete U[_],U});},[]),ie=useCallback(_=>{u.current.add(_);},[]),K=useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),$e=useCallback((_,b)=>{p.current.set(_,b);},[]),ke=useCallback((_,b)=>p.current.get(_)!==b?false:(p.current.delete(_),true),[]),_e=useCallback(_=>{if(!o)return;let b=JSON.stringify(_);h.current.get(_.id)===b||l.current.get(_.id)?.signature===b||(l.current.set(_.id,{boundary:_,signature:b}),S(G=>G+1));},[o]);useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let b=Array.from(l.current.values());b.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:b.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of b)l.current.get(U.boundary.id)?.signature===U.signature&&(l.current.delete(U.boundary.id),h.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(_);}},[t,o,r,E]);let rt=useCallback(_=>y[_],[y]),Ae=useCallback(async()=>{if(!H)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:H});j&&_.set("userHash",j);let b=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...X()}});if(!b.ok){let G=await b.json().catch(()=>({}));throw new Error(G.error||`API error: ${b.status}`)}let U=await b.json().catch(()=>({}));c({}),k({}),w(true),$(G=>G+1),u.current.clear(),p.current.clear();try{for(let G=sessionStorage.length-1;G>=0;G-=1){let re=sessionStorage.key(G);re&&re.startsWith("__fork_animated_")&&sessionStorage.removeItem(re);}}catch{}return U},[t,r,j,H]);return jsx(Jt.Provider,{value:{apiKey:t,userId:H,userHash:j,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Z,moduleManifestReady:C,moduleManifestVersion:I,currentContainerId:A,previewSession:M,setSlotFork:te,clearSlotFork:J,skipAnimationForSlot:ie,shouldSkipAnimation:K,queueBoundaryAnimation:$e,consumeBoundaryAnimation:ke,registerBoundary:_e,getBoundaryOverride:rt,refreshModuleManifest:N,resetAllForks:Ae},children:n})}function V(){let e=useContext(Jt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ze(e){return V().forks[e]}var xe=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 bt(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var Yt=new Set;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 ln(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function cn(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function er(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 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 c=0;c<e.length;c++){let{rect:x,borderRadius:T}=e[c],F=x.left-.5,v=x.top-.5,y=x.width+1,k=x.height+1,C=Math.min(T+.5,y/2,k/2),w=er(F,v,y,k,C),I=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",I),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let A=document.createElementNS(t,"feGaussianBlur");A.setAttribute("in","SourceGraphic"),A.setAttribute("stdDeviation","8"),$.appendChild(A),o.appendChild($);let R=`__fork-mask-${c}`,h=document.createElementNS(t,"mask");h.setAttribute("id",R),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(F-200)),h.setAttribute("y",String(v-200)),h.setAttribute("width",String(y+400)),h.setAttribute("height",String(k+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(F-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(k+400)),l.setAttribute("fill","white"),h.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",w),E.setAttribute("fill","black"),h.appendChild(E),o.appendChild(h);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${R})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${I})`);let p=document.createElementNS(t,"path");p.setAttribute("d",w),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let m=document.createElementNS(t,"path");m.setAttribute("d",w),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(p,m),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let x=i[c],T=i[c+1],F=x.__group,v=T.getTotalLength(),y=x.getTotalLength();if(v<=0)continue;let k=v*.35;T.setAttribute("stroke-dasharray",`${k} ${v-k}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;x.setAttribute("stroke-dasharray",`${C} ${y-C}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(F.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",f);},g=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function un(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:a,borderRadius:f}of e){let g=a.left,c=a.top,x=a.width,T=a.height,F=Math.min(f,x/2,T/2),v=er(g,c,x,T,F),y=document.createElementNS(t,"path");y.setAttribute("d",v),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.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 dn(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 fn=kt__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&dn(e.hostProps,t.hostProps)),yt=class extends kt__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 tr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){bt(t,e);let i=ze(e),{baseUrl:s,apiKey:a,appId:f,shouldSkipAnimation:g}=V(),[c,x]=useState(null),T=useRef(null),F=useRef(null),v=useRef(null),y=useRef(false),k=useRef(null),C=useRef(null),w=!!(n||o),I=useRef(null);w&&!I.current&&(I.current=new xe(e));let $=useRef(o);if($.current=o,useEffect(()=>{if(w)return ()=>{I.current?.destroy(),I.current=null;}},[w,e]),w&&I.current&&n)for(let[E,S]of Object.entries(n))I.current.set(E,S);useEffect(()=>{if(!w)return;I.current||(I.current=new xe(e));let E=I.current,S=Object.keys($.current||{}).map(u=>E.on(u,(...p)=>$.current?.[u]?.(...p)));return ()=>S.forEach(u=>u())},[w,e]),useEffect(()=>{if(Yt.has(e))return;Yt.add(e);let E={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 ${a}`,"Content-Type":"application/json"},body:JSON.stringify(E)}).catch(()=>{});},[e,s,a,r,f]);let A=i?.id||null;useEffect(()=>{if(i?.bundleUrl,T.current,F.current,!i?.bundleUrl||!A){return}let E=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,u=sessionStorage.getItem(S),p=g(e),m=!p&&u!==A;if(p&&A&&sessionStorage.setItem(S,A),m&&F.current){let j=Zt(F.current);v.current=j,y.current=true,`${e}${j.length}`;}window.__FORK_REACT__=kt__default,window.__FORK_REACT_DOM__=Nr,window.__FORK_REACT_JSX__=Dr;let M=Date.now(),z=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${M}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=z,Y.dataset.forkSlot=e,document.head.appendChild(Y);let H=document.createElement("script");return H.src=E+"?t="+M,H.onload=()=>{let j=window.__FORK_EXPORT__;if(j?.default){if(F.current&&v.current&&y.current){let Z=F.current.getBoundingClientRect(),N=F.current.cloneNode(true);N.style.position="fixed",N.style.top=`${Z.top}px`,N.style.left=`${Z.left}px`,N.style.width=`${Z.width}px`,N.style.height=`${Z.height}px`,N.style.flex="none",N.style.minHeight="auto",N.style.zIndex="9998",N.style.pointerEvents="none",N.style.overflow="hidden";let te=getComputedStyle(F.current).backgroundColor;N.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(N);let J=F.current.querySelectorAll("*"),ie=N.querySelectorAll("*");for(let K=0;K<J.length;K++)J[K].scrollTop!==0&&(ie[K].scrollTop=J[K].scrollTop),J[K].scrollLeft!==0&&(ie[K].scrollLeft=J[K].scrollLeft);k.current=N;}x(()=>j.default),T.current=A;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},H.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(H),()=>{H.remove(),Y.remove(),C.current&&(clearTimeout(C.current),C.current=null),k.current&&(k.current.remove(),k.current=null);}},[A,s,e]),useEffect(()=>{if(!y.current||!c||!F.current){`${e}${y.current}`,F.current;return}let E=v.current;if(!E){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!F.current)return;let S=Zt(F.current),u=ln(E,S),p=cn(E,S),m=k.current;if(`${e}${u.length}${p.length}`,p.length>0&&m){let M=un(p);C.current=setTimeout(()=>{C.current=null;let z=400;m.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),M.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{m.remove(),M.remove(),k.current=null,u.length>0&&(Qt(u));},z);},3500);}else m&&(m.remove(),k.current=null),u.length>0&&(Qt(u));v.current=null,y.current=false,A&&(sessionStorage.setItem(`__fork_animated_${e}`,A),`${e}`);});});},[c]);let R={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:F,style:R,children:t});if(!c)return jsx("div",{ref:F,style:R,children:t});let l=t?.props??{};return jsx(yt,{slotId:e,resetKey:A,fallback:jsx("div",{ref:F,style:R,children:t}),children:jsx(fn,{component:c,containerRef:F,wrapperStyle:R,hostProps:l})})}var nr=new Set;function mn(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 or(e,t=new Set){return Children.forEach(e,r=>{if(!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&&or(n.children,t);}),t}function hn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:f}){if(bt(r,e),s==="direct")return jsx(tr,{slotId:e,githubRepo:o,shared:a,events:f,children:r});let g=ze(e),{baseUrl:c,apiKey:x,appId:T}=V(),F=useRef(null),v=useRef(false),y=useRef(null),k=useRef(i);k.current=i;let C=useRef(t);C.current=t;let w=useRef(n);w.current=n,useEffect(()=>{if(typeof process<"u")return;let R=or(r),h=new Set(i?Object.keys(i):[]),l=[...R].filter(E=>!h.has(E));l.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:
1
+ import*as ht from'react';import ht__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Or from'react-dom';import {createPortal}from'react-dom';import*as Br from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as Hr from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var ue="__FORK_SHARED__";function it(){var t,r,n,o;let e=globalThis;return e[ue]||(e[ue]={}),(t=e[ue]).react||(t.react=ht),(r=e[ue])["react-dom"]||(r["react-dom"]=Or),(n=e[ue])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Br),(o=e[ue])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Hr),e[ue]}function at(e){return Object.assign(it(),e)}var Nr="__fork_preview_session__";function Oe(e){return `${Nr}${e}`}var K={apiKey:null,session:null},lt=new Set;function ct(){for(let e of lt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Bt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Dr(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Oe(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Bt(r)?(window.sessionStorage.removeItem(Oe(e)),null):r}catch{return null}}function Ht(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Oe(e),JSON.stringify(t)):window.sessionStorage.removeItem(Oe(e));}catch{}}function we(e){K.apiKey!==e&&(K.apiKey=e,K.session=Dr(e),ct());}function de(){return K.session?Bt(K.session)?(ut(null),null):K.session:null}function ut(e){K.session=e,K.apiKey&&Ht(K.apiKey,e),ct();}function ve(e){K.session&&K.session.fork_id!==e&&(K.session={...K.session,fork_id:e},K.apiKey&&Ht(K.apiKey,K.session),ct());}function dt(e){return lt.add(e),()=>{lt.delete(e);}}var Nt="__fork_preview";function Dt(){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(Nt);return typeof r=="string"&&r.length>0?r:null}function ft(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return zt()!==null}function jt(){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(Nt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var fe=null;function zt(){if(fe)return fe;let e=Dt();return e?(fe=e,jt(),fe):null}async function pt(e,t){we(e);let r=de();if(r)return fe=null,r;let n=fe??Dt();if(fe=null,!n)return null;jt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let 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,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ut(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function zr(){return de()}function Wr(){return null}function Be(){return useSyncExternalStore(dt,zr,Wr)}function Z(){let e=de();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 He(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[a,d]of Object.entries(i.modules)){let f=d.moduleUrl??d.bundleUrl??null,c=d.legacyModuleUrl??d.legacyBundleUrl??null;s[a]={forkId:d.forkId,moduleUrl:f,legacyModuleUrl:c,bundleUrl:d.bundleUrl??f,legacyBundleUrl:d.legacyBundleUrl??c,cssUrls:d.cssUrls??[],integrity:d.integrity,metadata:d.metadata,buildId:d.buildId,updatedAt:d.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Kr="fork:manifest:v1";function gt(e,t,r){return `${Kr}:${e}:${t}:${r}`}function Gr(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(gt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Vr(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(gt(e,t,r),JSON.stringify(n));}catch{}}function qr(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(gt(e,t,r));}catch{}}function Jr(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,a]of r){let d=t.slots[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let d=t.modules[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}return false}var Gt=createContext(null);function xe(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Zr(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:xe(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>xe(e,i)):[]};return r}function Wt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:xe(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function Kt(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:xe(e,i),cssUrls:(o.cssUrls??[]).map(s=>xe(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Qr(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[d]=useState(()=>(we(t),ft(t))),[f,c]=useState({}),[F,P]=useState(s?{userId:s,userHash:void 0}:null),[x,v]=useState(!!s||d),[y,h]=useState({}),[C,R]=useState(!o),[T,$]=useState(0),[M,w]=useState(null),k=useRef(new Map),l=useRef(new Map),[E,S]=useState(0),u=useRef(new Set),p=useRef(new Map),g=useRef(void 0);it(),useEffect(()=>{return pt(t,r).then(()=>{}),()=>{}},[]);let I=Be();i&&g.current!==i&&(at(i),g.current=i),useEffect(()=>{a&&(d||(v(false),fetch(a,{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");P({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{v(true);})));},[a,d]),useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),v(true));},[s,a]);let z=F?.userId??"",Y=F?.userHash,H=I?I.target_user_id:z,D=I?void 0:Y,V=!!o,N=useCallback(async()=>{if(!V){w(null),h({}),R(true),$(b=>b+1);return}if(!x){R(false);return}if(!H||!o){w(null),h({}),R(true),$(b=>b+1);return}if(R(false),!I){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,userHash:D});b&&(w(b.containerId),c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch fork manifest:",b.message),w(null),c({}),h({});}finally{$(b=>b+1),R(true);}return}if(w(I.container_id??null),I.container_id){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,containerId:I.container_id,extraHeaders:Z()});b&&(c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch preview container manifest:",b.message),c({}),h({});}finally{$(b=>b+1),R(true);}return}let _=new URLSearchParams({appId:o,userId:H});D&&_.set("userHash",D);try{let b=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok)throw new Error(`${b.status}`);let O=await b.json();h(Zr(r,O));}catch(b){console.error("[ForkProvider] Failed to fetch module override manifest:",b.message),h({});}finally{$(b=>b+1),R(true);}},[t,o,r,x,V,D,H,I?.preview_session_id,I?.fork_id,I?.container_id]);useEffect(()=>{if(!H||o&&(!I||I.container_id))return;let _=new URLSearchParams({userId:H});D&&_.set("userHash",D),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{b&&typeof b=="object"&&c(b);}).catch(()=>{});},[t,o,H,D,r,I?.preview_session_id,I?.fork_id]),useEffect(()=>{N();},[N]);let Q=useCallback((_,b)=>{c(O=>({...O,[_]:b}));},[]),ee=useCallback(_=>{c(b=>{let O={...b};return delete O[_],O});},[]),ie=useCallback(_=>{u.current.add(_);},[]),q=useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),Qe=useCallback((_,b)=>{p.current.set(_,b);},[]),_e=useCallback((_,b)=>p.current.get(_)!==b?false:(p.current.delete(_),true),[]),ke=useCallback(_=>{if(!o)return;let b=JSON.stringify(_);k.current.get(_.id)===b||l.current.get(_.id)?.signature===b||(l.current.set(_.id,{boundary:_,signature:b}),S(W=>W+1));},[o]);useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let b=Array.from(l.current.values());b.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:b.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of b)l.current.get(O.boundary.id)?.signature===O.signature&&(l.current.delete(O.boundary.id),k.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,E]);let be=useCallback(_=>y[_],[y]),J=useCallback(async()=>{if(!H)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:H});D&&_.set("userHash",D);let b=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok){let W=await b.json().catch(()=>({}));throw new Error(W.error||`API error: ${b.status}`)}let O=await b.json().catch(()=>({}));c({}),h({}),R(true),$(W=>W+1),u.current.clear(),p.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let ae=sessionStorage.key(W);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return O},[t,r,D,H]);return jsx(Gt.Provider,{value:{apiKey:t,userId:H,userHash:D,baseUrl:r,appId:o,forks:f,moduleOverridesEnabled:V,moduleManifestReady:C,moduleManifestVersion:T,currentContainerId:M,previewSession:I,setSlotFork:Q,clearSlotFork:ee,skipAnimationForSlot:ie,shouldSkipAnimation:q,queueBoundaryAnimation:Qe,consumeBoundaryAnimation:_e,registerBoundary:ke,getBoundaryOverride:be,refreshModuleManifest:N,resetAllForks:J},children:n})}function G(){let e=useContext(Gt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ne(e){return G().forks[e]}var Fe=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 yt(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var qt=new Set;function Jt(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 on(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(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(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yt(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 Xt(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 c=0;c<e.length;c++){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=Yt(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group,v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function an(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:a,borderRadius:d}of e){let f=a.left,c=a.top,F=a.width,P=a.height,x=Math.min(d,F/2,P/2),v=Yt(f,c,F,P,x),y=document.createElementNS(t,"path");y.setAttribute("d",v),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.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 ln(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 cn=ht__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&ln(e.hostProps,t.hostProps)),mt=class extends ht__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 Zt({slotId:e,children:t,githubRepo:r,shared:n,events:o}){yt(t,e);let i=Ne(e),{baseUrl:s,apiKey:a,appId:d,shouldSkipAnimation:f}=G(),[c,F]=useState(null),P=useRef(null),x=useRef(null),v=useRef(null),y=useRef(false),h=useRef(null),C=useRef(null),R=!!(n||o),T=useRef(null);R&&!T.current&&(T.current=new Fe(e));let $=useRef(o);if($.current=o,useEffect(()=>{if(R)return ()=>{T.current?.destroy(),T.current=null;}},[R,e]),R&&T.current&&n)for(let[E,S]of Object.entries(n))T.current.set(E,S);useEffect(()=>{if(!R)return;T.current||(T.current=new Fe(e));let E=T.current,S=Object.keys($.current||{}).map(u=>E.on(u,(...p)=>$.current?.[u]?.(...p)));return ()=>S.forEach(u=>u())},[R,e]),useEffect(()=>{if(qt.has(e))return;qt.add(e);let E={id:e,appId:d,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 ${a}`,"Content-Type":"application/json"},body:JSON.stringify(E)}).catch(()=>{});},[e,s,a,r,d]);let M=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,x.current,!i?.bundleUrl||!M){return}let E=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,u=sessionStorage.getItem(S),p=f(e),g=!p&&u!==M;if(p&&M&&sessionStorage.setItem(S,M),g&&x.current){let D=Jt(x.current);v.current=D,y.current=true,`${e}${D.length}`;}window.__FORK_REACT__=ht__default,window.__FORK_REACT_DOM__=Or,window.__FORK_REACT_JSX__=Br;let I=Date.now(),z=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${I}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=z,Y.dataset.forkSlot=e,document.head.appendChild(Y);let H=document.createElement("script");return H.src=E+"?t="+I,H.onload=()=>{let D=window.__FORK_EXPORT__;if(D?.default){if(x.current&&v.current&&y.current){let V=x.current.getBoundingClientRect(),N=x.current.cloneNode(true);N.style.position="fixed",N.style.top=`${V.top}px`,N.style.left=`${V.left}px`,N.style.width=`${V.width}px`,N.style.height=`${V.height}px`,N.style.flex="none",N.style.minHeight="auto",N.style.zIndex="9998",N.style.pointerEvents="none",N.style.overflow="hidden";let Q=getComputedStyle(x.current).backgroundColor;N.style.backgroundColor=Q&&Q!=="rgba(0, 0, 0, 0)"&&Q!=="transparent"?Q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(N);let ee=x.current.querySelectorAll("*"),ie=N.querySelectorAll("*");for(let q=0;q<ee.length;q++)ee[q].scrollTop!==0&&(ie[q].scrollTop=ee[q].scrollTop),ee[q].scrollLeft!==0&&(ie[q].scrollLeft=ee[q].scrollLeft);h.current=N;}F(()=>D.default),P.current=M;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},H.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(H),()=>{H.remove(),Y.remove(),C.current&&(clearTimeout(C.current),C.current=null),h.current&&(h.current.remove(),h.current=null);}},[M,s,e]),useEffect(()=>{if(!y.current||!c||!x.current){`${e}${y.current}`,x.current;return}let E=v.current;if(!E){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!x.current)return;let S=Jt(x.current),u=on(E,S),p=sn(E,S),g=h.current;if(`${e}${u.length}${p.length}`,p.length>0&&g){let I=an(p);C.current=setTimeout(()=>{C.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),h.current=null,u.length>0&&(Xt(u));},z);},3500);}else g&&(g.remove(),h.current=null),u.length>0&&(Xt(u));v.current=null,y.current=false,M&&(sessionStorage.setItem(`__fork_animated_${e}`,M),`${e}`);});});},[c]);let w={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:x,style:w,children:t});if(!c)return jsx("div",{ref:x,style:w,children:t});let l=t?.props??{};return jsx(mt,{slotId:e,resetKey:M,fallback:jsx("div",{ref:x,style:w,children:t}),children:jsx(cn,{component:c,containerRef:x,wrapperStyle:w,hostProps:l})})}var er=new Set;function fn(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 Children.forEach(e,r=>{if(!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 pn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:d}){if(yt(r,e),s==="direct")return jsx(Zt,{slotId:e,githubRepo:o,shared:a,events:d,children:r});let f=Ne(e),{baseUrl:c,apiKey:F,appId:P}=G(),x=useRef(null),v=useRef(false),y=useRef(null),h=useRef(i);h.current=i;let C=useRef(t);C.current=t;let R=useRef(n);R.current=n,useEffect(()=>{if(typeof process<"u")return;let w=tr(r),k=new Set(i?Object.keys(i):[]),l=[...w].filter(E=>!k.has(E));l.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
2
  `+l.map(E=>` - ${E}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{nr.has(e)||(nr.add(e),fetch(`${c}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${x}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:T,label:e,propsShape:t?mn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,c,x,o,T]);let I=useCallback(R=>{let h=F.current;if(h?.contentWindow&&v.current){let l=k.current?Object.keys(k.current):[];h.contentWindow.postMessage({type:"slot:props",props:R,callbackNames:l},"*"),y.current=null;}else y.current=R;},[]),$=useCallback((R,h)=>{let l=w.current;return !l||l.length===0?false:l.some(E=>{let[S,u]=E.split(" "),p=h.split("?")[0];return R.toUpperCase()===S.toUpperCase()&&p.startsWith(u)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let R=async h=>{if(h.source===F.current?.contentWindow){if(h.data?.type==="slot:ready")v.current=true,F.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:w.current||[]},"*"),w.current,y.current?I(y.current):I(C.current||{});else if(h.data?.type==="slot:event"){let l=h.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(h.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(h.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(h.data?.type==="slot:callback"){let{name:l,args:E}=h.data,S=k.current?.[l];S?(S(...E||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(h.data?.type==="slot:fetch"){let{id:l,method:E,url:S,body:u}=h.data,p=F.current?.contentWindow;if(!p)return;let m=E||"GET";if(!$(m,S)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${m} ${S} \u2014 not in allowedFetches`),p.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${m} ${S}`},"*");return}try{let M={method:m};u&&m!=="GET"&&(M.headers={"Content-Type":"application/json"},M.body=JSON.stringify(u));let z=await fetch(S,M),Y=await z.json();`${e}${l}${z.status}`,p.postMessage({type:"slot:fetch-response",id:l,data:Y,status:z.status},"*");}catch(M){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,M.message),p.postMessage({type:"slot:fetch-response",id:l,error:M.message},"*");}}}};return window.addEventListener("message",R),()=>{window.removeEventListener("message",R),v.current=false;}},[g?.bundleUrl,e,I,$]),useEffect(()=>{g?.bundleUrl&&v.current&&I(t||{});},[t,g?.bundleUrl,I]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let A=`${c}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:F,src:A,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Ke({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}function vt({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(Ke,{style:{width:24,height:24}})})}var En={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},$n={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},_n={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},An={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function xt(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 fr({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{er.has(e)||(er.add(e),fetch(`${c}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?fn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,c,F,o,P]);let T=useCallback(w=>{let k=x.current;if(k?.contentWindow&&v.current){let l=h.current?Object.keys(h.current):[];k.contentWindow.postMessage({type:"slot:props",props:w,callbackNames:l},"*"),y.current=null;}else y.current=w;},[]),$=useCallback((w,k)=>{let l=R.current;return !l||l.length===0?false:l.some(E=>{let[S,u]=E.split(" "),p=k.split("?")[0];return w.toUpperCase()===S.toUpperCase()&&p.startsWith(u)})},[]);if(useEffect(()=>{if(!f?.bundleUrl)return;let w=async k=>{if(k.source===x.current?.contentWindow){if(k.data?.type==="slot:ready")v.current=true,x.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,y.current?T(y.current):T(C.current||{});else if(k.data?.type==="slot:event"){let l=k.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(k.data?.type==="slot:callback"){let{name:l,args:E}=k.data,S=h.current?.[l];S?(S(...E||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(k.data?.type==="slot:fetch"){let{id:l,method:E,url:S,body:u}=k.data,p=x.current?.contentWindow;if(!p)return;let g=E||"GET";if(!$(g,S)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${g} ${S} \u2014 not in allowedFetches`),p.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${g} ${S}`},"*");return}try{let I={method:g};u&&g!=="GET"&&(I.headers={"Content-Type":"application/json"},I.body=JSON.stringify(u));let z=await fetch(S,I),Y=await z.json();`${e}${l}${z.status}`,p.postMessage({type:"slot:fetch-response",id:l,data:Y,status:z.status},"*");}catch(I){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,I.message),p.postMessage({type:"slot:fetch-response",id:l,error:I.message},"*");}}}};return window.addEventListener("message",w),()=>{window.removeEventListener("message",w),v.current=false;}},[f?.bundleUrl,e,T,$]),useEffect(()=>{f?.bundleUrl&&v.current&&T(t||{});},[t,f?.bundleUrl,T]),!f||f.status!=="complete"||!f.bundleUrl)return `${e}${f?.status||"none"}${f?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${f.bundleUrl}`;let M=`${c}${f.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:x,src:M,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function je({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}function bt({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(je,{style:{width:24,height:24}})})}var xn={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Fn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Rn={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},En={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function vt(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 cr({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
4
4
  @keyframes __fork-spin {
5
5
  from { transform: rotate(0deg); }
6
6
  to { transform: rotate(360deg); }
@@ -18,7 +18,7 @@ import*as kt from'react';import kt__default,{createContext,useSyncExternalStore,
18
18
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
19
  background: rgba(255, 255, 255, 0.3);
20
20
  }
21
- `}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,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"),a=En[r.type]||Code,f=$n[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");a=_n[g]||Wrench,f=An[g]||"#fbbf24";}return s?a=Loader2:!o&&r.type==="status"&&(a=Check,f="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:xt(r)})]},n)})]})]})}var On=["Dark mode redesign","New workflow for adding to this page","Data-dense analytics view"],hr=35,Bn="Working on Feature",Hn="Built Custom Feature",yr=360,qe=350;function Nn(e){return e.length<=hr?e:e.slice(0,hr-3).trimEnd()+"..."}function Dn({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return 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 a="Setting up environment...";if(s.current)for(let f=e.length-1;f>=0;f--){let g=e[f];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){a=Nn(xt(g));break}}if(a!==i.current){o(false);let f=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(f)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function jn({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function Je({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",examplePrompts:f=On,onSubmit:g,onUndo:c,onClose:x,baseUrl:T,apiKey:F,userId:v,userHash:y,appId:k,embedded:C=false}){let[w,I]=useState(""),[$,A]=useState([]),[R,h]=useState(false),[l,E]=useState(false),[S,u]=useState(false),[p,m]=useState(false),[M,z]=useState(false),[Y,H]=useState(false),[j,Z]=useState(false),[N,te]=useState(null),[J,ie]=useState(false),[K,$e]=useState(false),[ke,_e]=useState(null),[rt,Ae]=useState(false),[_,b]=useState([]),[U,G]=useState(null),[re,Mt]=useState(false),[pe,Pe]=useState(false),[Pr,It]=useState(false),[Cr,Lt]=useState(null),[ge,Ut]=useState(null),Ce=useRef(null),Te=useRef(null),{resetAllForks:Tr,previewSession:Me,currentContainerId:Mr}=V(),Ie=Me?.container_id??Mr,Ot=!!Me,ne=ge!==null,Bt=useRef(x);useEffect(()=>{Bt.current=x;});let nt=useRef(null),Le=useRef(false),Ht=typeof window<"u"&&"documentPictureInPicture"in window,Ir=async()=>{if(!(!Ht||ne))try{let d=await window.documentPictureInPicture.requestWindow({width:yr,height:640});d.document.body.style.margin="0",d.document.body.style.padding="0",d.document.body.style.height="100vh",d.document.body.style.overflow="hidden",d.document.body.style.background="#ffffff";try{let L=document.adoptedStyleSheets??[];L.length>0&&(d.document.adoptedStyleSheets=[...L]);}catch{}d.addEventListener("pagehide",()=>{nt.current=null,Ut(null),Le.current||Bt.current(),Le.current=!1;},{once:!0}),nt.current=d,Ut(d);}catch(d){console.warn("[Fork] PiP open failed:",d);}},Lr=()=>{ge&&(Le.current=true,ge.close());};useEffect(()=>()=>{Le.current=true,nt.current?.close();},[]);let oe=i??o??"",Ue=(s||oe).replace(/[-_]+/g," ").replace(/\b\w/g,d=>d.toUpperCase()),ot=useRef(""),Oe=C?true:l&&!S,Ur=r.find(d=>{let L=d.data;return d.type==="status"&&L.summary})?.data?.summary||t?.summary||Bn,le=r.find(d=>{let L=d.data;return (d.type==="status"||d.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){h(true);return}if(!T||!F||!v||!oe||R||!re)return;let d=new URLSearchParams({userId:v});if(y&&d.set("userHash",y),U&&d.set("containerId",U),a==="slot")d.set("slotId",oe);else if(a==="boundary"){if(!k){h(true);return}d.set("boundaryId",oe),d.set("appId",k);}fetch(`${T}/api/v1/forks/history?${d.toString()}`,{headers:{Authorization:`Bearer ${F}`}}).then(L=>L.ok?L.json():[]).then(L=>{let O=[];for(let He of L)He.role==="user"?O.push({type:"user",text:He.content}):O.push({type:"applied",text:He.content});A(O),h(true);}).catch(()=>h(true));},[F,k,T,R,a,oe,y,v,U,re]),useEffect(()=>{e==="complete"&&ie(false);},[e]),useEffect(()=>{if(C&&a==="none"){b([]),G(null),Mt(true);return}Ie?(b([{id:Ie,name:Ot?Me?.container_name||"Preview container":"Primary container",createdAt:""}]),G(Ie)):(b([]),G(null)),Mt(true);},[Ie,C,a,Ot,Me?.container_name]);let Be=useRef(void 0);useEffect(()=>{if(re){if(Be.current===void 0){Be.current=U;return}Be.current!==U&&(Be.current=U,A([]),h(false));}},[U,re]);let st=useRef(null);useEffect(()=>{if(!pe)return;let d=O=>{st.current&&(st.current.contains(O.target)||Pe(false));},L=O=>{O.key==="Escape"&&Pe(false);};return document.addEventListener("mousedown",d,true),document.addEventListener("keydown",L,true),()=>{document.removeEventListener("mousedown",d,true),document.removeEventListener("keydown",L,true);}},[pe]),useEffect(()=>{if(C)return;let d=requestAnimationFrame(()=>E(true));return ()=>cancelAnimationFrame(d)},[C]),useEffect(()=>{let d=C||ne;if((d||Oe)&&(e==="prompting"||e==="complete")){let L=setTimeout(()=>Ce.current?.focus(),d?100:qe+100);return ()=>clearTimeout(L)}},[Oe,C,ne,e]),useEffect(()=>{if(e==="complete"&&ot.current){let L=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||Hn;A(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:L}]),I(""),setTimeout(()=>Ce.current?.focus(),200);}},[e,Ue,r,t?.summary]),useEffect(()=>{Te.current&&(Te.current.scrollTop=Te.current.scrollHeight);},[$,e]);let Nt=()=>{w.trim()&&(ot.current=w.trim(),A(d=>[...d,{type:"user",text:w.trim()}]),g(w.trim(),oe,U),I(""));},Or=async()=>{if(!(!c||K||!oe)){$e(true);try{let d=await c(oe);A(L=>{let O=[...L];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),d?.removed&&A([]);}catch{}finally{$e(false);}}},it=()=>{if(C){x();return}if(ne){ge?.close();return}u(true),E(false),setTimeout(()=>x(),qe);},Br=C||ne?{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:yr,maxWidth:"100vw",background:"#ffffff",boxShadow:Oe?"-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:Oe?"translateX(0)":"translateX(100%)",transition:`transform ${qe}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${qe}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},at=jsxs(Fragment,{children:[jsx("style",{children:`
21
+ `}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,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"),a=xn[r.type]||Code,d=Fn[r.type]||"#9ca3af";if(r.type==="tool_use"){let f=String(r.data.category||"");a=Rn[f]||Wrench,d=En[f]||"#fbbf24";}return s?a=Loader2:!o&&r.type==="status"&&(a=Check,d="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:d,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:vt(r)})]},n)})]})]})}var pr=35,In="Working on Feature",Ln="Built Custom Feature",gr=360,Ke=350;function Un(e){return e.length<=pr?e:e.slice(0,pr-3).trimEnd()+"..."}function On({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let d of e)if(d.type==="status"&&String(d.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let d=e.length-1;d>=0;d--){let f=e[d];if(f.type==="tool_use"||f.type==="build_start"||f.type==="build_complete"){a=Un(vt(f));break}}if(a!==i.current){o(false);let d=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(d)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Bn({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function Ge({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:d,onUndo:f,onClose:c,baseUrl:F,apiKey:P,userId:x,userHash:v,appId:y,embedded:h=false}){let[C,R]=useState(""),[T,$]=useState([]),[M,w]=useState(false),[k,l]=useState(false),[E,S]=useState(false),[u,p]=useState(false),[g,I]=useState(false),[z,Y]=useState(false),[H,D]=useState(false),[V,N]=useState(false),[Q,ee]=useState(false),[ie,q]=useState(null),[Qe,_e]=useState(false),[ke,be]=useState([]),[J,_]=useState(null),[b,O]=useState(false),[W,ae]=useState(false),[$r,Ct]=useState(false),[_r,Tt]=useState(null),[ge,Mt]=useState(null),et=useRef(null),Ae=useRef(null),{resetAllForks:Ar,previewSession:Pe,currentContainerId:Pr}=G(),Ce=Pe?.container_id??Pr,It=!!Pe,ne=ge!==null,Lt=useRef(c);useEffect(()=>{Lt.current=c;});let tt=useRef(null),Te=useRef(false),Ut=typeof window<"u"&&"documentPictureInPicture"in window,Cr=async()=>{if(!(!Ut||ne))try{let m=await window.documentPictureInPicture.requestWindow({width:gr,height:640});m.document.body.style.margin="0",m.document.body.style.padding="0",m.document.body.style.height="100vh",m.document.body.style.overflow="hidden",m.document.body.style.background="#ffffff";try{let L=document.adoptedStyleSheets??[];L.length>0&&(m.document.adoptedStyleSheets=[...L]);}catch{}m.addEventListener("pagehide",()=>{tt.current=null,Mt(null),Te.current||Lt.current(),Te.current=!1;},{once:!0}),tt.current=m,Mt(m);}catch(m){console.warn("[Fork] PiP open failed:",m);}},Tr=()=>{ge&&(Te.current=true,ge.close());};useEffect(()=>()=>{Te.current=true,tt.current?.close();},[]);let oe=i??o??"",Me=(s||oe).replace(/[-_]+/g," ").replace(/\b\w/g,m=>m.toUpperCase()),rt=useRef(""),Ie=h?true:k&&!E,Mr=r.find(m=>{let L=m.data;return m.type==="status"&&L.summary})?.data?.summary||t?.summary||In,ce=r.find(m=>{let L=m.data;return (m.type==="status"||m.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){w(true);return}if(!F||!P||!x||!oe||M||!b)return;let m=new URLSearchParams({userId:x});if(v&&m.set("userHash",v),J&&m.set("containerId",J),a==="slot")m.set("slotId",oe);else if(a==="boundary"){if(!y){w(true);return}m.set("boundaryId",oe),m.set("appId",y);}fetch(`${F}/api/v1/forks/history?${m.toString()}`,{headers:{Authorization:`Bearer ${P}`}}).then(L=>L.ok?L.json():[]).then(L=>{let U=[];for(let Ue of L)Ue.role==="user"?U.push({type:"user",text:Ue.content}):U.push({type:"applied",text:Ue.content});$(U),w(true);}).catch(()=>w(true));},[P,y,F,M,a,oe,v,x,J,b]),useEffect(()=>{e==="complete"&&N(false);},[e]),useEffect(()=>{if(h&&a==="none"){be([]),_(null),O(true);return}Ce?(be([{id:Ce,name:It?Pe?.container_name||"Preview container":"Primary container",createdAt:""}]),_(Ce)):(be([]),_(null)),O(true);},[Ce,h,a,It,Pe?.container_name]);let Le=useRef(void 0);useEffect(()=>{if(b){if(Le.current===void 0){Le.current=J;return}Le.current!==J&&(Le.current=J,$([]),w(false));}},[J,b]);let nt=useRef(null);useEffect(()=>{if(!W)return;let m=U=>{nt.current&&(nt.current.contains(U.target)||ae(false));},L=U=>{U.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",m,true),document.addEventListener("keydown",L,true),()=>{document.removeEventListener("mousedown",m,true),document.removeEventListener("keydown",L,true);}},[W]),useEffect(()=>{if(h)return;let m=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(m)},[h]),useEffect(()=>{let m=h||ne;if((m||Ie)&&(e==="prompting"||e==="complete")){let L=setTimeout(()=>et.current?.focus(),m?100:Ke+100);return ()=>clearTimeout(L)}},[Ie,h,ne,e]),useEffect(()=>{if(e==="complete"&&rt.current){let L=r.find(U=>U.type==="complete")?.data?.summary||t?.summary||Ln;$(U=>U[U.length-1]?.type==="applied"?U:[...U,{type:"applied",text:L}]),R(""),setTimeout(()=>et.current?.focus(),200);}},[e,Me,r,t?.summary]),useEffect(()=>{Ae.current&&(Ae.current.scrollTop=Ae.current.scrollHeight);},[T,e]);let Ot=()=>{C.trim()&&(rt.current=C.trim(),$(m=>[...m,{type:"user",text:C.trim()}]),d(C.trim(),oe,J),R(""));},Ir=async()=>{if(!(!f||Q||!oe)){ee(true);try{let m=await f(oe);$(L=>{let U=[...L];return U.length>=2&&U[U.length-1]?.type==="applied"?U.splice(-2,2):U.length>=1&&U[U.length-1]?.type==="applied"&&U.splice(-1,1),U}),m?.removed&&$([]);}catch{}finally{ee(false);}}},ot=()=>{if(h){c();return}if(ne){ge?.close();return}S(true),l(false),setTimeout(()=>c(),Ke);},Lr=h||ne?{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:gr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ie?"-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:Ie?"translateX(0)":"translateX(100%)",transition:`transform ${Ke}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Ke}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},st=jsxs(Fragment,{children:[jsx("style",{children:`
22
22
  @keyframes __fork-pulse {
23
23
  0%, 100% { opacity: 1; }
24
24
  50% { opacity: 0.5; }
@@ -40,5 +40,5 @@ import*as kt from'react';import kt__default,{createContext,useSyncExternalStore,
40
40
  scrollbar-width: thin;
41
41
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
42
  }
43
- `}),jsxs("div",{className:"__fork-panel",style:Br,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx(Ke,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async d=>{if(d.stopPropagation(),!rt&&confirm("Reset all forks? This will remove all forked components.")){Ae(true);try{let L=await Tr();`${L?.deleted??0}`,A([]),I(""),ie(!1),it();}catch(L){console.error("[Fork] Reset failed:",L);}finally{Ae(false);}}}}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Ur}):_.length===0?jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Ue]}):jsxs("div",{ref:st,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{Pe(d=>!d);},onMouseEnter:()=>It(true),onMouseLeave:()=>It(false),"aria-haspopup":"menu","aria-expanded":pe,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Pr||pe?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:_.find(d=>d.id===U)?.name??(re?`Fork ${Ue}`:"Loading\u2026")}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),pe&&jsx("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:_.map(d=>{let L=d.id===U,O=Cr===d.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Lt(d.id),onMouseLeave:()=>Lt(null),onClick:()=>{Pe(false),d.id!==U&&G(d.id);},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:"pointer",textAlign:"left",fontWeight:L?600:400},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:L&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.name})]},d.id)})})]}),e==="running"&&jsx("span",{title:le?`Estimated ~${le} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:le?"#1c4587":"#9ca3af",backgroundColor:le?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:le?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:le?`~${le}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!C&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Ht&&jsx("button",{onClick:ne?Lr:Ir,onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),title:ne?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:M?"#4b5563":"#9ca3af",backgroundColor:M?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ne?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:it,onMouseEnter:()=>m(true),onMouseLeave:()=>m(false),style:{padding:6,borderRadius:6,color:p?"#4b5563":"#9ca3af",backgroundColor:p?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X$1,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:Te,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&$.length===0&&jsxs("div",{style:{padding:"24px 20px",textAlign:"center"},children:[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."}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"},children:f.map((d,L)=>jsx("button",{onClick:()=>{I(d),Ce.current?.focus();},onMouseEnter:()=>te(L),onMouseLeave:()=>te(null),style:{fontSize:12,padding:"5px 12px",borderRadius:9999,color:N===L?"#1f2937":"#6b7280",backgroundColor:N===L?"#f9fafb":"transparent",border:N===L?"1px solid #d1d5db":"1px solid #e5e7eb",cursor:"pointer",transition:"color 0.15s, background-color 0.15s, border-color 0.15s",fontFamily:"inherit"},children:d},d))})]}),$.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:$.map((d,L)=>jsx("div",{style:{marginBottom:L<$.length-1?10:0},children:d.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:d.text})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:d.text}),c&&L===$.length-1&&e!=="running"&&jsxs("button",{onClick:O=>{O.stopPropagation(),Or();},onMouseEnter:()=>_e(L),onMouseLeave:()=>_e(null),disabled:K,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ke===L?"rgba(0,0,0,0.06)":"transparent",color:ke===L?"#6b7280":"#d1d5db",cursor:K?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:K?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),ke===L&&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"})]})]})]})},L))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>ie(!J),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(Dn,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:J?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:J?320:0,opacity:J?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(fr,{events:r})})})]})}),e==="error"&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X$1,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let d=t?.prompt||ot.current;d&&g(d,oe);},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:j?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"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:[jsx("textarea",{ref:Ce,value:w,onChange:d=>{I(d.target.value),d.target.style.height="auto",d.target.style.height=Math.min(d.target.scrollHeight,160)+"px";},onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),Nt()),d.key==="Escape"&&!C&&it();},placeholder:$.length>0?"Ask for another change...":`Describe your ideal ${Ue.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"}}),jsx("button",{onClick:Nt,disabled:!w.trim(),onMouseEnter:()=>H(true),onMouseLeave:()=>H(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:w.trim()?1:.25,transform:Y&&w.trim()?"scale(1.1)":"scale(1)",background:w.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:w.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return C?at:ne&&ge?createPortal(at,ge.document.body):jsx(jn,{children:at})}function br(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 Ft(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:f}=V(),[g,c]=useState("idle"),[x,T]=useState(null),[F,v]=useState([]),[y,k]=useState(null),C=useRef(null),w=useCallback(()=>{c("prompting"),v([]),k(null),T(null);},[]),I=useCallback(()=>{c("idle"),C.current&&(C.current.close(),C.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&c(R=>R==="idle"?"prompting":R);},[s?.preview_session_id,s?.target.id,e]);let $=useCallback(async(R,h)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");c("running"),v([]),k(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...X()},body:JSON.stringify({prompt:R,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let M=await u.json().catch(()=>({}));throw new Error(M.error||`API error: ${u.status}`)}let p=await u.json();we(p.fork_id),l=await(await fetch(`${o}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...X()}})).json();}else {let u={userId:r,prompt:R,boundaryId:e,appId:i};h&&(u.containerId=h),n&&(u.userHash=n);let p=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!p.ok){let m=await p.json().catch(()=>({}));throw new Error(m.error||`API error: ${p.status}`)}l=await p.json();}T(l);let E=new URLSearchParams({key:t});n&&(E.set("userId",r),E.set("userHash",n));let S=new EventSource(`${o}/api/v1/forks/${l.id}/events?${E.toString()}`);C.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(v(m=>[...m,p]),p.type==="complete"){let m=p.data;f(e,l.id),a().catch(()=>{}).finally(()=>{let M={...l,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};T(M),c("complete"),S.close();});}else if(p.type==="error"){let m=p.data;k(m.error||"Unknown error"),c("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{T(u),u.status==="complete"?(f(e,u.id),a().catch(()=>{}),c("complete")):u.status==="error"&&(k(u.error||"Fork generation failed"),c("error"));}).catch(()=>{k("Connection lost"),c("error");}),S.close();};}catch(l){k(l.message),c("error");}},[t,i,o,e,s,f,a,n,r]),A=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let R={userId:r,boundaryId:e,appId:i};n&&(R.userHash=n);let h=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(R)});if(!h.ok){let E=await h.json().catch(()=>({}));throw new Error(E.error||`API error: ${h.status}`)}let l=await h.json();return await a().catch(()=>{}),l.removed?(T(null),c("prompting")):l.fork&&(T(l.fork),c("complete")),l}catch(R){throw k(R.message),R}},[t,i,o,e,a,n,r]);return {state:g,fork:x,events:F,error:y,open:w,close:I,startFork:$,undoFork:A}}function wr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:f}=Ft(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:f}}function Rt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=V(),[f,g]=useState("idle"),[c,x]=useState(null),[T,F]=useState([]),[v,y]=useState(null),k=useRef(null),C=useCallback(()=>{g("prompting"),F([]),y(null),x(null);},[]),w=useCallback(()=>{g("idle"),k.current&&(k.current.close(),k.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&g(A=>A==="idle"?"prompting":A);},[o?.preview_session_id,o?.target.kind]);let I=useCallback(async(A,R,h)=>{try{g("running"),F([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...X()},body:JSON.stringify({prompt:A,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let M=await u.json().catch(()=>({}));throw new Error(M.error||`API error: ${u.status}`)}let p=await u.json();we(p.fork_id),l=await(await fetch(`${n}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...X()}})).json();}else {let u={userId:t,prompt:A};R&&(u.slotId=R),h&&(u.containerId=h),r&&(u.userHash=r);let p=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!p.ok){let m=await p.json().catch(()=>({}));throw new Error(m.error||`API error: ${p.status}`)}l=await p.json();}x(l);let E=new URLSearchParams({key:e});r&&(E.set("userId",t),E.set("userHash",r));let S=new EventSource(`${n}/api/v1/forks/${l.id}/events?${E.toString()}`);k.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(F(m=>[...m,p]),p.type==="complete"){let m=p.data,M={...l,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};x(M),g("complete"),R&&m.bundleUrl&&i(R,M),S.close();}else if(p.type==="error"){let m=p.data;y(m.error||"Unknown error"),g("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{x(u),u.status==="complete"?(g("complete"),R&&u.bundleUrl&&i(R,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),g("error"));}).catch(()=>{y("Connection lost"),g("error");}),S.close();};}catch(l){y(l.message),g("error");}},[e,t,r,n,o,i]),$=useCallback(async A=>{try{let R={userId:t,slotId:A};r&&(R.userHash=r);let h=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(R)});if(!h.ok){let E=await h.json().catch(()=>({}));throw new Error(E.error||`API error: ${h.status}`)}let l=await h.json();return a(A),l.removed?(s(A),x(null),g("prompting")):l.fork&&(i(A,l.fork),x(l.fork)),l}catch(R){throw y(R.message),R}},[e,t,r,n,s,i]);return {state:f,fork:c,events:T,error:v,open:C,close:w,startFork:I,undoFork:$}}function vr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=Rt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Et(e){let t=br(e),r=vr(),n=wr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}=V(),g=t.type==="slot"?r:n,c=t.type==="slot"?"slot":"boundary",x=t.id,T=t.title,F=useCallback((y,k,C)=>t.type==="slot"?r.submit(y,k??t.id,C):n.submit(y,C),[n,r,t]),v=useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:x,targetLabel:T,historyMode:c,submit:F,undo:v,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:x,targetLabel:T,historyMode:c}:{targetId:x,targetLabel:T,historyMode:c},onSubmit:F,onUndo:v,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}}}function Ee(e){let{examplePrompts:t,embedded:r}=e,n=Et(e);return r?jsx(Je,{...n.panelProps,examplePrompts:t,embedded:true}):n.isOpen?jsx(Je,{...n.panelProps,examplePrompts:t}):jsx(vt,{...n.buttonProps})}function qn({boundaryId:e,title:t,examplePrompts:r}){return jsx(Ee,{boundaryId:e,title:t,examplePrompts:r})}function _t(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 xr(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 At(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 Fr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Rr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Er(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 Pt(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 c=0;c<e.length;c+=1){let{rect:x,borderRadius:T}=e[c],F=x.left-.5,v=x.top-.5,y=x.width+1,k=x.height+1,C=Math.min(T+.5,y/2,k/2),w=Er(F,v,y,k,C),I=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",I),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let A=document.createElementNS(t,"feGaussianBlur");A.setAttribute("in","SourceGraphic"),A.setAttribute("stdDeviation","8"),$.appendChild(A),o.appendChild($);let R=`__fork-mask-${c}`,h=document.createElementNS(t,"mask");h.setAttribute("id",R),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(F-200)),h.setAttribute("y",String(v-200)),h.setAttribute("width",String(y+400)),h.setAttribute("height",String(k+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(F-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(k+400)),l.setAttribute("fill","white"),h.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",w),E.setAttribute("fill","black"),h.appendChild(E),o.appendChild(h);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${R})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${I})`);let p=document.createElementNS(t,"path");p.setAttribute("d",w),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let m=document.createElementNS(t,"path");m.setAttribute("d",w),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(p,m),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let x=i[c],T=i[c+1],F=x.__group;if(!F)continue;let v=T.getTotalLength(),y=x.getTotalLength();if(v<=0)continue;let k=v*.35;T.setAttribute("stroke-dasharray",`${k} ${v-k}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;x.setAttribute("stroke-dasharray",`${C} ${y-C}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(F.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",f);},g=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function $r(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:a,borderRadius:f}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Er(a.left,a.top,a.width,a.height,f)),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 tt=new Map,Ct=new Map;function Yn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Ar(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 Zn(e){if(!e||typeof document>"u")return Promise.resolve();let t=tt.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),i();},f=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",f,{once:true});});return tt.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 tt.delete(e),o});return tt.set(e,n),n}function Qn(e){let t=Ct.get(e);if(t)return t;let r=import(e).catch(n=>{throw Ct.delete(e),n});return Ct.set(e,r),r}async function eo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Zn(i)));let o=await Qn(e.moduleUrl);return Ar(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 Ar(n,r)}function to(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:f,consumeBoundaryAnimation:g}=V(),[c,x]=useState(null),[T,F]=useState(null),v=useRef(null),y=useRef(null),k=useRef(null),C=useRef(false),w=useRef(null),I=useRef(null),$=f(e.id),A=$?`override:${$.id}`:"original",R=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{I.current&&(clearTimeout(I.current),I.current=null),w.current&&(w.current.remove(),w.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,R]),useEffect(()=>{if(o&&!i&&!c||y.current===A&&c)return;let h=false;return F(null),eo($,e.original,e.exportName).then(l=>{if(!h){if($?.id&&g(e.id,$.id)&&v.current){let E=_t(v.current);if(E){let S=At(E);S.length>0&&(k.current=S,C.current=true,I.current&&(clearTimeout(I.current),I.current=null),w.current&&w.current.remove(),w.current=xr(E));}}y.current=A,startTransition(()=>{x(()=>l);});}}).catch(l=>{h||F(Yn(l));}),()=>{h=true;}},[g,A,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,c]),useEffect(()=>{if(!C.current||!c||!v.current)return;let h=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(h||!v.current)return;let l=k.current,E=_t(v.current);if(k.current=null,C.current=false,!l||!E){w.current&&(w.current.remove(),w.current=null);return}let S=At(E),u=Fr(l,S),p=Rr(l,S),m=w.current;if(p.length>0&&m){let M=$r(p);I.current=setTimeout(()=>{I.current=null;let z=400;m.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),M.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{m.remove(),M.remove(),w.current===m&&(w.current=null),u.length>0&&Pt(u);},z);},3500);}else m&&(m.remove(),w.current===m&&(w.current=null)),u.length>0&&Pt(u);});}),()=>{h=true;}},[c]),T)throw T;return c?jsx("div",{ref:v,style:{display:"contents"},children:jsx(c,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function no({slotId:e,title:t,slotLabel:r,examplePrompts:n}){return jsx(Ee,{slotId:e,title:t,slotLabel:r,examplePrompts:n})}
44
- export{qn as ForkBoundaryUI,vt as ForkButton,Ee as ForkChatInterface,Je as ForkPanel,rn as ForkProvider,hn as ForkSlot,no as ForkUI,Yr as clearCachedManifest,to as forkable,je as loadManifest,Zr as manifestDiffers,Jr as readCachedManifest,ct as registerForkShared,Ft as useBoundaryFork,Rt as useFork,Et as useForkChatPanel,De as usePreviewSession,Xr as writeCachedManifest};
43
+ `}),jsxs("div",{className:"__fork-panel",style:Lr,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx(je,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async m=>{if(m.stopPropagation(),!Qe&&confirm("Reset all forks? This will remove all forked components.")){_e(true);try{let L=await Ar();`${L?.deleted??0}`,$([]),R(""),N(!1),ot();}catch(L){console.error("[Fork] Reset failed:",L);}finally{_e(false);}}}}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Mr}):ke.length===0?jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Me]}):jsxs("div",{ref:nt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ae(m=>!m);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(false),"aria-haspopup":"menu","aria-expanded":W,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:$r||W?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ke.find(m=>m.id===J)?.name??(b?`Fork ${Me}`:"Loading\u2026")}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:W?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),W&&jsx("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:ke.map(m=>{let L=m.id===J,U=_r===m.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Tt(m.id),onMouseLeave:()=>Tt(null),onClick:()=>{ae(false),m.id!==J&&_(m.id);},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:U?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:"pointer",textAlign:"left",fontWeight:L?600:400},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:L&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]},m.id)})})]}),e==="running"&&jsx("span",{title:ce?`Estimated ~${ce} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ce?"#1c4587":"#9ca3af",backgroundColor:ce?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ce?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ce?`~${ce}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!h&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Ut&&jsx("button",{onClick:ne?Tr:Cr,onMouseEnter:()=>I(true),onMouseLeave:()=>I(false),title:ne?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:g?"#4b5563":"#9ca3af",backgroundColor:g?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ne?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:ot,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:Ae,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&T.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children: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."})}),T.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:T.map((m,L)=>jsx("div",{style:{marginBottom:L<T.length-1?10:0},children:m.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:m.text})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:m.text}),f&&L===T.length-1&&e!=="running"&&jsxs("button",{onClick:U=>{U.stopPropagation(),Ir();},onMouseEnter:()=>q(L),onMouseLeave:()=>q(null),disabled:Q,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ie===L?"rgba(0,0,0,0.06)":"transparent",color:ie===L?"#6b7280":"#d1d5db",cursor:Q?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:Q?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),ie===L&&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"})]})]})]})},L))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>N(!V),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(On,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:V?320:0,opacity:V?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(cr,{events:r})})})]})}),e==="error"&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let m=t?.prompt||rt.current;m&&d(m,oe);},onMouseEnter:()=>D(true),onMouseLeave:()=>D(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:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"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:[jsx("textarea",{ref:et,value:C,onChange:m=>{R(m.target.value),m.target.style.height="auto",m.target.style.height=Math.min(m.target.scrollHeight,160)+"px";},onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),Ot()),m.key==="Escape"&&!h&&ot();},placeholder:T.length>0?"Ask for another change...":`Describe your ideal ${Me.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"}}),jsx("button",{onClick:Ot,disabled:!C.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:C.trim()?1:.25,transform:z&&C.trim()?"scale(1.1)":"scale(1)",background:C.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:C.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return h?st:ne&&ge?createPortal(st,ge.document.body):jsx(Bn,{children:st})}function hr(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 St(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:d}=G(),[f,c]=useState("idle"),[F,P]=useState(null),[x,v]=useState([]),[y,h]=useState(null),C=useRef(null),R=useCallback(()=>{c("prompting"),v([]),h(null),P(null);},[]),T=useCallback(()=>{c("idle"),C.current&&(C.current.close(),C.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&c(w=>w==="idle"?"prompting":w);},[s?.preview_session_id,s?.target.id,e]);let $=useCallback(async(w,k)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");c("running"),v([]),h(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...Z()},body:JSON.stringify({prompt:w,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${o}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...Z()}})).json();}else {let u={userId:r,prompt:w,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n);let p=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}P(l);let E=new URLSearchParams({key:t});n&&(E.set("userId",r),E.set("userHash",n));let S=new EventSource(`${o}/api/v1/forks/${l.id}/events?${E.toString()}`);C.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(v(g=>[...g,p]),p.type==="complete"){let g=p.data;d(e,l.id),a().catch(()=>{}).finally(()=>{let I={...l,status:"complete",moduleUrl:g.moduleUrl,cssUrls:g.cssUrls,summary:g.summary,completedAt:new Date().toISOString()};P(I),c("complete"),S.close();});}else if(p.type==="error"){let g=p.data;h(g.error||"Unknown error"),c("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(d(e,u.id),a().catch(()=>{}),c("complete")):u.status==="error"&&(h(u.error||"Fork generation failed"),c("error"));}).catch(()=>{h("Connection lost"),c("error");}),S.close();};}catch(l){h(l.message),c("error");}},[t,i,o,e,s,d,a,n,r]),M=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let w={userId:r,boundaryId:e,appId:i};n&&(w.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return await a().catch(()=>{}),l.removed?(P(null),c("prompting")):l.fork&&(P(l.fork),c("complete")),l}catch(w){throw h(w.message),w}},[t,i,o,e,a,n,r]);return {state:f,fork:F,events:x,error:y,open:R,close:T,startFork:$,undoFork:M}}function yr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:d}=St(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:d}}function xt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=G(),[d,f]=useState("idle"),[c,F]=useState(null),[P,x]=useState([]),[v,y]=useState(null),h=useRef(null),C=useCallback(()=>{f("prompting"),x([]),y(null),F(null);},[]),R=useCallback(()=>{f("idle"),h.current&&(h.current.close(),h.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&f(M=>M==="idle"?"prompting":M);},[o?.preview_session_id,o?.target.kind]);let T=useCallback(async(M,w,k)=>{try{f("running"),x([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...Z()},body:JSON.stringify({prompt:M,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${n}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...Z()}})).json();}else {let u={userId:t,prompt:M};w&&(u.slotId=w),k&&(u.containerId=k),r&&(u.userHash=r);let p=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}F(l);let E=new URLSearchParams({key:e});r&&(E.set("userId",t),E.set("userHash",r));let S=new EventSource(`${n}/api/v1/forks/${l.id}/events?${E.toString()}`);h.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(x(g=>[...g,p]),p.type==="complete"){let g=p.data,I={...l,status:"complete",bundleUrl:g.bundleUrl,summary:g.summary,completedAt:new Date().toISOString()};F(I),f("complete"),w&&g.bundleUrl&&i(w,I),S.close();}else if(p.type==="error"){let g=p.data;y(g.error||"Unknown error"),f("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{F(u),u.status==="complete"?(f("complete"),w&&u.bundleUrl&&i(w,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),f("error"));}).catch(()=>{y("Connection lost"),f("error");}),S.close();};}catch(l){y(l.message),f("error");}},[e,t,r,n,o,i]),$=useCallback(async M=>{try{let w={userId:t,slotId:M};r&&(w.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return a(M),l.removed?(s(M),F(null),f("prompting")):l.fork&&(i(M,l.fork),F(l.fork)),l}catch(w){throw y(w.message),w}},[e,t,r,n,s,i]);return {state:d,fork:c,events:P,error:v,open:C,close:R,startFork:T,undoFork:$}}function kr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=xt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Ft(e){let t=hr(e),r=kr(),n=yr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}=G(),f=t.type==="slot"?r:n,c=t.type==="slot"?"slot":"boundary",F=t.id,P=t.title,x=useCallback((y,h,C)=>t.type==="slot"?r.submit(y,h??t.id,C):n.submit(y,C),[n,r,t]),v=useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...f,target:t,targetId:F,targetLabel:P,historyMode:c,submit:x,undo:v,buttonProps:{onClick:f.open},panelProps:{state:f.state,fork:f.fork,events:f.events,error:f.error,...t.type==="slot"?{slotId:F,targetLabel:P,historyMode:c}:{targetId:F,targetLabel:P,historyMode:c},onSubmit:x,onUndo:v,onClose:f.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}}}function $e(e){let{embedded:t}=e,r=Ft(e);return t?jsx(Ge,{...r.panelProps,embedded:true}):r.isOpen?jsx(Ge,{...r.panelProps}):jsx(bt,{...r.buttonProps})}function Wn({boundaryId:e,title:t}){return jsx($e,{boundaryId:e,title:t})}function Et(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 wr(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 $t(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 vr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Sr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function xr(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 _t(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 c=0;c<e.length;c+=1){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=xr(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group;if(!x)continue;let v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function Fr(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:a,borderRadius:d}of e){let f=document.createElementNS(t,"path");f.setAttribute("d",xr(a.left,a.top,a.width,a.height,d)),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),f.setAttribute("stroke-width","1.5"),f.setAttribute("stroke-dasharray","8 4"),f.setAttribute("stroke-linecap","round"),f.setAttribute("filter","url(#__fork-removed-shadow)"),f.setAttribute("opacity","0"),n.appendChild(f),f.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var Ze=new Map,At=new Map;function Vn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Er(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 qn(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ze.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 a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),i();},d=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",d,{once:true});});return Ze.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 Ze.delete(e),o});return Ze.set(e,n),n}function Jn(e){let t=At.get(e);if(t)return t;let r=import(e).catch(n=>{throw At.delete(e),n});return At.set(e,r),r}async function Xn(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>qn(i)));let o=await Jn(e.moduleUrl);return Er(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 Er(n,r)}function Yn(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:d,consumeBoundaryAnimation:f}=G(),[c,F]=useState(null),[P,x]=useState(null),v=useRef(null),y=useRef(null),h=useRef(null),C=useRef(false),R=useRef(null),T=useRef(null),$=d(e.id),M=$?`override:${$.id}`:"original",w=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{T.current&&(clearTimeout(T.current),T.current=null),R.current&&(R.current.remove(),R.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,w]),useEffect(()=>{if(o&&!i&&!c||y.current===M&&c)return;let k=false;return x(null),Xn($,e.original,e.exportName).then(l=>{if(!k){if($?.id&&f(e.id,$.id)&&v.current){let E=Et(v.current);if(E){let S=$t(E);S.length>0&&(h.current=S,C.current=true,T.current&&(clearTimeout(T.current),T.current=null),R.current&&R.current.remove(),R.current=wr(E));}}y.current=M,startTransition(()=>{F(()=>l);});}}).catch(l=>{k||x(Vn(l));}),()=>{k=true;}},[f,M,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,c]),useEffect(()=>{if(!C.current||!c||!v.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!v.current)return;let l=h.current,E=Et(v.current);if(h.current=null,C.current=false,!l||!E){R.current&&(R.current.remove(),R.current=null);return}let S=$t(E),u=vr(l,S),p=Sr(l,S),g=R.current;if(p.length>0&&g){let I=Fr(p);T.current=setTimeout(()=>{T.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),R.current===g&&(R.current=null),u.length>0&&_t(u);},z);},3500);}else g&&(g.remove(),R.current===g&&(R.current=null)),u.length>0&&_t(u);});}),()=>{k=true;}},[c]),P)throw P;return c?jsx("div",{ref:v,style:{display:"contents"},children:jsx(c,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Qn({slotId:e,title:t,slotLabel:r}){return jsx($e,{slotId:e,title:t,slotLabel:r})}
44
+ export{Wn as ForkBoundaryUI,bt as ForkButton,$e as ForkChatInterface,Ge as ForkPanel,Qr as ForkProvider,pn as ForkSlot,Qn as ForkUI,qr as clearCachedManifest,Yn as forkable,He as loadManifest,Jr as manifestDiffers,Gr as readCachedManifest,at as registerForkShared,St as useBoundaryFork,xt as useFork,Ft as useForkChatPanel,Be as usePreviewSession,Vr as writeCachedManifest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fork-api/chat-sdk",
3
- "version": "0.1.133",
3
+ "version": "0.1.134",
4
4
  "description": "React SDK for Fork — let your users customize your UI with AI.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://withfork.co",