@fork-api/chat-sdk 0.1.172 → 0.1.173

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';var vr=require('react'),wo=require('react-dom'),vo=require('react/jsx-runtime'),So=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 vr__namespace=/*#__PURE__*/_interopNamespace(vr);var wo__namespace=/*#__PURE__*/_interopNamespace(wo);var vo__namespace=/*#__PURE__*/_interopNamespace(vo);var So__namespace=/*#__PURE__*/_interopNamespace(So);var Ge="__FORK_SHARED__";function cr(){var t,r,n,o;let e=globalThis;return e[Ge]||(e[Ge]={}),(t=e[Ge]).react||(t.react=vr__namespace),(r=e[Ge])["react-dom"]||(r["react-dom"]=wo__namespace),(n=e[Ge])["react/jsx-runtime"]||(n["react/jsx-runtime"]=vo__namespace),(o=e[Ge])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=So__namespace),e[Ge]}function ur(e){return Object.assign(cr(),e)}var Fo="__fork_preview_session__";function Bt(e){return `${Fo}${e}`}var ae={apiKey:null,session:null},dr=new Set;function Nt(){for(let e of dr)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function nn(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function xo(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Bt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:nn(r)?(window.sessionStorage.removeItem(Bt(e)),null):r}catch{return null}}function fr(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Bt(e),JSON.stringify(t)):window.sessionStorage.removeItem(Bt(e));}catch{}}function at(e){ae.apiKey!==e&&(ae.apiKey=e,ae.session=xo(e),Nt());}function Ne(){return ae.session?nn(ae.session)?(Dt(null),null):ae.session:null}function Dt(e){ae.session=e,ae.apiKey&&fr(ae.apiKey,e),Nt();}function ft(e){ae.session&&ae.session.fork_id!==e&&(ae.session={...ae.session,fork_id:e},ae.apiKey&&fr(ae.apiKey,ae.session),Nt());}function Ye(e,t){ae.session&&(ae.session.container_id===e&&ae.session.container_name===t||(ae.session={...ae.session,container_id:e,container_name:t??ae.session.container_name??"Fork",fork_id:null},ae.apiKey&&fr(ae.apiKey,ae.session),Nt()));}function pr(e){return dr.add(e),()=>{dr.delete(e);}}var on="__fork_preview";function sn(){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(on);return typeof r=="string"&&r.length>0?r:null}function mr(e){if(typeof window>"u")return false;try{let t=window.sessionStorage.getItem(`__fork_preview_session__${e}`);if(t){let r=JSON.parse(t),n=typeof r?.expires_at=="string"?Date.parse(r.expires_at):NaN;if(Number.isFinite(n)&&n>Date.now())return !0;window.sessionStorage.removeItem(`__fork_preview_session__${e}`);}}catch{}return ln()!==null}function an(){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(on);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Qe=null,gr=null,pt=null;function ln(){if(Qe)return Qe;let e=sn();return e?(Qe=e,an(),Qe):null}async function hr(e,t){at(e);let r=Ne();if(r)return Qe=null,r;let n=Qe??sn();if(Qe=null,!n)return null;an();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let s=await o.json(),i={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Dt(i),i}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function yr(e,t,r){at(e);let n=Ne();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
2
2
  `);return pt&&gr===o||(gr=o,pt=(async()=>{try{let s=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(s.status===204)return null;if(!s.ok){let u=await s.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${s.status}): ${u.error??"unknown"}`),null}let i=await s.json(),a={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Dt(a),a}catch(s){return console.warn("[fork-preview] auto admin activate threw",s),null}finally{gr=null,pt=null;}})()),pt}function Io(){return Ne()}function _o(){return null}function jt(){return vr.useSyncExternalStore(pr,Io,_o)}function oe(){let e=Ne();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Kt(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let s=await o.json(),i={};for(let[a,u]of Object.entries(s.modules)){let b=u.moduleUrl??u.bundleUrl??null,g=u.legacyModuleUrl??u.legacyBundleUrl??null;i[a]={forkId:u.forkId,moduleUrl:b,legacyModuleUrl:g,bundleUrl:u.bundleUrl??b,legacyBundleUrl:u.legacyBundleUrl??g,cssUrls:u.cssUrls??[],integrity:u.integrity,metadata:u.metadata,highlightHint:u.highlightHint,buildId:u.buildId,updatedAt:u.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var Ro="fork:manifest:v1";function kr(e,t,r){return `${Ro}:${e}:${t}:${r}`}function Eo(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(kr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Co(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(kr(e,t,r),JSON.stringify(n));}catch{}}function $o(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(kr(e,t,r));}catch{}}function Po(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,a]of r){let u=t.slots[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,a]of o){let u=t.modules[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}return false}var gn=vr.createContext(null),Lo=12e3,Ho=45e3,cn="fork:activity:v1",Oo=new Set(["pending","running","building"]),Uo="Setting up environment";function Ee(e){return Oo.has(e)}function Bo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function No(e,t){let r=Bo(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function un(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function zt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function gt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Ze(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function et(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var Do="fork:previewPaused:v1";function br(e,t,r,n){return `${Do}:${e}:${t}:${r}:${n}`}function jo(e){if(typeof window>"u")return false;try{return window.localStorage.getItem(e)==="1"}catch{return false}}function dn(e,t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(e,"1"):window.localStorage.removeItem(e);}catch{}}function Ko(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function zo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Ee(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function Wo(e){let t=e.filter(o=>Ee(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():Uo,detail:s?Ko(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function mt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Jo(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:mt(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(s=>mt(e,s)):[]};return r}function fn(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let a=i.bundleUrl??i.legacyBundleUrl;a&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:mt(e,a),createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function pn(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:mt(e,s),cssUrls:(o.cssUrls??[]).map(i=>mt(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function Vo(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[u]=vr.useState(()=>(at(t),mr(t))),[b,g]=vr.useState({}),[d,w]=vr.useState(i?{userId:i,userHash:void 0}:null),[I,f]=vr.useState(!!i||u),[m,x]=vr.useState({}),[H,h]=vr.useState(!o),[v,M]=vr.useState(0),[N,D]=vr.useState(null),[j,_]=vr.useState(false),[L,O]=vr.useState([]),[S,c]=vr.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),F=vr.useRef(new Map),$=vr.useRef(new Map),[P,A]=vr.useState(0),k=vr.useRef(new Set),C=vr.useRef(new Map),G=vr.useRef(void 0),V=vr.useRef(new Map),q=vr.useRef([]),te=vr.useRef(new Set),X=vr.useRef(false);cr(),vr.useEffect(()=>{return hr(t,r).then(()=>{}),()=>{}},[]);let U=jt();vr.useEffect(()=>{u||U||!o||!d?.userHash||yr(t,r,{appId:o,userId:d.userId,userHash:d.userHash});},[t,o,d?.userHash,d?.userId,r,u,U?.preview_session_id]),s&&G.current!==s&&(ur(s),G.current=s),vr.useEffect(()=>{a&&(u||(f(false),fetch(a,{credentials:"include"}).then(p=>{if(!p.ok)throw new Error(`Auth endpoint returned ${p.status}`);return p.json()}).then(p=>{if(!p.userId||typeof p.userId!="string")throw new Error("authUrl response must include userId");w({userId:p.userId,userHash:typeof p.userHash=="string"?p.userHash:void 0});}).catch(p=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",p.message);}).finally(()=>{f(true);})));},[a,u]),vr.useEffect(()=>{!a&&i&&(w({userId:i,userHash:void 0}),f(true));},[i,a]);let ne=d?.userId??"",_e=d?.userHash,z=U?"":ne,ee=U?void 0:_e,ve=!!o,se=vr.useCallback(async()=>{if(!ve){D(null),_(false),x({}),h(true),M(y=>y+1);return}if(!I){h(false);return}if(!U&&!z||!o){D(null),_(false),x({}),h(true),M(y=>y+1);return}if(h(false),!U){try{let y=await Kt({baseUrl:r,apiKey:t,appId:o,userId:z,userHash:ee});y&&(D(y.containerId),_(!!y.forksPaused),g(fn(r,y,z,o)),x(pn(r,y)));}catch(y){console.error("[ForkProvider] Failed to fetch fork manifest:",y.message),D(null),_(false),g({}),x({});}finally{M(y=>y+1),h(true);}return}if(D(U.container_id??null),U.container_id){let y=br(t,o,U.operator_id,U.container_id);if(jo(y)){_(true),g({}),x({}),M(E=>E+1),h(true);return}_(false);try{let E=await Kt({baseUrl:r,apiKey:t,appId:o,userId:z,containerId:U.container_id,extraHeaders:oe()});E&&(g(fn(r,E,z,o)),x(pn(r,E)));}catch(E){console.error("[ForkProvider] Failed to fetch preview container manifest:",E.message),g({}),x({});}finally{M(E=>E+1),h(true);}return}_(false);let p=new URLSearchParams({appId:o,userId:z});ee&&p.set("userHash",ee);try{let y=await fetch(`${r}/api/v1/boundaries/manifest?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,...oe()}});if(!y.ok)throw new Error(`${y.status}`);let E=await y.json();x(Jo(r,E));}catch(y){console.error("[ForkProvider] Failed to fetch module override manifest:",y.message),x({});}finally{M(y=>y+1),h(true);}},[t,o,r,I,ve,ee,z,U?.preview_session_id,U?.fork_id,U?.container_id]);vr.useEffect(()=>{if(!z||o&&(!U||U.container_id))return;let p=new URLSearchParams({userId:z});ee&&p.set("userHash",ee),fetch(`${r}/api/v1/forks/active?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,...oe()}}).then(y=>{if(!y.ok)throw new Error(`${y.status}`);return y.json()}).then(y=>{y&&typeof y=="object"&&g(y);}).catch(()=>{});},[t,o,z,ee,r,U?.preview_session_id,U?.fork_id]),vr.useEffect(()=>{se();},[se]);let Me=vr.useCallback(async p=>{if(o){if(U){if(!U.container_id)return;dn(br(t,o,U.operator_id,U.container_id),p),_(p),p?(g({}),x({}),M(y=>y+1)):await se();return}if(z){_(p),p&&(g({}),x({}),M(y=>y+1));try{let y=await fetch(`${r}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:p,userId:z,userHash:ee})});if(!y.ok)throw new Error(`${y.status}`);p||await se();}catch(y){console.error("[ForkProvider] Failed to persist fork pause state:",y?.message??y),se().catch(()=>{});}}}},[t,o,r,se,U,ee,z]),ze=vr.useCallback((p,y)=>{g(E=>({...E,[p]:y}));},[]),nt=vr.useCallback(p=>{g(y=>{let E={...y};return delete E[p],E});},[]),Pe=vr.useCallback(p=>{k.current.add(p);},[]),We=vr.useCallback(p=>k.current.has(p)?(k.current.delete(p),true):false,[]),Je=vr.useCallback((p,y)=>{C.current.set(p,y);},[]),Ct=vr.useCallback((p,y)=>C.current.get(p)!==y?false:(C.current.delete(p),true),[]),or=vr.useCallback(p=>{if(!o)return;let y=JSON.stringify(p);F.current.get(p.id)===y||$.current.get(p.id)?.signature===y||($.current.set(p.id,{boundary:p,signature:y}),A(Q=>Q+1));},[o]);vr.useEffect(()=>{if(!o||$.current.size===0)return;let p=setTimeout(()=>{let y=Array.from($.current.values());y.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:y.map(E=>E.boundary)})}).then(E=>{if(!E.ok)throw new Error(`${E.status}`)}).then(()=>{for(let E of y)$.current.get(E.boundary.id)?.signature===E.signature&&($.current.delete(E.boundary.id),F.current.set(E.boundary.id,E.signature));}).catch(E=>{console.error("[ForkProvider] Failed to register module boundaries:",E.message);});},50);return ()=>{clearTimeout(p);}},[t,o,r,P]);let $t=vr.useCallback(p=>m[p],[m]),ge=U?`preview:${U.preview_session_id}`:z,Ve=`${t}:${o||"no-app"}:${N||"no-container"}:${ge||"anonymous"}`,sr=U?`op:${U.operator_id}`:z,Pt=`${t}:${o||"no-app"}:${sr||"anonymous"}`,Se=`${cn}:seen:${Ve}`,me=`${cn}:tracked:${Ve}`;vr.useEffect(()=>{q.current=L;},[L]);let Te=vr.useCallback(()=>{let p={Authorization:`Bearer ${t}`,...oe()};return o&&(p["X-Fork-App-Id"]=o),!U&&z&&(p["X-Fork-User-Id"]=z),!U&&ee&&(p["X-Fork-User-Hash"]=ee),p},[t,o,U,ee,z]);vr.useEffect(()=>{if(typeof window>"u")return;let p=window.__FORK_RUNTIME__,y={dataFetch:async(E,Q,K="POST")=>{if(!o||!N)throw new Error("Fork data is unavailable until appId and containerId are resolved");let W=typeof E=="string"&&E.startsWith("/")?E:`/${String(E||"")}`,re=W.startsWith("/api/v1/data")?W:`/api/v1/data${W}`,ie=K.toUpperCase(),ce=new URL(`${r}${re}`),ue={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...oe()};!U&&z&&(ue["X-Fork-User-Id"]=z),!U&&ee&&(ue["X-Fork-User-Hash"]=ee);let de={method:ie,headers:ue};ie==="GET"?(ce.searchParams.set("appId",o),ce.searchParams.set("containerId",N)):de.body=JSON.stringify({appId:o,containerId:N,...Q&&typeof Q=="object"?Q:{}});let fe=await fetch(ce.toString(),de),J=await fe.json().catch(()=>({}));if(!fe.ok)throw new Error(typeof J?.error=="string"?J.error:`Fork data API ${fe.status}`);return J}};return window.__FORK_RUNTIME__=y,()=>{window.__FORK_RUNTIME__===y&&(window.__FORK_RUNTIME__=p);}},[t,o,r,N,U,ee,z]);let Fe=vr.useCallback(async()=>{if(!N)return;let p=new URLSearchParams({container_id:N}),y=await fetch(`${r}/api/v1/forks?${p.toString()}`,{headers:Te()}).catch(()=>null);if(!y||!y.ok)return;let E=await y.json().catch(()=>({})),Q=Array.isArray(E.forks)?E.forks:[],K=Ze(Se),W=Ze(me),re=false,ie=new Map(q.current.map(ue=>[ue.id,ue])),ce=[];for(let ue of Q){let de=un(ue);Ee(de.status)&&!W.has(de.id)&&(W.add(de.id),re=true);let fe=ie.get(de.id),J=fe?Ee(fe.status):false,xe=gt(de);de.status==="complete"&&(W.has(de.id)||J)&&!K.has(xe)&&!te.current.has(xe)&&!fe?.unread&&(X.current||W.has(de.id)||J)&&(te.current.add(xe),ce.push(de));}if(O(ue=>{let de=new Map(ue.map(le=>[le.id,le])),fe=new Set,J=new Map;for(let le of Q){let Ae=un(le);fe.add(Ae.id);let we=de.get(Ae.id),Ie=we?Ee(we.status):false,ut=gt(Ae),Tt=Ae.status==="complete"&&(W.has(Ae.id)||Ie)&&!K.has(ut),Mt=zt(we,{...Ae,unread:Tt});J.set(Ae.id,Mt);}for(let le of ue)fe.has(le.id)||(Ee(le.status)||le.unread)&&J.set(le.id,le);let xe=[...J.values()].sort((le,Ae)=>Date.parse(Ae.updatedAt)-Date.parse(le.updatedAt));return q.current=xe,xe}),re&&et(me,W),ce.length>0){for(let ue of ce)ue.targetKind==="module"&&Je(ue.targetId,ue.id);se().catch(()=>{});}X.current=true;},[Se,me,r,Te,N,se,Je]),ct=vr.useCallback((p,y)=>{let E=No(p,y);if(!E)return;let Q=p.containerId??p._containerId;if(Q&&!N&&D(Q),Ee(E.status)){let re=Ze(me);re.has(E.id)||(re.add(E.id),et(me,re)),_(false),U?.container_id&&o&&dn(br(t,o,U.operator_id,U.container_id),false);}let K=new Map(q.current.map(re=>[re.id,re]));K.set(E.id,zt(K.get(E.id),E));let W=[...K.values()].sort((re,ie)=>Date.parse(ie.updatedAt)-Date.parse(re.updatedAt));q.current=W,O(W);},[me,t,o,N,U]),ot=vr.useCallback((p,y)=>{let E=zo(y),Q=Ze(Se),K=Ze(me),W=q.current.find(fe=>fe.id===p),re=W?Ee(W.status):false;E.status&&Ee(E.status)&&!K.has(p)&&(K.add(p),et(me,K));let ie=W?zt(W,{...W,...E}):null,ce=ie?gt(ie):null,ue=!!(ie&&ie.status==="complete"&&(K.has(p)||re)&&ce&&!Q.has(ce)&&!te.current.has(ce)&&!W?.unread),de=y.type==="complete"&&W?.targetKind==="module"?W.targetId:null;if(O(fe=>{let J=fe.find(Ie=>Ie.id===p);if(!J)return fe;let xe=zt(J,{...J,...E}),le=xe.status==="complete"&&(K.has(p)||Ee(J.status))&&!Q.has(gt(xe)),Ae={...xe,unread:le},we=fe.map(Ie=>Ie.id===p?Ae:Ie).sort((Ie,ut)=>Date.parse(ut.updatedAt)-Date.parse(Ie.updatedAt));return q.current=we,we}),ue&&ie&&ce&&te.current.add(ce),y.type==="complete"){let fe=y.data&&typeof y.data=="object"?y.data:{},J=typeof fe.boundaryId=="string"?fe.boundaryId:de;J&&Je(J,p),se().catch(()=>{});}},[Se,me,se,Je]),Le=vr.useCallback(p=>{let y=Ze(Se),E=Ze(me),Q=false,K=false;for(let W of q.current){if(W.status!=="complete"||p&&W.id!==p)continue;let re=gt(W);y.has(re)||(y.add(re),Q=true),E.delete(W.id)&&(K=true);}O(W=>{let re=W.map(ie=>ie.status!=="complete"||p&&ie.id!==p?ie:{...ie,unread:false});return q.current=re,re}),Q&&et(Se,y),K&&et(me,E);},[Se,me]);vr.useEffect(()=>{X.current=false,te.current.clear(),O([]);for(let p of V.current.values())p.close();V.current.clear(),N&&Fe();},[N,Fe]),vr.useEffect(()=>{if(typeof document>"u")return;let p=()=>{let y=document.visibilityState!=="hidden";c(y),y&&N&&Fe();};return document.addEventListener("visibilitychange",p),window.addEventListener("focus",p),window.addEventListener("online",p),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("focus",p),window.removeEventListener("online",p);}},[N,Fe]),vr.useEffect(()=>{let p=L.filter(Q=>Ee(Q.status));if(!N||p.length===0)return;let y=S?Lo:Ho,E=window.setInterval(()=>{Fe();},y);return ()=>window.clearInterval(E)},[N,S,L,Fe]),vr.useEffect(()=>{for(let p of V.current.values())p.close();V.current.clear();},[t,r,U?.preview_session_id,ee,z]),vr.useEffect(()=>{let p=new Set(L.filter(y=>Ee(y.status)).map(y=>y.id));for(let[y,E]of V.current.entries())p.has(y)||(E.close(),V.current.delete(y));for(let y of p){if(V.current.has(y))continue;let E=new URLSearchParams({key:t});U?(E.set("previewSessionId",U.preview_session_id),E.set("previewForkId",y)):z&&E.set("userId",z),ee&&E.set("userHash",ee);let Q=new EventSource(`${r}/api/v1/forks/${y}/events?${E.toString()}`);Q.onmessage=K=>{try{ot(y,JSON.parse(K.data));}catch{}},Q.onerror=()=>{Q.close(),V.current.delete(y);},V.current.set(y,Q);}},[t,r,L,U,ot,ee,z]),vr.useEffect(()=>()=>{for(let p of V.current.values())p.close();V.current.clear();},[]);let ir=Wo(L),qe=vr.useCallback(async()=>{if(!z)throw new Error("Reset requires a resolved user identity.");let p=new URLSearchParams({userId:z});ee&&p.set("userHash",ee);let y={Authorization:`Bearer ${t}`,...oe()};o&&(y["X-Fork-App-Id"]=o);let E=await fetch(`${r}/api/v1/forks/all?${p.toString()}`,{method:"DELETE",headers:y});if(!E.ok){let K=await E.json().catch(()=>({}));throw new Error(K.error||`API error: ${E.status}`)}let Q=await E.json().catch(()=>({}));g({}),x({}),h(true),M(K=>K+1),O([]),te.current.clear(),et(Se,new Set),et(me,new Set),k.current.clear(),C.current.clear();try{for(let K=sessionStorage.length-1;K>=0;K-=1){let W=sessionStorage.key(K);W&&W.startsWith("__fork_animated_")&&sessionStorage.removeItem(W);}}catch{}return Q},[Se,me,t,o,r,ee,z]);return vo.jsx(gn.Provider,{value:{apiKey:t,userId:z,userHash:ee,baseUrl:r,appId:o,forks:b,moduleOverridesEnabled:ve,moduleManifestReady:H,moduleManifestVersion:v,currentContainerId:N,forksPaused:j,setForksPaused:Me,forkActivities:L,activitySummary:ir,previewSession:U,trackForkActivity:ct,recordForkActivityEvent:ot,markForkActivitySeen:Le,refreshForkActivities:Fe,setSlotFork:ze,clearSlotFork:nt,skipAnimationForSlot:Pe,shouldSkipAnimation:We,queueBoundaryAnimation:Je,consumeBoundaryAnimation:Ct,registerBoundary:or,getBoundaryOverride:$t,refreshModuleManifest:se,resetAllForks:qe,highlightScope:Pt},children:n})}function ye(){let e=vr.useContext(gn);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Wt(e){return ye().forks[e]}var ht=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(s=>s());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function Sr(e,t){let r;try{r=vr.Children.only(e);}catch{let o=vr.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 hn=new Set;function yn(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Qo(e,t){let r=[];for(let n of t)if(!e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Zo(e,t){let r=[];for(let n of e)if(!t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function bn(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 kn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g++){let{rect:d,borderRadius:w}=e[g],I=d.left-.5,f=d.top-.5,m=d.width+1,x=d.height+1,H=Math.min(w+.5,m/2,x/2),h=bn(I,f,m,x,H),v=`__fork-glow-${g}`,M=document.createElementNS(t,"filter");M.setAttribute("id",v),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),M.appendChild(N),o.appendChild(M);let D=`__fork-mask-${g}`,j=document.createElementNS(t,"mask");j.setAttribute("id",D),j.setAttribute("maskUnits","userSpaceOnUse"),j.setAttribute("x",String(I-200)),j.setAttribute("y",String(f-200)),j.setAttribute("width",String(m+400)),j.setAttribute("height",String(x+400));let _=document.createElementNS(t,"rect");_.setAttribute("x",String(I-200)),_.setAttribute("y",String(f-200)),_.setAttribute("width",String(m+400)),_.setAttribute("height",String(x+400)),_.setAttribute("fill","white"),j.appendChild(_);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),j.appendChild(L),o.appendChild(j);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${D})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",h),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),S.appendChild(c),O.appendChild(S),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",h),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(c,F),c.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let g=0;g<s.length;g+=2){let d=s[g],w=s[g+1],I=d.__group,f=w.getTotalLength(),m=d.getTotalLength();if(f<=0)continue;let x=f*.35;w.setAttribute("stroke-dasharray",`${x} ${f-x}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*f,opacity:.92,offset:.06},{strokeDashoffset:-2*f,opacity:.92,offset:.92},{strokeDashoffset:-2.25*f,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let H=m*.35;d.setAttribute("stroke-dasharray",`${H} ${m-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*m,offset:.06},{strokeDashoffset:-2*m,offset:.92},{strokeDashoffset:-2.25*m,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,u=()=>{if(a)return;a=true,clearTimeout(b);for(let d of i)try{d.cancel();}catch{}let g=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});g.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function es(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:u}of e){let b=a.left,g=a.top,d=a.width,w=a.height,I=Math.min(u,d/2,w/2),f=bn(b,g,d,w,I),m=document.createElementNS(t,"path");m.setAttribute("d",f),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),m.setAttribute("stroke-width","1.5"),m.setAttribute("stroke-dasharray","8 4"),m.setAttribute("stroke-linecap","round"),m.setAttribute("filter","url(#__fork-removed-shadow)"),m.setAttribute("opacity","0"),n.appendChild(m),m.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 ts(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 rs=vr__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return vo.jsx("div",{ref:r,style:n,children:vo.jsx(t,{...o})})},(e,t)=>e.component===t.component&&ts(e.hostProps,t.hostProps)),wr=class extends vr__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 wn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){Sr(t,e);let i=Wt(e),{baseUrl:a,apiKey:u,appId:b,shouldSkipAnimation:g}=ye(),[d,w]=vr.useState(null),I=vr.useRef(null),f=vr.useRef(null),m=vr.useRef(null),x=vr.useRef(false),H=vr.useRef(null),h=vr.useRef(null),v=!!(n||o),M=vr.useRef(null);v&&!M.current&&(M.current=new ht(e));let N=vr.useRef(o);if(N.current=o,vr.useEffect(()=>{if(v)return ()=>{M.current?.destroy(),M.current=null;}},[v,e]),v&&M.current&&n)for(let[O,S]of Object.entries(n))M.current.set(O,S);vr.useEffect(()=>{if(!v)return;M.current||(M.current=new ht(e));let O=M.current,S=Object.keys(N.current||{}).map(c=>O.on(c,(...F)=>N.current?.[c]?.(...F)));return ()=>S.forEach(c=>c())},[v,e]),vr.useEffect(()=>{if(hn.has(e))return;hn.add(e);let O={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${a}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify(O)}).catch(()=>{});},[e,a,u,r,b,s]);let D=i?.id||null;vr.useEffect(()=>{if(i?.bundleUrl,I.current,f.current,!i?.bundleUrl||!D){return}let O=`${a}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,c=sessionStorage.getItem(S),F=g(e),$=!F&&c!==D;if(F&&D&&sessionStorage.setItem(S,D),$&&f.current){let G=yn(f.current);m.current=G,x.current=true,`${e}${G.length}`;}window.__FORK_REACT__=vr__namespace.default,window.__FORK_REACT_DOM__=wo__namespace,window.__FORK_REACT_JSX__=vo__namespace;let P=Date.now(),A=`${a}${i.bundleUrl.replace("bundle.js","component.css")}?t=${P}`,k=document.createElement("link");k.rel="stylesheet",k.href=A,k.dataset.forkSlot=e,document.head.appendChild(k);let C=document.createElement("script");return C.src=O+"?t="+P,C.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(f.current&&m.current&&x.current){let V=f.current.getBoundingClientRect(),q=f.current.cloneNode(true);q.setAttribute("data-fork-clone-overlay","true"),q.style.position="fixed",q.style.top=`${V.top}px`,q.style.left=`${V.left}px`,q.style.width=`${V.width}px`,q.style.height=`${V.height}px`,q.style.flex="none",q.style.minHeight="auto",q.style.zIndex="9998",q.style.pointerEvents="none",q.style.overflow="hidden";let te=getComputedStyle(f.current).backgroundColor;q.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(q);let X=f.current.querySelectorAll("*"),U=q.querySelectorAll("*");for(let ne=0;ne<X.length;ne++)X[ne].scrollTop!==0&&(U[ne].scrollTop=X[ne].scrollTop),X[ne].scrollLeft!==0&&(U[ne].scrollLeft=X[ne].scrollLeft);H.current=q;}w(()=>G.default),I.current=D;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},C.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(C),()=>{C.remove(),k.remove(),h.current&&(clearTimeout(h.current),h.current=null),H.current&&(H.current.remove(),H.current=null);}},[D,a,e]),vr.useEffect(()=>{if(!x.current||!d||!f.current){`${e}${x.current}`,f.current;return}let O=m.current;if(!O){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!f.current)return;let S=yn(f.current),c=Qo(O,S),F=Zo(O,S),$=H.current;if(`${e}${c.length}${F.length}`,F.length>0&&$){let P=es(F);h.current=setTimeout(()=>{h.current=null;let A=400;$.animate([{opacity:1},{opacity:0}],{duration:A,fill:"forwards"}),P.animate([{opacity:1},{opacity:0}],{duration:A,fill:"forwards"}),setTimeout(()=>{$.remove(),P.remove(),H.current=null,c.length>0&&(kn(c));},A);},3500);}else $&&($.remove(),H.current=null),c.length>0&&(kn(c));m.current=null,x.current=false,D&&(sessionStorage.setItem(`__fork_animated_${e}`,D),`${e}`);});});},[d]);let j={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return vo.jsx("div",{ref:f,style:j,children:t});if(!d)return vo.jsx("div",{ref:f,style:j,children:t});let L=t?.props??{};return vo.jsx(wr,{slotId:e,resetKey:D,fallback:vo.jsx("div",{ref:f,style:j,children:t}),children:vo.jsx(rs,{component:d,containerRef:f,wrapperStyle:j,hostProps:L})})}var Sn=new Set;function ss(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 Fn(e,t=new Set){return vr.Children.forEach(e,r=>{if(!vr.isValidElement(r))return;let n=r.props;for(let[o,s]of Object.entries(n))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&Fn(n.children,t);}),t}function is({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:a="iframe",shared:u,events:b}){if(Sr(r,e),a==="direct")return vo.jsx(wn,{slotId:e,githubRepo:s,shared:u,events:b,entityBindings:o,children:r});let g=Wt(e),{baseUrl:d,apiKey:w,appId:I,userId:f,userHash:m,currentContainerId:x,previewSession:H}=ye(),h=vr.useRef(null),v=vr.useRef(false),M=vr.useRef(null),N=vr.useRef(i);N.current=i;let D=vr.useRef(t);D.current=t;let j=vr.useRef(n);j.current=n,vr.useEffect(()=>{if(typeof process<"u")return;let S=Fn(r),c=new Set(i?Object.keys(i):[]),F=[...S].filter($=>!c.has($));F.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
3
3
  `+F.map($=>` - ${$}`).join(`
4
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),vr.useEffect(()=>{Sn.has(e)||(Sn.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?ss(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,d,w,s,I,o]);let _=vr.useCallback(S=>{let c=h.current;if(c?.contentWindow&&v.current){let F=N.current?Object.keys(N.current):[];c.contentWindow.postMessage({type:"slot:props",props:S,callbackNames:F},"*"),M.current=null;}else M.current=S;},[]),L=vr.useCallback((S,c)=>{let F=j.current;return !F||F.length===0?false:F.some($=>{let[P,A]=$.split(" "),k=c.split("?")[0];return S.toUpperCase()===P.toUpperCase()&&k.startsWith(A)})},[]);if(vr.useEffect(()=>{if(!g?.bundleUrl)return;let S=async c=>{if(c.source===h.current?.contentWindow){if(c.data?.type==="slot:ready")v.current=true,h.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:j.current||[]},"*"),j.current,M.current?_(M.current):_(D.current||{});else if(c.data?.type==="slot:event"){let F=c.data.event;F?.navigate&&(window.location.hash=F.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(F=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,F.message);});else if(c.data?.type==="slot:callback"){let{name:F,args:$}=c.data,P=N.current?.[F];P?(P(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(c.data?.type==="slot:fetch"){let{id:F,method:$,url:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;let C=$||"GET";if(!L(C,P)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${C} ${P} \u2014 not in allowedFetches`),k.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${C} ${P}`},"*");return}try{let G={method:C};A&&C!=="GET"&&(G.headers={"Content-Type":"application/json"},G.body=JSON.stringify(A));let V=await fetch(P,G),q=await V.json();`${e}${F}${V.status}`,k.postMessage({type:"slot:fetch-response",id:F,data:q,status:V.status},"*");}catch(G){console.error(`[ForkSlot:${e}] fetch #${F} failed:`,G.message),k.postMessage({type:"slot:fetch-response",id:F,error:G.message},"*");}}else if(c.data?.type==="slot:fork-data"){let{id:F,path:$,method:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;if(!x||!I){k.postMessage({type:"slot:fork-data-response",id:F,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let C=typeof $=="string"&&$.startsWith("/")?$:`/${String($||"")}`,G=C.startsWith("/api/v1/data")?C:`/api/v1/data${C}`;try{let V={Authorization:`Bearer ${w}`,"Content-Type":"application/json","X-Fork-App-Id":I,...oe()};!H&&f&&(V["X-Fork-User-Id"]=f),!H&&m&&(V["X-Fork-User-Hash"]=m);let q=typeof P=="string"?P.toUpperCase():"POST",te=new URL(`${d}${G}`),X={method:q,headers:V};q==="GET"?(te.searchParams.set("appId",I),te.searchParams.set("containerId",x)):X.body=JSON.stringify({appId:I,containerId:x,...A&&typeof A=="object"?A:{}});let U=await fetch(te.toString(),X),ne=await U.json().catch(()=>({}));if(!U.ok){let _e=typeof ne?.error=="string"?ne.error:`Fork data API ${U.status}`;k.postMessage({type:"slot:fork-data-response",id:F,error:_e,status:U.status},"*");return}k.postMessage({type:"slot:fork-data-response",id:F,data:ne,status:U.status},"*");}catch(V){k.postMessage({type:"slot:fork-data-response",id:F,error:V.message},"*");}}}};return window.addEventListener("message",S),()=>{window.removeEventListener("message",S),v.current=false;}},[g?.bundleUrl,e,_,L,x,I,w,d,H,m,f]),vr.useEffect(()=>{g?.bundleUrl&&v.current&&_(t||{});},[t,g?.bundleUrl,_]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,vo.jsx(vo.Fragment,{children:r});`${e}${g.bundleUrl}`;let O=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return vo.jsx("iframe",{ref:h,src:O,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Vt({style:e={width:20,height:20},...t}){return vo.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[vo.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"}),vo.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),vo.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"}),vo.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"}),vo.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var ds=5600,xr=2147483002;function fs(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ps(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Ar(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function gs(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function Ir({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=vr.useState(false),[s,i]=vr.useState(false),[a,u]=vr.useState(null),[b,g]=vr.useState(null),[d,w]=vr.useState(null),I=vr.useRef(0),f=n?48:40,m=fs(r),x=!!(m&&r?.state==="complete"&&r.unreadCompletedCount>0),H=x?m:b?.key??null,h=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(H&&H!==a&&(x||b)),M=h||v,N=x?r?.label:b?.label,D=v?"Built":r?.label??"Fork this app",j=v?N:r?.detail,_=Ar(r?.label??"Fork this app",r?.detail),L=Ar(D,j),O=v?Math.min(420,Math.max(326,L,b?.width??0,I.current+40)):L,S=v?46:40,c=M?[D,j].filter(Boolean).join(" "):gs(r,t)??"Fork this app",F=M?`${D}:${j??""}`:"idle",$=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!M;vr.useEffect(()=>{if(typeof document>"u")return;let X=document.createElement("div");return X.setAttribute("data-fork-button-host","true"),X.style.position="relative",X.style.zIndex=String(xr),document.body.appendChild(X),w(X),()=>{X.remove(),w(null);}},[]),vr.useEffect(()=>{h&&(I.current=_);},[_,h]),vr.useEffect(()=>{!x||!m||!r?.label||g(X=>{if(X?.key===m)return X;let U=Math.min(420,Math.max(326,Ar("Built",r.label),I.current+40));return {key:m,label:r.label,width:U,startedAt:Date.now()}});},[r?.label,m,x]),vr.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&g(null);},[r?.state,r?.unreadCompletedCount]),vr.useEffect(()=>{if(!H||!v||H===a)return;let X,U=b?.key===H?b.startedAt:Date.now(),ne=()=>{if(Date.now()-U>=ds&&!ps()){u(H);return}X=window.setTimeout(ne,250);};return X=window.setTimeout(ne,250),()=>{X!==void 0&&window.clearTimeout(X);}},[H,a,b?.key,b?.startedAt,v]);let P=M?{position:"fixed",bottom:24,right:24,zIndex:xr,width:`min(${O}px, calc(100vw - 32px))`,height:S,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:v?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":"center",gap:v?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:v?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:xr,width:f,height:f,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},A={minWidth:0,maxWidth:h?286:v?82:j?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},k={minWidth:0,maxWidth:v?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:v?1:0,color:"#64748b",fontSize:h?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},C={minWidth:0,flex:v?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},G={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:v?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},te=vo.jsxs(vo.Fragment,{children:[vo.jsx("style",{children:`
4
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),vr.useEffect(()=>{Sn.has(e)||(Sn.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?ss(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,d,w,s,I,o]);let _=vr.useCallback(S=>{let c=h.current;if(c?.contentWindow&&v.current){let F=N.current?Object.keys(N.current):[];c.contentWindow.postMessage({type:"slot:props",props:S,callbackNames:F},"*"),M.current=null;}else M.current=S;},[]),L=vr.useCallback((S,c)=>{let F=j.current;return !F||F.length===0?false:F.some($=>{let[P,A]=$.split(" "),k=c.split("?")[0];return S.toUpperCase()===P.toUpperCase()&&k.startsWith(A)})},[]);if(vr.useEffect(()=>{if(!g?.bundleUrl)return;let S=async c=>{if(c.source===h.current?.contentWindow){if(c.data?.type==="slot:ready")v.current=true,h.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:j.current||[]},"*"),j.current,M.current?_(M.current):_(D.current||{});else if(c.data?.type==="slot:event"){let F=c.data.event;F?.navigate&&(window.location.hash=F.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(F=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,F.message);});else if(c.data?.type==="slot:callback"){let{name:F,args:$}=c.data,P=N.current?.[F];P?(P(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(c.data?.type==="slot:fetch"){let{id:F,method:$,url:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;let C=$||"GET";if(!L(C,P)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${C} ${P} \u2014 not in allowedFetches`),k.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${C} ${P}`},"*");return}try{let G={method:C};A&&C!=="GET"&&(G.headers={"Content-Type":"application/json"},G.body=JSON.stringify(A));let V=await fetch(P,G),q=await V.json();`${e}${F}${V.status}`,k.postMessage({type:"slot:fetch-response",id:F,data:q,status:V.status},"*");}catch(G){console.error(`[ForkSlot:${e}] fetch #${F} failed:`,G.message),k.postMessage({type:"slot:fetch-response",id:F,error:G.message},"*");}}else if(c.data?.type==="slot:fork-data"){let{id:F,path:$,method:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;if(!x||!I){k.postMessage({type:"slot:fork-data-response",id:F,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let C=typeof $=="string"&&$.startsWith("/")?$:`/${String($||"")}`,G=C.startsWith("/api/v1/data")?C:`/api/v1/data${C}`;try{let V={Authorization:`Bearer ${w}`,"Content-Type":"application/json","X-Fork-App-Id":I,...oe()};!H&&f&&(V["X-Fork-User-Id"]=f),!H&&m&&(V["X-Fork-User-Hash"]=m);let q=typeof P=="string"?P.toUpperCase():"POST",te=new URL(`${d}${G}`),X={method:q,headers:V};q==="GET"?(te.searchParams.set("appId",I),te.searchParams.set("containerId",x)):X.body=JSON.stringify({appId:I,containerId:x,...A&&typeof A=="object"?A:{}});let U=await fetch(te.toString(),X),ne=await U.json().catch(()=>({}));if(!U.ok){let _e=typeof ne?.error=="string"?ne.error:`Fork data API ${U.status}`;k.postMessage({type:"slot:fork-data-response",id:F,error:_e,status:U.status},"*");return}k.postMessage({type:"slot:fork-data-response",id:F,data:ne,status:U.status},"*");}catch(V){k.postMessage({type:"slot:fork-data-response",id:F,error:V.message},"*");}}}};return window.addEventListener("message",S),()=>{window.removeEventListener("message",S),v.current=false;}},[g?.bundleUrl,e,_,L,x,I,w,d,H,m,f]),vr.useEffect(()=>{g?.bundleUrl&&v.current&&_(t||{});},[t,g?.bundleUrl,_]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,vo.jsx(vo.Fragment,{children:r});`${e}${g.bundleUrl}`;let O=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return vo.jsx("iframe",{ref:h,src:O,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Vt({style:e={width:20,height:20},...t}){return vo.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[vo.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"}),vo.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),vo.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"}),vo.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"}),vo.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var ds=5600,xr=2147483002;function fs(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ps(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Ar(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function gs(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function Ir({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=vr.useState(false),[s,i]=vr.useState(false),[a,u]=vr.useState(null),[b,g]=vr.useState(null),[d,w]=vr.useState(null),I=vr.useRef(0),f=n?48:40,m=fs(r),x=!!(m&&r?.state==="complete"&&r.unreadCompletedCount>0),H=x?m:b?.key??null,h=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(H&&H!==a&&(x||b)),M=h||v,N=x?r?.label:b?.label,D=v?"Built":r?.label??"Fork this app",j=v?N:r?.detail,_=Ar(r?.label??"Fork this app",r?.detail),L=Ar(D,j),O=v?Math.min(420,Math.max(326,L,b?.width??0,I.current+40)):L,S=v?46:40,c=M?[D,j].filter(Boolean).join(" "):gs(r,t)??"Fork this app",F=M?`${D}:${j??""}`:"idle",$=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!M;vr.useEffect(()=>{if(typeof document>"u")return;let X=document.createElement("div");return X.setAttribute("data-fork-button-host","true"),X.style.position="relative",X.style.zIndex=String(xr),document.body.appendChild(X),w(X),()=>{X.remove(),w(null);}},[]),vr.useEffect(()=>{h&&(I.current=_);},[_,h]),vr.useEffect(()=>{!x||!m||!r?.label||g(X=>{if(X?.key===m)return X;let U=Math.min(420,Math.max(326,Ar("Built",r.label),I.current+40));return {key:m,label:r.label,width:U,startedAt:Date.now()}});},[r?.label,m,x]),vr.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&g(null);},[r?.state,r?.unreadCompletedCount]),vr.useEffect(()=>{if(!H||!v||H===a)return;let X,U=b?.key===H?b.startedAt:Date.now(),ne=()=>{if(Date.now()-U>=ds&&!ps()){u(H);return}X=window.setTimeout(ne,250);};return X=window.setTimeout(ne,250),()=>{X!==void 0&&window.clearTimeout(X);}},[H,a,b?.key,b?.startedAt,v]);let P=M?{position:"fixed",bottom:24,right:24,zIndex:xr,width:`min(${O}px, calc(100vw - 32px))`,height:S,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:v?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":"center",gap:v?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:v?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:xr,width:f,height:f,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},A={minWidth:0,maxWidth:h?286:v?82:j?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},k={minWidth:0,maxWidth:v?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:v?1:0,color:"#64748b",fontSize:h?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},C={minWidth:0,flex:v?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},G={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:v?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},te=vo.jsxs(vo.Fragment,{children:[vo.jsx("style",{children:`
5
5
  @keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
6
6
  @keyframes __forkButtonTextSwap {
7
7
  from { opacity: 0; transform: translateY(2px); }
@@ -16,7 +16,7 @@
16
16
  70% { opacity: 1; transform: scale(1.18); }
17
17
  100% { opacity: 1; transform: scale(1); }
18
18
  }
19
- `}),vo.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:P,title:c,"aria-label":c,children:[M&&r?vo.jsxs(vo.Fragment,{children:[h?vo.jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(37, 99, 235, 0.18)",borderTopColor:"#2563eb",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):vo.jsx("span",{"aria-hidden":true,style:G}),vo.jsxs("span",{style:C,children:[vo.jsx("span",{style:A,children:D}),j&&vo.jsx("span",{style:k,children:j})]},F)]}):vo.jsx(Vt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),$&&vo.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#2563eb",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return d?wo.createPortal(te,d):te}var Ss={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},Fs={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},xs={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},As={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Rr(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 Cn({events:e}){let t=vr.useRef(null);return vr.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),vo.jsxs(vo.Fragment,{children:[vo.jsx("style",{children:`
19
+ `}),vo.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:P,title:c,"aria-label":c,children:[M&&r?vo.jsxs(vo.Fragment,{children:[h?vo.jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(17, 24, 39, 0.18)",borderTopColor:"#111827",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):vo.jsx("span",{"aria-hidden":true,style:G}),vo.jsxs("span",{style:C,children:[vo.jsx("span",{style:A,children:D}),j&&vo.jsx("span",{style:k,children:j})]},F)]}):vo.jsx(Vt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),$&&vo.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#111827",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return d?wo.createPortal(te,d):te}var Ss={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},Fs={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},xs={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},As={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Rr(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 Cn({events:e}){let t=vr.useRef(null);return vr.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),vo.jsxs(vo.Fragment,{children:[vo.jsx("style",{children:`
20
20
  @keyframes __fork-spin {
21
21
  from { transform: rotate(0deg); }
22
22
  to { transform: rotate(360deg); }
@@ -56,7 +56,7 @@
56
56
  scrollbar-width: thin;
57
57
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
58
58
  }
59
- `}),vo.jsxs("div",{className:"__fork-panel",style:yo,children:[vo.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:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[vo.jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!_e&&confirm("Kill all forks in this container?")){z(true);try{let R=await fe();`${R?.deleted??0}`,Q([]),W(null),ie(!1),v("");}catch(R){console.error("[Fork] Reset failed:",R);}finally{z(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:vo.jsx(Vt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?vo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:mo}):ee.length===0&&!Ie?vo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ie?vo.jsxs("div",{ref:Ut,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[vo.jsxs("button",{type:"button",onClick:()=>{We(l=>!l);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(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:Je||Pe?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[vo.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rn}),vo.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Pe&&vo.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[ee.map(l=>{let R=l.id===se,B=or===l.id,he=ge===l.id;return vo.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>$t(l.id),onMouseLeave:()=>$t(null),onClick:()=>{l.id!==se&&ho(l.id);},disabled:!!ge,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:B?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",fontWeight:R?600:400,opacity:ge&&!he?.55:1},children:[vo.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:R&&vo.jsx(lucideReact.Check,{style:{width:12,height:12}})}),vo.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:he?"Switching...":l.name})]},l.id)}),vo.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Se?vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[vo.jsx("input",{ref:ct,type:"text",value:Te,placeholder:"Container name",disabled:ge==="__new__",onChange:l=>Fe(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),Zr(Te)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),me(false),Fe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:l=>{l.currentTarget.style.borderColor="#1c4587",l.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none";}}),vo.jsx("button",{type:"button",onClick:()=>{Zr(Te);},disabled:!Te.trim()||ge==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Te.trim()||ge==="__new__"?"#e5e7eb":"#1c4587",color:!Te.trim()||ge==="__new__"?"#9ca3af":"#ffffff",cursor:!Te.trim()||ge==="__new__"?"default":"pointer",flexShrink:0},children:ge==="__new__"?vo.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):vo.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):vo.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pt(true),onMouseLeave:()=>Pt(false),onClick:()=>{ge||(Le(null),Fe(""),me(true));},disabled:!!ge,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:sr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",opacity:ge&&ge!=="__new__"?.55:1},children:"+ New container"}),ot&&vo.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:ot})]})]}):vo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rn}),e==="running"&&vo.jsx("span",{title:Xe?`Estimated ~${Xe} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Xe?"#1c4587":"#9ca3af",backgroundColor:Xe?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Xe?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Xe?`~${Xe}m`:"~ m"})]}),vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[ut&&vo.jsx("button",{type:"button",role:"switch","aria-checked":!le,"aria-label":le?"Turn Fork back on":"Turn Fork off",title:le?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ae(!le);},onMouseEnter:()=>Mt(true),onMouseLeave:()=>Mt(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:le?Tt?"#9ca3af":"#d1d5db":Tt?"#27599c":"#1c4587",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:vo.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:le?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!x&&vo.jsxs(vo.Fragment,{children:[qr&&vo.jsx("button",{onClick:$e?po:fo,onMouseEnter:()=>P(true),onMouseLeave:()=>P(false),title:$e?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:$?"#4b5563":"#9ca3af",backgroundColor:$?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:$e?vo.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):vo.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),vo.jsx("button",{onClick:tn,onMouseEnter:()=>F(true),onMouseLeave:()=>F(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:vo.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),vo.jsxs("div",{ref:de,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(K||re)&&vo.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[vo.jsx("button",{onClick:()=>{W(null),ie(false),ce.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let R=(K?E.find(B=>B.id===K)?.targetId:null)??st;return R?vo.jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${R}`,children:["Forking ",vo.jsx("span",{style:{color:"#6b7280"},children:R})]}):null})()]}),!K&&!re&&vo.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[vo.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:vo.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),E.length===0&&vo.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),E.length>0&&vo.jsx("div",{style:{display:"flex",flexDirection:"column"},children:E.map(l=>{let R=l.summary||"Untitled fork";return vo.jsxs("button",{onClick:()=>{ie(false),W(l.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:B=>B.currentTarget.style.background="#fafafa",onMouseLeave:B=>B.currentTarget.style.background="#ffffff",children:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[vo.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:R}),vo.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Hs(l.updatedAt)})]}),vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[vo.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),vo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),vo.jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?vo.jsxs(vo.Fragment,{children:[vo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),vo.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},l.id)})})]}),K&&dt.length>0&&vo.jsx("div",{style:{padding:"16px 16px 0 16px"},children:dt.map((l,R)=>vo.jsx("div",{style:{marginBottom:R<dt.length-1?10:0},children:l.type==="user"?vo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[vo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:vo.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),vo.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:l.text})]}):H==="item"&&R===dt.length-1?vo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[vo.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:vo.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),vo.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[vo.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),vo.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),b&&e!=="running"&&vo.jsx("button",{onClick:B=>{B.stopPropagation(),en();},disabled:te,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:te?"default":"pointer",opacity:te?.4:1,height:28,flexShrink:0},children:"Undo"})]}):vo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[vo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:vo.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),vo.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:[vo.jsx("span",{style:{flex:1},children:l.text}),b&&R===dt.length-1&&e!=="running"&&vo.jsxs("button",{onClick:B=>{B.stopPropagation(),en();},onMouseEnter:()=>ne(R),onMouseLeave:()=>ne(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:U===R?"rgba(0,0,0,0.06)":"transparent",color:U===R?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[vo.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),U===R&&vo.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"})]})]})]})},R))}),e==="running"&&(K||re)&&vo.jsx("div",{style:{padding:16},children:vo.jsxs("div",{onClick:()=>q(!V),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[vo.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:vo.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),vo.jsx(Us,{events:r})]}),vo.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:vo.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),vo.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:vo.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:vo.jsx(Cn,{events:r})})})]})}),e==="error"&&(K||re)&&vo.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[vo.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:vo.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),vo.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),vo.jsxs("button",{onClick:()=>{let l=t?.prompt||Ht.current;l&&u(l,st);},onMouseEnter:()=>G(true),onMouseLeave:()=>G(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:C?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[vo.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&vo.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[vo.jsx("textarea",{ref:ue,value:h,onChange:l=>{v(l.target.value),l.target.style.height="auto",l.target.style.height=Math.min(l.target.scrollHeight,160)+"px";},onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Yr()),l.key==="Escape"&&!x&&tn();},placeholder:K?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),vo.jsx("button",{onClick:Yr,disabled:!h.trim(),onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:h.trim()?1:.25,transform:A&&h.trim()?"scale(1.1)":"scale(1)",background:h.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:h.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:vo.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return x?lr:$e&&p?wo.createPortal(lr,p.document.body):vo.jsx(Bs,{children:lr})}function Hn(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 $r(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:b,recordForkActivityEvent:g}=ye(),[d,w]=vr.useState("idle"),[I,f]=vr.useState(null),[m,x]=vr.useState([]),[H,h]=vr.useState(null),v=vr.useRef(null),M=vr.useCallback(()=>{w("prompting"),x([]),h(null),f(null);},[]),N=vr.useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]);vr.useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&w(L=>L==="idle"?"prompting":L);},[i?.preview_session_id,i?.target.id,e]);let D=vr.useCallback(async(L,O,S)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),x([]),h(null),f(null);let c;if(i){let P=S?.forkId??i.fork_id??void 0,A=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...oe()},body:JSON.stringify({prompt:L,...e?{boundary_id:e}:{},...P&&!S?.forceNew?{fork_id:P}:{},...S?.forceNew?{force_new:!0}:{}})});if(!A.ok){let G=await A.json().catch(()=>({}));throw new Error(G.error||`API error: ${A.status}`)}let k=await A.json();k.container_id&&Ye(k.container_id,k.container_name),ft(k.fork_id),c=await(await fetch(`${o}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...oe()}})).json();}else if(S?.forkId){let P={prompt:L};r&&(P.userId=r),n&&(P.userHash=n);let A=await fetch(`${o}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}else {let P={userId:r,prompt:L,boundaryId:e,appId:s};O&&(P.containerId=O),n&&(P.userHash=n),S?.forceNew&&(P.force_new=!0);let A=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}f(c),b(c,{targetKind:"module",targetId:e});let F=new URLSearchParams({key:t});i?(F.set("previewSessionId",i.preview_session_id),F.set("previewForkId",c.id)):r&&F.set("userId",r),n&&F.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${c.id}/events?${F.toString()}`);v.current=$,$.onmessage=P=>{try{let A=JSON.parse(P.data);if(g(c.id,A),x(k=>[...k,A]),A.type==="complete"){let k=A.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let C={...c,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};f(C),w("complete"),$.close();});}else if(A.type==="error"){let k=A.data;h(k.error||"Unknown error"),w("error"),$.close();}}catch{}},$.onerror=()=>{let P={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(P["X-Fork-User-Id"]=r),!i&&n&&(P["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:P}).then(A=>A.json()).then(A=>{f(A),A.status==="complete"?(u(e,A.id),a().catch(()=>{}),w("complete")):A.status==="error"&&(h(A.error||"Fork generation failed"),w("error"));}).catch(()=>{h("Connection lost"),w("error");}),$.close();};}catch(c){h(c.message),w("error");}},[t,s,o,e,i,u,a,g,b,n,r]),j=vr.useCallback(async L=>{try{let O={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(O["X-Fork-User-Id"]=r),!i&&n&&(O["X-Fork-User-Hash"]=n);let S=await fetch(`${o}/api/v1/forks/${L}`,{headers:O});if(!S.ok)return;let c=await S.json(),F=c.boundaryId??e;if(b(c,{targetKind:"module",targetId:F}),c.status==="complete"){w("complete"),f(c),h(null),x([]);return}if(c.status==="error"){w("error"),f(c),h(c.error||"Fork generation failed"),x([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;w("running"),f(c),h(null),x([]);let $=new URLSearchParams({key:t});i?($.set("previewSessionId",i.preview_session_id),$.set("previewForkId",c.id)):r&&$.set("userId",r),n&&$.set("userHash",n);let P=new EventSource(`${o}/api/v1/forks/${c.id}/events?${$.toString()}`);v.current&&v.current.close(),v.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(g(c.id,k),x(C=>[...C,k]),k.type==="complete"){let C=k.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let G={...c,status:"complete",moduleUrl:C.moduleUrl,cssUrls:C.cssUrls,summary:C.summary,completedAt:new Date().toISOString()};f(G),w("complete"),P.close();});}else if(k.type==="error"){let C=k.data;h(C.error||"Unknown error"),w("error"),P.close();}}catch{}},P.onerror=()=>{P.close();};}catch{}},[t,o,e,i,u,g,a,b,n,r]),_=vr.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let L={userId:r,boundaryId:e,appId:s};n&&(L.userHash=n);let O=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return await a().catch(()=>{}),S.removed?(f(null),w("prompting")):S.fork&&(f(S.fork),w("complete")),S}catch(L){throw h(L.message),L}},[t,s,o,e,a,n,r]);return {state:d,fork:I,events:m,error:H,open:M,close:N,startFork:D,undoFork:_,adoptRunningFork:j}}var Ks=0;function Bn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:b}=$r(e),[g,d]=vr.useState(false),w=vr.useRef(null),I=vr.useRef(t),f=vr.useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),m=vr.useCallback(()=>{f(),d(true),s();},[f,s]),x=vr.useCallback(()=>{f(),d(false),i();},[f,i]),H=vr.useCallback(async h=>{f(),d(true),await b(h);},[b,f]);return vr.useEffect(()=>{let h=I.current;I.current=t,t==="complete"&&h==="running"&&g&&(f(),w.current=setTimeout(()=>{w.current=null,d(false),i();},Ks)),(t==="running"||t==="prompting")&&f();},[t,g,f,i]),vr.useEffect(()=>f,[f]),{state:t,fork:r,events:n,error:o,isOpen:g,open:m,close:x,submit:a,undo:u,adoptRunningFork:H}}function Pr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:b}=ye(),[g,d]=vr.useState("idle"),[w,I]=vr.useState(null),[f,m]=vr.useState([]),[x,H]=vr.useState(null),h=vr.useRef(null),v=vr.useCallback(()=>{d("prompting"),m([]),H(null),I(null);},[]),M=vr.useCallback(()=>{d("idle"),h.current&&(h.current.close(),h.current=null);},[]);vr.useEffect(()=>{o&&o.target.kind==="slot"&&d(_=>_==="idle"?"prompting":_);},[o?.preview_session_id,o?.target.kind]);let N=vr.useCallback(async(_,L,O,S)=>{try{d("running"),m([]),H(null),I(null);let c;if(o){let A=S?.forkId??o.fork_id??void 0,k=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...oe()},body:JSON.stringify({prompt:_,...L?{slot_id:L}:{},...A&&!S?.forceNew?{fork_id:A}:{},...S?.forceNew?{force_new:!0}:{}})});if(!k.ok){let V=await k.json().catch(()=>({}));throw new Error(V.error||`API error: ${k.status}`)}let C=await k.json();C.container_id&&Ye(C.container_id,C.container_name),ft(C.fork_id),c=await(await fetch(`${n}/api/v1/forks/${C.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...oe()}})).json();}else if(S?.forkId){let A={prompt:_};t&&(A.userId=t),r&&(A.userHash=r);let k=await fetch(`${n}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}else {let A={userId:t,prompt:_};L&&(A.slotId=L),O&&(A.containerId=O),r&&(A.userHash=r),S?.forceNew&&(A.force_new=!0);let k=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}I(c);let F=L??c.slotId;F&&u(c,{targetKind:"slot",targetId:F});let $=new URLSearchParams({key:e});o?($.set("previewSessionId",o.preview_session_id),$.set("previewForkId",c.id)):t&&$.set("userId",t),r&&$.set("userHash",r);let P=new EventSource(`${n}/api/v1/forks/${c.id}/events?${$.toString()}`);h.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(b(c.id,k),m(C=>[...C,k]),k.type==="complete"){let C=k.data,G={...c,status:"complete",bundleUrl:C.bundleUrl,summary:C.summary,completedAt:new Date().toISOString()};I(G),d("complete"),L&&C.bundleUrl&&s(L,G),P.close();}else if(k.type==="error"){let C=k.data;H(C.error||"Unknown error"),d("error"),P.close();}}catch{}},P.onerror=()=>{let A={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(A["X-Fork-User-Id"]=t),!o&&r&&(A["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:A}).then(k=>k.json()).then(k=>{I(k),k.status==="complete"?(d("complete"),L&&k.bundleUrl&&s(L,k)):k.status==="error"&&(H(k.error||"Fork generation failed"),d("error"));}).catch(()=>{H("Connection lost"),d("error");}),P.close();};}catch(c){H(c.message),d("error");}},[e,n,o,b,s,u,r,t]),D=vr.useCallback(async _=>{try{let L={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(L["X-Fork-User-Id"]=t),!o&&r&&(L["X-Fork-User-Hash"]=r);let O=await fetch(`${n}/api/v1/forks/${_}`,{headers:L});if(!O.ok)return;let S=await O.json();if(S.slotId&&u(S,{targetKind:"slot",targetId:S.slotId}),S.status==="complete"){d("complete"),I(S),H(null),m([]);return}if(S.status==="error"){d("error"),I(S),H(S.error||"Fork generation failed"),m([]);return}if(S.status!=="pending"&&S.status!=="running"&&S.status!=="building")return;d("running"),I(S),H(null),m([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",S.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let F=new EventSource(`${n}/api/v1/forks/${S.id}/events?${c.toString()}`);h.current&&h.current.close(),h.current=F;let $=S.slotId;F.onmessage=P=>{try{let A=JSON.parse(P.data);if(b(S.id,A),m(k=>[...k,A]),A.type==="complete"){let k=A.data,C={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};I(C),d("complete"),$&&k.bundleUrl&&s($,C),F.close();}else if(A.type==="error"){let k=A.data;H(k.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{F.close();};}catch{}},[e,n,o,b,s,u,r,t]),j=vr.useCallback(async _=>{try{let L={userId:t,slotId:_};r&&(L.userHash=r);let O=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return a(_),S.removed?(i(_),I(null),d("prompting")):S.fork&&(s(_,S.fork),I(S.fork)),S}catch(L){throw H(L.message),L}},[e,t,r,n,i,s]);return {state:g,fork:w,events:f,error:x,open:v,close:M,startFork:N,undoFork:j,adoptRunningFork:D}}var Vs=0;function jn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=Pr(),[b,g]=vr.useState(false),d=vr.useRef(null),w=vr.useRef(e),I=vr.useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),f=vr.useCallback(()=>{I(),g(true),o();},[I,o]),m=vr.useCallback(()=>{I(),g(false),s();},[I,s]),x=vr.useCallback(async H=>{I(),g(true),await u(H);},[u,I]);return vr.useEffect(()=>{let H=w.current;w.current=e,e==="complete"&&H==="running"&&b&&(I(),d.current=setTimeout(()=>{d.current=null,g(false),s();},Vs)),(e==="running"||e==="prompting")&&I();},[e,b,I,s]),vr.useEffect(()=>I,[I]),{state:e,fork:t,events:r,error:n,isOpen:b,open:f,close:m,submit:i,undo:a,adoptRunningFork:x}}var qs=new Set(["pending","running","building"]);function Mr(e){let t=Hn(e),r=jn(),n=Bn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:b,forkActivities:g,markForkActivitySeen:d}=ye(),w=t.type==="slot"?r:n,I=t.type==="slot"?"slot":"boundary",f=t.id,m=t.title,x=t.type==="slot"?"slot":"module",H=g.find(D=>D.targetKind===x&&D.targetId===t.id&&qs.has(D.status)),h=g.find(D=>D.targetKind===x&&D.targetId===t.id&&D.status==="complete"&&D.unread),v=vr.useCallback(()=>{d();let D=H??h;if(D){w.adoptRunningFork(D.id);return}w.open();},[w,d,H,h]),M=vr.useCallback((D,j,_,L)=>t.type==="slot"?r.submit(D,j??t.id,_,L):n.submit(D,_,L),[n,r,t]),N=vr.useCallback(D=>t.type==="slot"?r.undo(D??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:f,targetLabel:m,historyMode:I,submit:M,undo:N,buttonProps:{onClick:v,hasNotification:b.unreadCompletedCount>0,activity:b},panelProps:{state:w.state,fork:w.fork,events:w.events,error:w.error,...t.type==="slot"?{slotId:f,targetLabel:m,historyMode:I}:{targetId:f,targetLabel:m,historyMode:I},onSubmit:M,onUndo:N,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function xt(e){let{embedded:t,completeVariant:r}=e,n=Mr(e);return t?vo.jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?vo.jsx(Yt,{...n.panelProps,completeVariant:r}):vo.jsx(Ir,{...n.buttonProps})}function Xs({boundaryId:e,title:t}){return vo.jsx(xt,{boundaryId:e,title:t})}function Hr(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 Kn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Or(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function zn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Wn(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Jn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Ur(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g+=1){let{rect:d,borderRadius:w}=e[g],I=d.left-.5,f=d.top-.5,m=d.width+1,x=d.height+1,H=Math.min(w+.5,m/2,x/2),h=Jn(I,f,m,x,H),v=`__fork-glow-${g}`,M=document.createElementNS(t,"filter");M.setAttribute("id",v),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),M.appendChild(N),o.appendChild(M);let D=`__fork-mask-${g}`,j=document.createElementNS(t,"mask");j.setAttribute("id",D),j.setAttribute("maskUnits","userSpaceOnUse"),j.setAttribute("x",String(I-200)),j.setAttribute("y",String(f-200)),j.setAttribute("width",String(m+400)),j.setAttribute("height",String(x+400));let _=document.createElementNS(t,"rect");_.setAttribute("x",String(I-200)),_.setAttribute("y",String(f-200)),_.setAttribute("width",String(m+400)),_.setAttribute("height",String(x+400)),_.setAttribute("fill","white"),j.appendChild(_);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),j.appendChild(L),o.appendChild(j);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${D})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",h),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),S.appendChild(c),O.appendChild(S),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",h),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(c,F),c.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let g=0;g<s.length;g+=2){let d=s[g],w=s[g+1],I=d.__group;if(!I)continue;let f=w.getTotalLength(),m=d.getTotalLength();if(f<=0)continue;let x=f*.35;w.setAttribute("stroke-dasharray",`${x} ${f-x}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*f,opacity:.92,offset:.06},{strokeDashoffset:-2*f,opacity:.92,offset:.92},{strokeDashoffset:-2.25*f,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let H=m*.35;d.setAttribute("stroke-dasharray",`${H} ${m-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*m,offset:.06},{strokeDashoffset:-2*m,offset:.92},{strokeDashoffset:-2.25*m,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,u=()=>{if(a)return;a=true,clearTimeout(b);for(let d of i)try{d.cancel();}catch{}let g=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});g.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Vn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:u}of e){let b=document.createElementNS(t,"path");b.setAttribute("d",Jn(a.left,a.top,a.width,a.height,u)),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Gn(e,t){if(Ys(t.selector))return Xn(e,t);let n=Xn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(qn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Nr(e,g=>g===s);if(i)return i;let a=s.toLowerCase(),u=Nr(e,g=>g.toLowerCase()===a);if(u)return u;let b=Nr(e,g=>g.toLowerCase().includes(a));if(b)return b}}let o=Qs(t.selector);if(o&&o!==t.selector&&qn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function qn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Xn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Br(t.label),o=Br(t.textHint);return r.find(i=>{let a=Br(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function Ys(e){return e.trim()==="[data-fork-new]"}function Br(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Qs(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Nr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let u=a.width*a.height;u<n&&(r=s,n=u);}return r}var Dr=2147483600,Zs=1600,ei=3e4,ti=300,je=10;function ri(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let a=e.getBoundingClientRect(),u=Math.min(a.width,a.height);return Math.max(4,i/100*u)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function ni(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+je+8?a="bottom":a==="bottom"&&i-t.bottom<n+je+8?a="top":a==="left"&&t.left<r+je+8?a="right":a==="right"&&s-t.right<r+je+8&&(a="left");let u=0,b=0;return a==="top"?(u=t.top-n-je,b=t.left+t.width/2-r/2):a==="bottom"?(u=t.bottom+je,b=t.left+t.width/2-r/2):a==="left"?(u=t.top+t.height/2-n/2,b=t.left-r-je):(u=t.top+t.height/2-n/2,b=t.right+je),b=Math.max(8,Math.min(b,s-r-8)),u=Math.max(8,Math.min(u,i-n-8)),{top:u,left:b,placement:a}}function oi(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function si(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
59
+ `}),vo.jsxs("div",{className:"__fork-panel",style:yo,children:[vo.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:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[vo.jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!_e&&confirm("Kill all forks in this container?")){z(true);try{let R=await fe();`${R?.deleted??0}`,Q([]),W(null),ie(!1),v("");}catch(R){console.error("[Fork] Reset failed:",R);}finally{z(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:vo.jsx(Vt,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),e==="running"?vo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:mo}):ee.length===0&&!Ie?vo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ie?vo.jsxs("div",{ref:Ut,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[vo.jsxs("button",{type:"button",onClick:()=>{We(l=>!l);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(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:Je||Pe?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[vo.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rn}),vo.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Pe&&vo.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[ee.map(l=>{let R=l.id===se,B=or===l.id,he=ge===l.id;return vo.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>$t(l.id),onMouseLeave:()=>$t(null),onClick:()=>{l.id!==se&&ho(l.id);},disabled:!!ge,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:B?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",fontWeight:R?600:400,opacity:ge&&!he?.55:1},children:[vo.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:R&&vo.jsx(lucideReact.Check,{style:{width:12,height:12}})}),vo.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:he?"Switching...":l.name})]},l.id)}),vo.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Se?vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[vo.jsx("input",{ref:ct,type:"text",value:Te,placeholder:"Container name",disabled:ge==="__new__",onChange:l=>Fe(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),Zr(Te)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),me(false),Fe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:l=>{l.currentTarget.style.borderColor="#111827",l.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none";}}),vo.jsx("button",{type:"button",onClick:()=>{Zr(Te);},disabled:!Te.trim()||ge==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Te.trim()||ge==="__new__"?"#e5e7eb":"#111827",color:!Te.trim()||ge==="__new__"?"#9ca3af":"#ffffff",cursor:!Te.trim()||ge==="__new__"?"default":"pointer",flexShrink:0},children:ge==="__new__"?vo.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):vo.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):vo.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pt(true),onMouseLeave:()=>Pt(false),onClick:()=>{ge||(Le(null),Fe(""),me(true));},disabled:!!ge,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:sr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",opacity:ge&&ge!=="__new__"?.55:1},children:"+ New container"}),ot&&vo.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:ot})]})]}):vo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rn}),e==="running"&&vo.jsx("span",{title:Xe?`Estimated ~${Xe} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Xe?"#111827":"#9ca3af",backgroundColor:Xe?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Xe?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Xe?`~${Xe}m`:"~ m"})]}),vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[ut&&vo.jsx("button",{type:"button",role:"switch","aria-checked":!le,"aria-label":le?"Turn Fork back on":"Turn Fork off",title:le?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ae(!le);},onMouseEnter:()=>Mt(true),onMouseLeave:()=>Mt(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:le?Tt?"#9ca3af":"#d1d5db":Tt?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:vo.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:le?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!x&&vo.jsxs(vo.Fragment,{children:[qr&&vo.jsx("button",{onClick:$e?po:fo,onMouseEnter:()=>P(true),onMouseLeave:()=>P(false),title:$e?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:$?"#4b5563":"#9ca3af",backgroundColor:$?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:$e?vo.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):vo.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),vo.jsx("button",{onClick:tn,onMouseEnter:()=>F(true),onMouseLeave:()=>F(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:vo.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),vo.jsxs("div",{ref:de,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(K||re)&&vo.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[vo.jsx("button",{onClick:()=>{W(null),ie(false),ce.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let R=(K?E.find(B=>B.id===K)?.targetId:null)??st;return R?vo.jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${R}`,children:["Forking ",vo.jsx("span",{style:{color:"#6b7280"},children:R})]}):null})()]}),!K&&!re&&vo.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[vo.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:vo.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),E.length===0&&vo.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),E.length>0&&vo.jsx("div",{style:{display:"flex",flexDirection:"column"},children:E.map(l=>{let R=l.summary||"Untitled fork";return vo.jsxs("button",{onClick:()=>{ie(false),W(l.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:B=>B.currentTarget.style.background="#fafafa",onMouseLeave:B=>B.currentTarget.style.background="#ffffff",children:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[vo.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:R}),vo.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Hs(l.updatedAt)})]}),vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[vo.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),vo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),vo.jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?vo.jsxs(vo.Fragment,{children:[vo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),vo.jsx("span",{style:{color:"#111827"},children:"running"})]}):null]})]},l.id)})})]}),K&&dt.length>0&&vo.jsx("div",{style:{padding:"16px 16px 0 16px"},children:dt.map((l,R)=>vo.jsx("div",{style:{marginBottom:R<dt.length-1?10:0},children:l.type==="user"?vo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[vo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:vo.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),vo.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:l.text})]}):H==="item"&&R===dt.length-1?vo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[vo.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:vo.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),vo.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[vo.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),vo.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),b&&e!=="running"&&vo.jsx("button",{onClick:B=>{B.stopPropagation(),en();},disabled:te,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:te?"default":"pointer",opacity:te?.4:1,height:28,flexShrink:0},children:"Undo"})]}):vo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[vo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:vo.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),vo.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:[vo.jsx("span",{style:{flex:1},children:l.text}),b&&R===dt.length-1&&e!=="running"&&vo.jsxs("button",{onClick:B=>{B.stopPropagation(),en();},onMouseEnter:()=>ne(R),onMouseLeave:()=>ne(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:U===R?"rgba(0,0,0,0.06)":"transparent",color:U===R?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[vo.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),U===R&&vo.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"})]})]})]})},R))}),e==="running"&&(K||re)&&vo.jsx("div",{style:{padding:16},children:vo.jsxs("div",{onClick:()=>q(!V),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[vo.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:vo.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),vo.jsx(Us,{events:r})]}),vo.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:vo.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),vo.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:vo.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:vo.jsx(Cn,{events:r})})})]})}),e==="error"&&(K||re)&&vo.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[vo.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:vo.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),vo.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),vo.jsxs("button",{onClick:()=>{let l=t?.prompt||Ht.current;l&&u(l,st);},onMouseEnter:()=>G(true),onMouseLeave:()=>G(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:C?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[vo.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&vo.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:vo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[vo.jsx("textarea",{ref:ue,value:h,onChange:l=>{v(l.target.value),l.target.style.height="auto",l.target.style.height=Math.min(l.target.scrollHeight,160)+"px";},onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Yr()),l.key==="Escape"&&!x&&tn();},placeholder:K?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),vo.jsx("button",{onClick:Yr,disabled:!h.trim(),onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:h.trim()?1:.25,transform:A&&h.trim()?"scale(1.1)":"scale(1)",background:h.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:h.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:vo.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return x?lr:$e&&p?wo.createPortal(lr,p.document.body):vo.jsx(Bs,{children:lr})}function Hn(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 $r(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:b,recordForkActivityEvent:g}=ye(),[d,w]=vr.useState("idle"),[I,f]=vr.useState(null),[m,x]=vr.useState([]),[H,h]=vr.useState(null),v=vr.useRef(null),M=vr.useCallback(()=>{w("prompting"),x([]),h(null),f(null);},[]),N=vr.useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]);vr.useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&w(L=>L==="idle"?"prompting":L);},[i?.preview_session_id,i?.target.id,e]);let D=vr.useCallback(async(L,O,S)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),x([]),h(null),f(null);let c;if(i){let P=S?.forkId??i.fork_id??void 0,A=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...oe()},body:JSON.stringify({prompt:L,...e?{boundary_id:e}:{},...P&&!S?.forceNew?{fork_id:P}:{},...S?.forceNew?{force_new:!0}:{}})});if(!A.ok){let G=await A.json().catch(()=>({}));throw new Error(G.error||`API error: ${A.status}`)}let k=await A.json();k.container_id&&Ye(k.container_id,k.container_name),ft(k.fork_id),c=await(await fetch(`${o}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...oe()}})).json();}else if(S?.forkId){let P={prompt:L};r&&(P.userId=r),n&&(P.userHash=n);let A=await fetch(`${o}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}else {let P={userId:r,prompt:L,boundaryId:e,appId:s};O&&(P.containerId=O),n&&(P.userHash=n),S?.forceNew&&(P.force_new=!0);let A=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}f(c),b(c,{targetKind:"module",targetId:e});let F=new URLSearchParams({key:t});i?(F.set("previewSessionId",i.preview_session_id),F.set("previewForkId",c.id)):r&&F.set("userId",r),n&&F.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${c.id}/events?${F.toString()}`);v.current=$,$.onmessage=P=>{try{let A=JSON.parse(P.data);if(g(c.id,A),x(k=>[...k,A]),A.type==="complete"){let k=A.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let C={...c,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};f(C),w("complete"),$.close();});}else if(A.type==="error"){let k=A.data;h(k.error||"Unknown error"),w("error"),$.close();}}catch{}},$.onerror=()=>{let P={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(P["X-Fork-User-Id"]=r),!i&&n&&(P["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:P}).then(A=>A.json()).then(A=>{f(A),A.status==="complete"?(u(e,A.id),a().catch(()=>{}),w("complete")):A.status==="error"&&(h(A.error||"Fork generation failed"),w("error"));}).catch(()=>{h("Connection lost"),w("error");}),$.close();};}catch(c){h(c.message),w("error");}},[t,s,o,e,i,u,a,g,b,n,r]),j=vr.useCallback(async L=>{try{let O={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(O["X-Fork-User-Id"]=r),!i&&n&&(O["X-Fork-User-Hash"]=n);let S=await fetch(`${o}/api/v1/forks/${L}`,{headers:O});if(!S.ok)return;let c=await S.json(),F=c.boundaryId??e;if(b(c,{targetKind:"module",targetId:F}),c.status==="complete"){w("complete"),f(c),h(null),x([]);return}if(c.status==="error"){w("error"),f(c),h(c.error||"Fork generation failed"),x([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;w("running"),f(c),h(null),x([]);let $=new URLSearchParams({key:t});i?($.set("previewSessionId",i.preview_session_id),$.set("previewForkId",c.id)):r&&$.set("userId",r),n&&$.set("userHash",n);let P=new EventSource(`${o}/api/v1/forks/${c.id}/events?${$.toString()}`);v.current&&v.current.close(),v.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(g(c.id,k),x(C=>[...C,k]),k.type==="complete"){let C=k.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let G={...c,status:"complete",moduleUrl:C.moduleUrl,cssUrls:C.cssUrls,summary:C.summary,completedAt:new Date().toISOString()};f(G),w("complete"),P.close();});}else if(k.type==="error"){let C=k.data;h(C.error||"Unknown error"),w("error"),P.close();}}catch{}},P.onerror=()=>{P.close();};}catch{}},[t,o,e,i,u,g,a,b,n,r]),_=vr.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let L={userId:r,boundaryId:e,appId:s};n&&(L.userHash=n);let O=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return await a().catch(()=>{}),S.removed?(f(null),w("prompting")):S.fork&&(f(S.fork),w("complete")),S}catch(L){throw h(L.message),L}},[t,s,o,e,a,n,r]);return {state:d,fork:I,events:m,error:H,open:M,close:N,startFork:D,undoFork:_,adoptRunningFork:j}}var Ks=0;function Bn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:b}=$r(e),[g,d]=vr.useState(false),w=vr.useRef(null),I=vr.useRef(t),f=vr.useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),m=vr.useCallback(()=>{f(),d(true),s();},[f,s]),x=vr.useCallback(()=>{f(),d(false),i();},[f,i]),H=vr.useCallback(async h=>{f(),d(true),await b(h);},[b,f]);return vr.useEffect(()=>{let h=I.current;I.current=t,t==="complete"&&h==="running"&&g&&(f(),w.current=setTimeout(()=>{w.current=null,d(false),i();},Ks)),(t==="running"||t==="prompting")&&f();},[t,g,f,i]),vr.useEffect(()=>f,[f]),{state:t,fork:r,events:n,error:o,isOpen:g,open:m,close:x,submit:a,undo:u,adoptRunningFork:H}}function Pr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:b}=ye(),[g,d]=vr.useState("idle"),[w,I]=vr.useState(null),[f,m]=vr.useState([]),[x,H]=vr.useState(null),h=vr.useRef(null),v=vr.useCallback(()=>{d("prompting"),m([]),H(null),I(null);},[]),M=vr.useCallback(()=>{d("idle"),h.current&&(h.current.close(),h.current=null);},[]);vr.useEffect(()=>{o&&o.target.kind==="slot"&&d(_=>_==="idle"?"prompting":_);},[o?.preview_session_id,o?.target.kind]);let N=vr.useCallback(async(_,L,O,S)=>{try{d("running"),m([]),H(null),I(null);let c;if(o){let A=S?.forkId??o.fork_id??void 0,k=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...oe()},body:JSON.stringify({prompt:_,...L?{slot_id:L}:{},...A&&!S?.forceNew?{fork_id:A}:{},...S?.forceNew?{force_new:!0}:{}})});if(!k.ok){let V=await k.json().catch(()=>({}));throw new Error(V.error||`API error: ${k.status}`)}let C=await k.json();C.container_id&&Ye(C.container_id,C.container_name),ft(C.fork_id),c=await(await fetch(`${n}/api/v1/forks/${C.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...oe()}})).json();}else if(S?.forkId){let A={prompt:_};t&&(A.userId=t),r&&(A.userHash=r);let k=await fetch(`${n}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}else {let A={userId:t,prompt:_};L&&(A.slotId=L),O&&(A.containerId=O),r&&(A.userHash=r),S?.forceNew&&(A.force_new=!0);let k=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}I(c);let F=L??c.slotId;F&&u(c,{targetKind:"slot",targetId:F});let $=new URLSearchParams({key:e});o?($.set("previewSessionId",o.preview_session_id),$.set("previewForkId",c.id)):t&&$.set("userId",t),r&&$.set("userHash",r);let P=new EventSource(`${n}/api/v1/forks/${c.id}/events?${$.toString()}`);h.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(b(c.id,k),m(C=>[...C,k]),k.type==="complete"){let C=k.data,G={...c,status:"complete",bundleUrl:C.bundleUrl,summary:C.summary,completedAt:new Date().toISOString()};I(G),d("complete"),L&&C.bundleUrl&&s(L,G),P.close();}else if(k.type==="error"){let C=k.data;H(C.error||"Unknown error"),d("error"),P.close();}}catch{}},P.onerror=()=>{let A={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(A["X-Fork-User-Id"]=t),!o&&r&&(A["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:A}).then(k=>k.json()).then(k=>{I(k),k.status==="complete"?(d("complete"),L&&k.bundleUrl&&s(L,k)):k.status==="error"&&(H(k.error||"Fork generation failed"),d("error"));}).catch(()=>{H("Connection lost"),d("error");}),P.close();};}catch(c){H(c.message),d("error");}},[e,n,o,b,s,u,r,t]),D=vr.useCallback(async _=>{try{let L={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(L["X-Fork-User-Id"]=t),!o&&r&&(L["X-Fork-User-Hash"]=r);let O=await fetch(`${n}/api/v1/forks/${_}`,{headers:L});if(!O.ok)return;let S=await O.json();if(S.slotId&&u(S,{targetKind:"slot",targetId:S.slotId}),S.status==="complete"){d("complete"),I(S),H(null),m([]);return}if(S.status==="error"){d("error"),I(S),H(S.error||"Fork generation failed"),m([]);return}if(S.status!=="pending"&&S.status!=="running"&&S.status!=="building")return;d("running"),I(S),H(null),m([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",S.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let F=new EventSource(`${n}/api/v1/forks/${S.id}/events?${c.toString()}`);h.current&&h.current.close(),h.current=F;let $=S.slotId;F.onmessage=P=>{try{let A=JSON.parse(P.data);if(b(S.id,A),m(k=>[...k,A]),A.type==="complete"){let k=A.data,C={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};I(C),d("complete"),$&&k.bundleUrl&&s($,C),F.close();}else if(A.type==="error"){let k=A.data;H(k.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{F.close();};}catch{}},[e,n,o,b,s,u,r,t]),j=vr.useCallback(async _=>{try{let L={userId:t,slotId:_};r&&(L.userHash=r);let O=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return a(_),S.removed?(i(_),I(null),d("prompting")):S.fork&&(s(_,S.fork),I(S.fork)),S}catch(L){throw H(L.message),L}},[e,t,r,n,i,s]);return {state:g,fork:w,events:f,error:x,open:v,close:M,startFork:N,undoFork:j,adoptRunningFork:D}}var Vs=0;function jn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=Pr(),[b,g]=vr.useState(false),d=vr.useRef(null),w=vr.useRef(e),I=vr.useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),f=vr.useCallback(()=>{I(),g(true),o();},[I,o]),m=vr.useCallback(()=>{I(),g(false),s();},[I,s]),x=vr.useCallback(async H=>{I(),g(true),await u(H);},[u,I]);return vr.useEffect(()=>{let H=w.current;w.current=e,e==="complete"&&H==="running"&&b&&(I(),d.current=setTimeout(()=>{d.current=null,g(false),s();},Vs)),(e==="running"||e==="prompting")&&I();},[e,b,I,s]),vr.useEffect(()=>I,[I]),{state:e,fork:t,events:r,error:n,isOpen:b,open:f,close:m,submit:i,undo:a,adoptRunningFork:x}}var qs=new Set(["pending","running","building"]);function Mr(e){let t=Hn(e),r=jn(),n=Bn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:b,forkActivities:g,markForkActivitySeen:d}=ye(),w=t.type==="slot"?r:n,I=t.type==="slot"?"slot":"boundary",f=t.id,m=t.title,x=t.type==="slot"?"slot":"module",H=g.find(D=>D.targetKind===x&&D.targetId===t.id&&qs.has(D.status)),h=g.find(D=>D.targetKind===x&&D.targetId===t.id&&D.status==="complete"&&D.unread),v=vr.useCallback(()=>{d();let D=H??h;if(D){w.adoptRunningFork(D.id);return}w.open();},[w,d,H,h]),M=vr.useCallback((D,j,_,L)=>t.type==="slot"?r.submit(D,j??t.id,_,L):n.submit(D,_,L),[n,r,t]),N=vr.useCallback(D=>t.type==="slot"?r.undo(D??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:f,targetLabel:m,historyMode:I,submit:M,undo:N,buttonProps:{onClick:v,hasNotification:b.unreadCompletedCount>0,activity:b},panelProps:{state:w.state,fork:w.fork,events:w.events,error:w.error,...t.type==="slot"?{slotId:f,targetLabel:m,historyMode:I}:{targetId:f,targetLabel:m,historyMode:I},onSubmit:M,onUndo:N,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function xt(e){let{embedded:t,completeVariant:r}=e,n=Mr(e);return t?vo.jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?vo.jsx(Yt,{...n.panelProps,completeVariant:r}):vo.jsx(Ir,{...n.buttonProps})}function Xs({boundaryId:e,title:t}){return vo.jsx(xt,{boundaryId:e,title:t})}function Hr(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 Kn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Or(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function zn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Wn(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Jn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Ur(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g+=1){let{rect:d,borderRadius:w}=e[g],I=d.left-.5,f=d.top-.5,m=d.width+1,x=d.height+1,H=Math.min(w+.5,m/2,x/2),h=Jn(I,f,m,x,H),v=`__fork-glow-${g}`,M=document.createElementNS(t,"filter");M.setAttribute("id",v),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),M.appendChild(N),o.appendChild(M);let D=`__fork-mask-${g}`,j=document.createElementNS(t,"mask");j.setAttribute("id",D),j.setAttribute("maskUnits","userSpaceOnUse"),j.setAttribute("x",String(I-200)),j.setAttribute("y",String(f-200)),j.setAttribute("width",String(m+400)),j.setAttribute("height",String(x+400));let _=document.createElementNS(t,"rect");_.setAttribute("x",String(I-200)),_.setAttribute("y",String(f-200)),_.setAttribute("width",String(m+400)),_.setAttribute("height",String(x+400)),_.setAttribute("fill","white"),j.appendChild(_);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),j.appendChild(L),o.appendChild(j);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${D})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",h),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),S.appendChild(c),O.appendChild(S),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",h),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(c,F),c.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let g=0;g<s.length;g+=2){let d=s[g],w=s[g+1],I=d.__group;if(!I)continue;let f=w.getTotalLength(),m=d.getTotalLength();if(f<=0)continue;let x=f*.35;w.setAttribute("stroke-dasharray",`${x} ${f-x}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*f,opacity:.92,offset:.06},{strokeDashoffset:-2*f,opacity:.92,offset:.92},{strokeDashoffset:-2.25*f,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let H=m*.35;d.setAttribute("stroke-dasharray",`${H} ${m-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*m,offset:.06},{strokeDashoffset:-2*m,offset:.92},{strokeDashoffset:-2.25*m,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,u=()=>{if(a)return;a=true,clearTimeout(b);for(let d of i)try{d.cancel();}catch{}let g=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});g.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Vn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:u}of e){let b=document.createElementNS(t,"path");b.setAttribute("d",Jn(a.left,a.top,a.width,a.height,u)),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Gn(e,t){if(Ys(t.selector))return Xn(e,t);let n=Xn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(qn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Nr(e,g=>g===s);if(i)return i;let a=s.toLowerCase(),u=Nr(e,g=>g.toLowerCase()===a);if(u)return u;let b=Nr(e,g=>g.toLowerCase().includes(a));if(b)return b}}let o=Qs(t.selector);if(o&&o!==t.selector&&qn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function qn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Xn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Br(t.label),o=Br(t.textHint);return r.find(i=>{let a=Br(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function Ys(e){return e.trim()==="[data-fork-new]"}function Br(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Qs(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Nr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let u=a.width*a.height;u<n&&(r=s,n=u);}return r}var Dr=2147483600,Zs=1600,ei=3e4,ti=300,je=10;function ri(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let a=e.getBoundingClientRect(),u=Math.min(a.width,a.height);return Math.max(4,i/100*u)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function ni(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+je+8?a="bottom":a==="bottom"&&i-t.bottom<n+je+8?a="top":a==="left"&&t.left<r+je+8?a="right":a==="right"&&s-t.right<r+je+8&&(a="left");let u=0,b=0;return a==="top"?(u=t.top-n-je,b=t.left+t.width/2-r/2):a==="bottom"?(u=t.bottom+je,b=t.left+t.width/2-r/2):a==="left"?(u=t.top+t.height/2-n/2,b=t.left-r-je):(u=t.top+t.height/2-n/2,b=t.right+je),b=Math.max(8,Math.min(b,s-r-8)),u=Math.max(8,Math.min(u,i-n-8)),{top:u,left:b,placement:a}}function oi(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function si(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
60
60
  @keyframes __fork-highlight-pulse {
61
61
  0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
62
62
  50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import*as vr from'react';import vr__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,useMemo,startTransition,Children,useContext,isValidElement}from'react';import*as wo from'react-dom';import {createPortal}from'react-dom';import*as vo from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as So from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,BadgeCheck,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var Ge="__FORK_SHARED__";function cr(){var t,r,n,o;let e=globalThis;return e[Ge]||(e[Ge]={}),(t=e[Ge]).react||(t.react=vr),(r=e[Ge])["react-dom"]||(r["react-dom"]=wo),(n=e[Ge])["react/jsx-runtime"]||(n["react/jsx-runtime"]=vo),(o=e[Ge])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=So),e[Ge]}function ur(e){return Object.assign(cr(),e)}var Fo="__fork_preview_session__";function Bt(e){return `${Fo}${e}`}var ae={apiKey:null,session:null},dr=new Set;function Nt(){for(let e of dr)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function nn(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function xo(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Bt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:nn(r)?(window.sessionStorage.removeItem(Bt(e)),null):r}catch{return null}}function fr(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Bt(e),JSON.stringify(t)):window.sessionStorage.removeItem(Bt(e));}catch{}}function at(e){ae.apiKey!==e&&(ae.apiKey=e,ae.session=xo(e),Nt());}function Ne(){return ae.session?nn(ae.session)?(Dt(null),null):ae.session:null}function Dt(e){ae.session=e,ae.apiKey&&fr(ae.apiKey,e),Nt();}function ft(e){ae.session&&ae.session.fork_id!==e&&(ae.session={...ae.session,fork_id:e},ae.apiKey&&fr(ae.apiKey,ae.session),Nt());}function Ye(e,t){ae.session&&(ae.session.container_id===e&&ae.session.container_name===t||(ae.session={...ae.session,container_id:e,container_name:t??ae.session.container_name??"Fork",fork_id:null},ae.apiKey&&fr(ae.apiKey,ae.session),Nt()));}function pr(e){return dr.add(e),()=>{dr.delete(e);}}var on="__fork_preview";function sn(){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(on);return typeof r=="string"&&r.length>0?r:null}function mr(e){if(typeof window>"u")return false;try{let t=window.sessionStorage.getItem(`__fork_preview_session__${e}`);if(t){let r=JSON.parse(t),n=typeof r?.expires_at=="string"?Date.parse(r.expires_at):NaN;if(Number.isFinite(n)&&n>Date.now())return !0;window.sessionStorage.removeItem(`__fork_preview_session__${e}`);}}catch{}return ln()!==null}function an(){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(on);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Qe=null,gr=null,pt=null;function ln(){if(Qe)return Qe;let e=sn();return e?(Qe=e,an(),Qe):null}async function hr(e,t){at(e);let r=Ne();if(r)return Qe=null,r;let n=Qe??sn();if(Qe=null,!n)return null;an();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let s=await o.json(),i={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Dt(i),i}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function yr(e,t,r){at(e);let n=Ne();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
2
2
  `);return pt&&gr===o||(gr=o,pt=(async()=>{try{let s=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(s.status===204)return null;if(!s.ok){let u=await s.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${s.status}): ${u.error??"unknown"}`),null}let i=await s.json(),a={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Dt(a),a}catch(s){return console.warn("[fork-preview] auto admin activate threw",s),null}finally{gr=null,pt=null;}})()),pt}function Io(){return Ne()}function _o(){return null}function jt(){return useSyncExternalStore(pr,Io,_o)}function oe(){let e=Ne();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Kt(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let s=await o.json(),i={};for(let[a,u]of Object.entries(s.modules)){let b=u.moduleUrl??u.bundleUrl??null,g=u.legacyModuleUrl??u.legacyBundleUrl??null;i[a]={forkId:u.forkId,moduleUrl:b,legacyModuleUrl:g,bundleUrl:u.bundleUrl??b,legacyBundleUrl:u.legacyBundleUrl??g,cssUrls:u.cssUrls??[],integrity:u.integrity,metadata:u.metadata,highlightHint:u.highlightHint,buildId:u.buildId,updatedAt:u.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var Ro="fork:manifest:v1";function kr(e,t,r){return `${Ro}:${e}:${t}:${r}`}function Eo(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(kr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Co(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(kr(e,t,r),JSON.stringify(n));}catch{}}function $o(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(kr(e,t,r));}catch{}}function Po(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,a]of r){let u=t.slots[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,a]of o){let u=t.modules[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}return false}var gn=createContext(null),Lo=12e3,Ho=45e3,cn="fork:activity:v1",Oo=new Set(["pending","running","building"]),Uo="Setting up environment";function Ee(e){return Oo.has(e)}function Bo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function No(e,t){let r=Bo(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function un(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function zt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function gt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Ze(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function et(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var Do="fork:previewPaused:v1";function br(e,t,r,n){return `${Do}:${e}:${t}:${r}:${n}`}function jo(e){if(typeof window>"u")return false;try{return window.localStorage.getItem(e)==="1"}catch{return false}}function dn(e,t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(e,"1"):window.localStorage.removeItem(e);}catch{}}function Ko(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function zo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Ee(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function Wo(e){let t=e.filter(o=>Ee(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():Uo,detail:s?Ko(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function mt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Jo(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:mt(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(s=>mt(e,s)):[]};return r}function fn(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let a=i.bundleUrl??i.legacyBundleUrl;a&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:mt(e,a),createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function pn(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:mt(e,s),cssUrls:(o.cssUrls??[]).map(i=>mt(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function Vo(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[u]=useState(()=>(at(t),mr(t))),[b,g]=useState({}),[d,w]=useState(i?{userId:i,userHash:void 0}:null),[I,f]=useState(!!i||u),[m,x]=useState({}),[H,h]=useState(!o),[v,M]=useState(0),[N,D]=useState(null),[j,_]=useState(false),[L,O]=useState([]),[S,c]=useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),F=useRef(new Map),$=useRef(new Map),[P,A]=useState(0),k=useRef(new Set),C=useRef(new Map),G=useRef(void 0),V=useRef(new Map),q=useRef([]),te=useRef(new Set),X=useRef(false);cr(),useEffect(()=>{return hr(t,r).then(()=>{}),()=>{}},[]);let U=jt();useEffect(()=>{u||U||!o||!d?.userHash||yr(t,r,{appId:o,userId:d.userId,userHash:d.userHash});},[t,o,d?.userHash,d?.userId,r,u,U?.preview_session_id]),s&&G.current!==s&&(ur(s),G.current=s),useEffect(()=>{a&&(u||(f(false),fetch(a,{credentials:"include"}).then(p=>{if(!p.ok)throw new Error(`Auth endpoint returned ${p.status}`);return p.json()}).then(p=>{if(!p.userId||typeof p.userId!="string")throw new Error("authUrl response must include userId");w({userId:p.userId,userHash:typeof p.userHash=="string"?p.userHash:void 0});}).catch(p=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",p.message);}).finally(()=>{f(true);})));},[a,u]),useEffect(()=>{!a&&i&&(w({userId:i,userHash:void 0}),f(true));},[i,a]);let ne=d?.userId??"",_e=d?.userHash,z=U?"":ne,ee=U?void 0:_e,ve=!!o,se=useCallback(async()=>{if(!ve){D(null),_(false),x({}),h(true),M(y=>y+1);return}if(!I){h(false);return}if(!U&&!z||!o){D(null),_(false),x({}),h(true),M(y=>y+1);return}if(h(false),!U){try{let y=await Kt({baseUrl:r,apiKey:t,appId:o,userId:z,userHash:ee});y&&(D(y.containerId),_(!!y.forksPaused),g(fn(r,y,z,o)),x(pn(r,y)));}catch(y){console.error("[ForkProvider] Failed to fetch fork manifest:",y.message),D(null),_(false),g({}),x({});}finally{M(y=>y+1),h(true);}return}if(D(U.container_id??null),U.container_id){let y=br(t,o,U.operator_id,U.container_id);if(jo(y)){_(true),g({}),x({}),M(E=>E+1),h(true);return}_(false);try{let E=await Kt({baseUrl:r,apiKey:t,appId:o,userId:z,containerId:U.container_id,extraHeaders:oe()});E&&(g(fn(r,E,z,o)),x(pn(r,E)));}catch(E){console.error("[ForkProvider] Failed to fetch preview container manifest:",E.message),g({}),x({});}finally{M(E=>E+1),h(true);}return}_(false);let p=new URLSearchParams({appId:o,userId:z});ee&&p.set("userHash",ee);try{let y=await fetch(`${r}/api/v1/boundaries/manifest?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,...oe()}});if(!y.ok)throw new Error(`${y.status}`);let E=await y.json();x(Jo(r,E));}catch(y){console.error("[ForkProvider] Failed to fetch module override manifest:",y.message),x({});}finally{M(y=>y+1),h(true);}},[t,o,r,I,ve,ee,z,U?.preview_session_id,U?.fork_id,U?.container_id]);useEffect(()=>{if(!z||o&&(!U||U.container_id))return;let p=new URLSearchParams({userId:z});ee&&p.set("userHash",ee),fetch(`${r}/api/v1/forks/active?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,...oe()}}).then(y=>{if(!y.ok)throw new Error(`${y.status}`);return y.json()}).then(y=>{y&&typeof y=="object"&&g(y);}).catch(()=>{});},[t,o,z,ee,r,U?.preview_session_id,U?.fork_id]),useEffect(()=>{se();},[se]);let Me=useCallback(async p=>{if(o){if(U){if(!U.container_id)return;dn(br(t,o,U.operator_id,U.container_id),p),_(p),p?(g({}),x({}),M(y=>y+1)):await se();return}if(z){_(p),p&&(g({}),x({}),M(y=>y+1));try{let y=await fetch(`${r}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:p,userId:z,userHash:ee})});if(!y.ok)throw new Error(`${y.status}`);p||await se();}catch(y){console.error("[ForkProvider] Failed to persist fork pause state:",y?.message??y),se().catch(()=>{});}}}},[t,o,r,se,U,ee,z]),ze=useCallback((p,y)=>{g(E=>({...E,[p]:y}));},[]),nt=useCallback(p=>{g(y=>{let E={...y};return delete E[p],E});},[]),Pe=useCallback(p=>{k.current.add(p);},[]),We=useCallback(p=>k.current.has(p)?(k.current.delete(p),true):false,[]),Je=useCallback((p,y)=>{C.current.set(p,y);},[]),Ct=useCallback((p,y)=>C.current.get(p)!==y?false:(C.current.delete(p),true),[]),or=useCallback(p=>{if(!o)return;let y=JSON.stringify(p);F.current.get(p.id)===y||$.current.get(p.id)?.signature===y||($.current.set(p.id,{boundary:p,signature:y}),A(Q=>Q+1));},[o]);useEffect(()=>{if(!o||$.current.size===0)return;let p=setTimeout(()=>{let y=Array.from($.current.values());y.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:y.map(E=>E.boundary)})}).then(E=>{if(!E.ok)throw new Error(`${E.status}`)}).then(()=>{for(let E of y)$.current.get(E.boundary.id)?.signature===E.signature&&($.current.delete(E.boundary.id),F.current.set(E.boundary.id,E.signature));}).catch(E=>{console.error("[ForkProvider] Failed to register module boundaries:",E.message);});},50);return ()=>{clearTimeout(p);}},[t,o,r,P]);let $t=useCallback(p=>m[p],[m]),ge=U?`preview:${U.preview_session_id}`:z,Ve=`${t}:${o||"no-app"}:${N||"no-container"}:${ge||"anonymous"}`,sr=U?`op:${U.operator_id}`:z,Pt=`${t}:${o||"no-app"}:${sr||"anonymous"}`,Se=`${cn}:seen:${Ve}`,me=`${cn}:tracked:${Ve}`;useEffect(()=>{q.current=L;},[L]);let Te=useCallback(()=>{let p={Authorization:`Bearer ${t}`,...oe()};return o&&(p["X-Fork-App-Id"]=o),!U&&z&&(p["X-Fork-User-Id"]=z),!U&&ee&&(p["X-Fork-User-Hash"]=ee),p},[t,o,U,ee,z]);useEffect(()=>{if(typeof window>"u")return;let p=window.__FORK_RUNTIME__,y={dataFetch:async(E,Q,K="POST")=>{if(!o||!N)throw new Error("Fork data is unavailable until appId and containerId are resolved");let W=typeof E=="string"&&E.startsWith("/")?E:`/${String(E||"")}`,re=W.startsWith("/api/v1/data")?W:`/api/v1/data${W}`,ie=K.toUpperCase(),ce=new URL(`${r}${re}`),ue={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...oe()};!U&&z&&(ue["X-Fork-User-Id"]=z),!U&&ee&&(ue["X-Fork-User-Hash"]=ee);let de={method:ie,headers:ue};ie==="GET"?(ce.searchParams.set("appId",o),ce.searchParams.set("containerId",N)):de.body=JSON.stringify({appId:o,containerId:N,...Q&&typeof Q=="object"?Q:{}});let fe=await fetch(ce.toString(),de),J=await fe.json().catch(()=>({}));if(!fe.ok)throw new Error(typeof J?.error=="string"?J.error:`Fork data API ${fe.status}`);return J}};return window.__FORK_RUNTIME__=y,()=>{window.__FORK_RUNTIME__===y&&(window.__FORK_RUNTIME__=p);}},[t,o,r,N,U,ee,z]);let Fe=useCallback(async()=>{if(!N)return;let p=new URLSearchParams({container_id:N}),y=await fetch(`${r}/api/v1/forks?${p.toString()}`,{headers:Te()}).catch(()=>null);if(!y||!y.ok)return;let E=await y.json().catch(()=>({})),Q=Array.isArray(E.forks)?E.forks:[],K=Ze(Se),W=Ze(me),re=false,ie=new Map(q.current.map(ue=>[ue.id,ue])),ce=[];for(let ue of Q){let de=un(ue);Ee(de.status)&&!W.has(de.id)&&(W.add(de.id),re=true);let fe=ie.get(de.id),J=fe?Ee(fe.status):false,xe=gt(de);de.status==="complete"&&(W.has(de.id)||J)&&!K.has(xe)&&!te.current.has(xe)&&!fe?.unread&&(X.current||W.has(de.id)||J)&&(te.current.add(xe),ce.push(de));}if(O(ue=>{let de=new Map(ue.map(le=>[le.id,le])),fe=new Set,J=new Map;for(let le of Q){let Ae=un(le);fe.add(Ae.id);let we=de.get(Ae.id),Ie=we?Ee(we.status):false,ut=gt(Ae),Tt=Ae.status==="complete"&&(W.has(Ae.id)||Ie)&&!K.has(ut),Mt=zt(we,{...Ae,unread:Tt});J.set(Ae.id,Mt);}for(let le of ue)fe.has(le.id)||(Ee(le.status)||le.unread)&&J.set(le.id,le);let xe=[...J.values()].sort((le,Ae)=>Date.parse(Ae.updatedAt)-Date.parse(le.updatedAt));return q.current=xe,xe}),re&&et(me,W),ce.length>0){for(let ue of ce)ue.targetKind==="module"&&Je(ue.targetId,ue.id);se().catch(()=>{});}X.current=true;},[Se,me,r,Te,N,se,Je]),ct=useCallback((p,y)=>{let E=No(p,y);if(!E)return;let Q=p.containerId??p._containerId;if(Q&&!N&&D(Q),Ee(E.status)){let re=Ze(me);re.has(E.id)||(re.add(E.id),et(me,re)),_(false),U?.container_id&&o&&dn(br(t,o,U.operator_id,U.container_id),false);}let K=new Map(q.current.map(re=>[re.id,re]));K.set(E.id,zt(K.get(E.id),E));let W=[...K.values()].sort((re,ie)=>Date.parse(ie.updatedAt)-Date.parse(re.updatedAt));q.current=W,O(W);},[me,t,o,N,U]),ot=useCallback((p,y)=>{let E=zo(y),Q=Ze(Se),K=Ze(me),W=q.current.find(fe=>fe.id===p),re=W?Ee(W.status):false;E.status&&Ee(E.status)&&!K.has(p)&&(K.add(p),et(me,K));let ie=W?zt(W,{...W,...E}):null,ce=ie?gt(ie):null,ue=!!(ie&&ie.status==="complete"&&(K.has(p)||re)&&ce&&!Q.has(ce)&&!te.current.has(ce)&&!W?.unread),de=y.type==="complete"&&W?.targetKind==="module"?W.targetId:null;if(O(fe=>{let J=fe.find(Ie=>Ie.id===p);if(!J)return fe;let xe=zt(J,{...J,...E}),le=xe.status==="complete"&&(K.has(p)||Ee(J.status))&&!Q.has(gt(xe)),Ae={...xe,unread:le},we=fe.map(Ie=>Ie.id===p?Ae:Ie).sort((Ie,ut)=>Date.parse(ut.updatedAt)-Date.parse(Ie.updatedAt));return q.current=we,we}),ue&&ie&&ce&&te.current.add(ce),y.type==="complete"){let fe=y.data&&typeof y.data=="object"?y.data:{},J=typeof fe.boundaryId=="string"?fe.boundaryId:de;J&&Je(J,p),se().catch(()=>{});}},[Se,me,se,Je]),Le=useCallback(p=>{let y=Ze(Se),E=Ze(me),Q=false,K=false;for(let W of q.current){if(W.status!=="complete"||p&&W.id!==p)continue;let re=gt(W);y.has(re)||(y.add(re),Q=true),E.delete(W.id)&&(K=true);}O(W=>{let re=W.map(ie=>ie.status!=="complete"||p&&ie.id!==p?ie:{...ie,unread:false});return q.current=re,re}),Q&&et(Se,y),K&&et(me,E);},[Se,me]);useEffect(()=>{X.current=false,te.current.clear(),O([]);for(let p of V.current.values())p.close();V.current.clear(),N&&Fe();},[N,Fe]),useEffect(()=>{if(typeof document>"u")return;let p=()=>{let y=document.visibilityState!=="hidden";c(y),y&&N&&Fe();};return document.addEventListener("visibilitychange",p),window.addEventListener("focus",p),window.addEventListener("online",p),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("focus",p),window.removeEventListener("online",p);}},[N,Fe]),useEffect(()=>{let p=L.filter(Q=>Ee(Q.status));if(!N||p.length===0)return;let y=S?Lo:Ho,E=window.setInterval(()=>{Fe();},y);return ()=>window.clearInterval(E)},[N,S,L,Fe]),useEffect(()=>{for(let p of V.current.values())p.close();V.current.clear();},[t,r,U?.preview_session_id,ee,z]),useEffect(()=>{let p=new Set(L.filter(y=>Ee(y.status)).map(y=>y.id));for(let[y,E]of V.current.entries())p.has(y)||(E.close(),V.current.delete(y));for(let y of p){if(V.current.has(y))continue;let E=new URLSearchParams({key:t});U?(E.set("previewSessionId",U.preview_session_id),E.set("previewForkId",y)):z&&E.set("userId",z),ee&&E.set("userHash",ee);let Q=new EventSource(`${r}/api/v1/forks/${y}/events?${E.toString()}`);Q.onmessage=K=>{try{ot(y,JSON.parse(K.data));}catch{}},Q.onerror=()=>{Q.close(),V.current.delete(y);},V.current.set(y,Q);}},[t,r,L,U,ot,ee,z]),useEffect(()=>()=>{for(let p of V.current.values())p.close();V.current.clear();},[]);let ir=Wo(L),qe=useCallback(async()=>{if(!z)throw new Error("Reset requires a resolved user identity.");let p=new URLSearchParams({userId:z});ee&&p.set("userHash",ee);let y={Authorization:`Bearer ${t}`,...oe()};o&&(y["X-Fork-App-Id"]=o);let E=await fetch(`${r}/api/v1/forks/all?${p.toString()}`,{method:"DELETE",headers:y});if(!E.ok){let K=await E.json().catch(()=>({}));throw new Error(K.error||`API error: ${E.status}`)}let Q=await E.json().catch(()=>({}));g({}),x({}),h(true),M(K=>K+1),O([]),te.current.clear(),et(Se,new Set),et(me,new Set),k.current.clear(),C.current.clear();try{for(let K=sessionStorage.length-1;K>=0;K-=1){let W=sessionStorage.key(K);W&&W.startsWith("__fork_animated_")&&sessionStorage.removeItem(W);}}catch{}return Q},[Se,me,t,o,r,ee,z]);return jsx(gn.Provider,{value:{apiKey:t,userId:z,userHash:ee,baseUrl:r,appId:o,forks:b,moduleOverridesEnabled:ve,moduleManifestReady:H,moduleManifestVersion:v,currentContainerId:N,forksPaused:j,setForksPaused:Me,forkActivities:L,activitySummary:ir,previewSession:U,trackForkActivity:ct,recordForkActivityEvent:ot,markForkActivitySeen:Le,refreshForkActivities:Fe,setSlotFork:ze,clearSlotFork:nt,skipAnimationForSlot:Pe,shouldSkipAnimation:We,queueBoundaryAnimation:Je,consumeBoundaryAnimation:Ct,registerBoundary:or,getBoundaryOverride:$t,refreshModuleManifest:se,resetAllForks:qe,highlightScope:Pt},children:n})}function ye(){let e=useContext(gn);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Wt(e){return ye().forks[e]}var ht=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(s=>s());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function Sr(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 hn=new Set;function yn(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Qo(e,t){let r=[];for(let n of t)if(!e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Zo(e,t){let r=[];for(let n of e)if(!t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)&&!r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function bn(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 kn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g++){let{rect:d,borderRadius:w}=e[g],I=d.left-.5,f=d.top-.5,m=d.width+1,x=d.height+1,H=Math.min(w+.5,m/2,x/2),h=bn(I,f,m,x,H),v=`__fork-glow-${g}`,M=document.createElementNS(t,"filter");M.setAttribute("id",v),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),M.appendChild(N),o.appendChild(M);let D=`__fork-mask-${g}`,j=document.createElementNS(t,"mask");j.setAttribute("id",D),j.setAttribute("maskUnits","userSpaceOnUse"),j.setAttribute("x",String(I-200)),j.setAttribute("y",String(f-200)),j.setAttribute("width",String(m+400)),j.setAttribute("height",String(x+400));let _=document.createElementNS(t,"rect");_.setAttribute("x",String(I-200)),_.setAttribute("y",String(f-200)),_.setAttribute("width",String(m+400)),_.setAttribute("height",String(x+400)),_.setAttribute("fill","white"),j.appendChild(_);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),j.appendChild(L),o.appendChild(j);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${D})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",h),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),S.appendChild(c),O.appendChild(S),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",h),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(c,F),c.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let g=0;g<s.length;g+=2){let d=s[g],w=s[g+1],I=d.__group,f=w.getTotalLength(),m=d.getTotalLength();if(f<=0)continue;let x=f*.35;w.setAttribute("stroke-dasharray",`${x} ${f-x}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*f,opacity:.92,offset:.06},{strokeDashoffset:-2*f,opacity:.92,offset:.92},{strokeDashoffset:-2.25*f,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let H=m*.35;d.setAttribute("stroke-dasharray",`${H} ${m-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*m,offset:.06},{strokeDashoffset:-2*m,offset:.92},{strokeDashoffset:-2.25*m,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,u=()=>{if(a)return;a=true,clearTimeout(b);for(let d of i)try{d.cancel();}catch{}let g=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});g.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function es(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:u}of e){let b=a.left,g=a.top,d=a.width,w=a.height,I=Math.min(u,d/2,w/2),f=bn(b,g,d,w,I),m=document.createElementNS(t,"path");m.setAttribute("d",f),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),m.setAttribute("stroke-width","1.5"),m.setAttribute("stroke-dasharray","8 4"),m.setAttribute("stroke-linecap","round"),m.setAttribute("filter","url(#__fork-removed-shadow)"),m.setAttribute("opacity","0"),n.appendChild(m),m.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 ts(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 rs=vr__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&&ts(e.hostProps,t.hostProps)),wr=class extends vr__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 wn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){Sr(t,e);let i=Wt(e),{baseUrl:a,apiKey:u,appId:b,shouldSkipAnimation:g}=ye(),[d,w]=useState(null),I=useRef(null),f=useRef(null),m=useRef(null),x=useRef(false),H=useRef(null),h=useRef(null),v=!!(n||o),M=useRef(null);v&&!M.current&&(M.current=new ht(e));let N=useRef(o);if(N.current=o,useEffect(()=>{if(v)return ()=>{M.current?.destroy(),M.current=null;}},[v,e]),v&&M.current&&n)for(let[O,S]of Object.entries(n))M.current.set(O,S);useEffect(()=>{if(!v)return;M.current||(M.current=new ht(e));let O=M.current,S=Object.keys(N.current||{}).map(c=>O.on(c,(...F)=>N.current?.[c]?.(...F)));return ()=>S.forEach(c=>c())},[v,e]),useEffect(()=>{if(hn.has(e))return;hn.add(e);let O={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${a}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify(O)}).catch(()=>{});},[e,a,u,r,b,s]);let D=i?.id||null;useEffect(()=>{if(i?.bundleUrl,I.current,f.current,!i?.bundleUrl||!D){return}let O=`${a}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,c=sessionStorage.getItem(S),F=g(e),$=!F&&c!==D;if(F&&D&&sessionStorage.setItem(S,D),$&&f.current){let G=yn(f.current);m.current=G,x.current=true,`${e}${G.length}`;}window.__FORK_REACT__=vr__default,window.__FORK_REACT_DOM__=wo,window.__FORK_REACT_JSX__=vo;let P=Date.now(),A=`${a}${i.bundleUrl.replace("bundle.js","component.css")}?t=${P}`,k=document.createElement("link");k.rel="stylesheet",k.href=A,k.dataset.forkSlot=e,document.head.appendChild(k);let C=document.createElement("script");return C.src=O+"?t="+P,C.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(f.current&&m.current&&x.current){let V=f.current.getBoundingClientRect(),q=f.current.cloneNode(true);q.setAttribute("data-fork-clone-overlay","true"),q.style.position="fixed",q.style.top=`${V.top}px`,q.style.left=`${V.left}px`,q.style.width=`${V.width}px`,q.style.height=`${V.height}px`,q.style.flex="none",q.style.minHeight="auto",q.style.zIndex="9998",q.style.pointerEvents="none",q.style.overflow="hidden";let te=getComputedStyle(f.current).backgroundColor;q.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(q);let X=f.current.querySelectorAll("*"),U=q.querySelectorAll("*");for(let ne=0;ne<X.length;ne++)X[ne].scrollTop!==0&&(U[ne].scrollTop=X[ne].scrollTop),X[ne].scrollLeft!==0&&(U[ne].scrollLeft=X[ne].scrollLeft);H.current=q;}w(()=>G.default),I.current=D;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},C.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(C),()=>{C.remove(),k.remove(),h.current&&(clearTimeout(h.current),h.current=null),H.current&&(H.current.remove(),H.current=null);}},[D,a,e]),useEffect(()=>{if(!x.current||!d||!f.current){`${e}${x.current}`,f.current;return}let O=m.current;if(!O){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!f.current)return;let S=yn(f.current),c=Qo(O,S),F=Zo(O,S),$=H.current;if(`${e}${c.length}${F.length}`,F.length>0&&$){let P=es(F);h.current=setTimeout(()=>{h.current=null;let A=400;$.animate([{opacity:1},{opacity:0}],{duration:A,fill:"forwards"}),P.animate([{opacity:1},{opacity:0}],{duration:A,fill:"forwards"}),setTimeout(()=>{$.remove(),P.remove(),H.current=null,c.length>0&&(kn(c));},A);},3500);}else $&&($.remove(),H.current=null),c.length>0&&(kn(c));m.current=null,x.current=false,D&&(sessionStorage.setItem(`__fork_animated_${e}`,D),`${e}`);});});},[d]);let j={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:f,style:j,children:t});if(!d)return jsx("div",{ref:f,style:j,children:t});let L=t?.props??{};return jsx(wr,{slotId:e,resetKey:D,fallback:jsx("div",{ref:f,style:j,children:t}),children:jsx(rs,{component:d,containerRef:f,wrapperStyle:j,hostProps:L})})}var Sn=new Set;function ss(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 Fn(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,s]of Object.entries(n))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&Fn(n.children,t);}),t}function is({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:a="iframe",shared:u,events:b}){if(Sr(r,e),a==="direct")return jsx(wn,{slotId:e,githubRepo:s,shared:u,events:b,entityBindings:o,children:r});let g=Wt(e),{baseUrl:d,apiKey:w,appId:I,userId:f,userHash:m,currentContainerId:x,previewSession:H}=ye(),h=useRef(null),v=useRef(false),M=useRef(null),N=useRef(i);N.current=i;let D=useRef(t);D.current=t;let j=useRef(n);j.current=n,useEffect(()=>{if(typeof process<"u")return;let S=Fn(r),c=new Set(i?Object.keys(i):[]),F=[...S].filter($=>!c.has($));F.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
3
3
  `+F.map($=>` - ${$}`).join(`
4
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{Sn.has(e)||(Sn.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?ss(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,d,w,s,I,o]);let _=useCallback(S=>{let c=h.current;if(c?.contentWindow&&v.current){let F=N.current?Object.keys(N.current):[];c.contentWindow.postMessage({type:"slot:props",props:S,callbackNames:F},"*"),M.current=null;}else M.current=S;},[]),L=useCallback((S,c)=>{let F=j.current;return !F||F.length===0?false:F.some($=>{let[P,A]=$.split(" "),k=c.split("?")[0];return S.toUpperCase()===P.toUpperCase()&&k.startsWith(A)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let S=async c=>{if(c.source===h.current?.contentWindow){if(c.data?.type==="slot:ready")v.current=true,h.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:j.current||[]},"*"),j.current,M.current?_(M.current):_(D.current||{});else if(c.data?.type==="slot:event"){let F=c.data.event;F?.navigate&&(window.location.hash=F.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(F=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,F.message);});else if(c.data?.type==="slot:callback"){let{name:F,args:$}=c.data,P=N.current?.[F];P?(P(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(c.data?.type==="slot:fetch"){let{id:F,method:$,url:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;let C=$||"GET";if(!L(C,P)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${C} ${P} \u2014 not in allowedFetches`),k.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${C} ${P}`},"*");return}try{let G={method:C};A&&C!=="GET"&&(G.headers={"Content-Type":"application/json"},G.body=JSON.stringify(A));let V=await fetch(P,G),q=await V.json();`${e}${F}${V.status}`,k.postMessage({type:"slot:fetch-response",id:F,data:q,status:V.status},"*");}catch(G){console.error(`[ForkSlot:${e}] fetch #${F} failed:`,G.message),k.postMessage({type:"slot:fetch-response",id:F,error:G.message},"*");}}else if(c.data?.type==="slot:fork-data"){let{id:F,path:$,method:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;if(!x||!I){k.postMessage({type:"slot:fork-data-response",id:F,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let C=typeof $=="string"&&$.startsWith("/")?$:`/${String($||"")}`,G=C.startsWith("/api/v1/data")?C:`/api/v1/data${C}`;try{let V={Authorization:`Bearer ${w}`,"Content-Type":"application/json","X-Fork-App-Id":I,...oe()};!H&&f&&(V["X-Fork-User-Id"]=f),!H&&m&&(V["X-Fork-User-Hash"]=m);let q=typeof P=="string"?P.toUpperCase():"POST",te=new URL(`${d}${G}`),X={method:q,headers:V};q==="GET"?(te.searchParams.set("appId",I),te.searchParams.set("containerId",x)):X.body=JSON.stringify({appId:I,containerId:x,...A&&typeof A=="object"?A:{}});let U=await fetch(te.toString(),X),ne=await U.json().catch(()=>({}));if(!U.ok){let _e=typeof ne?.error=="string"?ne.error:`Fork data API ${U.status}`;k.postMessage({type:"slot:fork-data-response",id:F,error:_e,status:U.status},"*");return}k.postMessage({type:"slot:fork-data-response",id:F,data:ne,status:U.status},"*");}catch(V){k.postMessage({type:"slot:fork-data-response",id:F,error:V.message},"*");}}}};return window.addEventListener("message",S),()=>{window.removeEventListener("message",S),v.current=false;}},[g?.bundleUrl,e,_,L,x,I,w,d,H,m,f]),useEffect(()=>{g?.bundleUrl&&v.current&&_(t||{});},[t,g?.bundleUrl,_]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let O=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:h,src:O,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Vt({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var ds=5600,xr=2147483002;function fs(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ps(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Ar(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function gs(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function Ir({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=useState(false),[s,i]=useState(false),[a,u]=useState(null),[b,g]=useState(null),[d,w]=useState(null),I=useRef(0),f=n?48:40,m=fs(r),x=!!(m&&r?.state==="complete"&&r.unreadCompletedCount>0),H=x?m:b?.key??null,h=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(H&&H!==a&&(x||b)),M=h||v,N=x?r?.label:b?.label,D=v?"Built":r?.label??"Fork this app",j=v?N:r?.detail,_=Ar(r?.label??"Fork this app",r?.detail),L=Ar(D,j),O=v?Math.min(420,Math.max(326,L,b?.width??0,I.current+40)):L,S=v?46:40,c=M?[D,j].filter(Boolean).join(" "):gs(r,t)??"Fork this app",F=M?`${D}:${j??""}`:"idle",$=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!M;useEffect(()=>{if(typeof document>"u")return;let X=document.createElement("div");return X.setAttribute("data-fork-button-host","true"),X.style.position="relative",X.style.zIndex=String(xr),document.body.appendChild(X),w(X),()=>{X.remove(),w(null);}},[]),useEffect(()=>{h&&(I.current=_);},[_,h]),useEffect(()=>{!x||!m||!r?.label||g(X=>{if(X?.key===m)return X;let U=Math.min(420,Math.max(326,Ar("Built",r.label),I.current+40));return {key:m,label:r.label,width:U,startedAt:Date.now()}});},[r?.label,m,x]),useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&g(null);},[r?.state,r?.unreadCompletedCount]),useEffect(()=>{if(!H||!v||H===a)return;let X,U=b?.key===H?b.startedAt:Date.now(),ne=()=>{if(Date.now()-U>=ds&&!ps()){u(H);return}X=window.setTimeout(ne,250);};return X=window.setTimeout(ne,250),()=>{X!==void 0&&window.clearTimeout(X);}},[H,a,b?.key,b?.startedAt,v]);let P=M?{position:"fixed",bottom:24,right:24,zIndex:xr,width:`min(${O}px, calc(100vw - 32px))`,height:S,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:v?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":"center",gap:v?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:v?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:xr,width:f,height:f,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},A={minWidth:0,maxWidth:h?286:v?82:j?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},k={minWidth:0,maxWidth:v?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:v?1:0,color:"#64748b",fontSize:h?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},C={minWidth:0,flex:v?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},G={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:v?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},te=jsxs(Fragment,{children:[jsx("style",{children:`
4
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{Sn.has(e)||(Sn.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?ss(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,d,w,s,I,o]);let _=useCallback(S=>{let c=h.current;if(c?.contentWindow&&v.current){let F=N.current?Object.keys(N.current):[];c.contentWindow.postMessage({type:"slot:props",props:S,callbackNames:F},"*"),M.current=null;}else M.current=S;},[]),L=useCallback((S,c)=>{let F=j.current;return !F||F.length===0?false:F.some($=>{let[P,A]=$.split(" "),k=c.split("?")[0];return S.toUpperCase()===P.toUpperCase()&&k.startsWith(A)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let S=async c=>{if(c.source===h.current?.contentWindow){if(c.data?.type==="slot:ready")v.current=true,h.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:j.current||[]},"*"),j.current,M.current?_(M.current):_(D.current||{});else if(c.data?.type==="slot:event"){let F=c.data.event;F?.navigate&&(window.location.hash=F.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(F=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,F.message);});else if(c.data?.type==="slot:callback"){let{name:F,args:$}=c.data,P=N.current?.[F];P?(P(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(c.data?.type==="slot:fetch"){let{id:F,method:$,url:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;let C=$||"GET";if(!L(C,P)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${C} ${P} \u2014 not in allowedFetches`),k.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${C} ${P}`},"*");return}try{let G={method:C};A&&C!=="GET"&&(G.headers={"Content-Type":"application/json"},G.body=JSON.stringify(A));let V=await fetch(P,G),q=await V.json();`${e}${F}${V.status}`,k.postMessage({type:"slot:fetch-response",id:F,data:q,status:V.status},"*");}catch(G){console.error(`[ForkSlot:${e}] fetch #${F} failed:`,G.message),k.postMessage({type:"slot:fetch-response",id:F,error:G.message},"*");}}else if(c.data?.type==="slot:fork-data"){let{id:F,path:$,method:P,body:A}=c.data,k=h.current?.contentWindow;if(!k)return;if(!x||!I){k.postMessage({type:"slot:fork-data-response",id:F,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let C=typeof $=="string"&&$.startsWith("/")?$:`/${String($||"")}`,G=C.startsWith("/api/v1/data")?C:`/api/v1/data${C}`;try{let V={Authorization:`Bearer ${w}`,"Content-Type":"application/json","X-Fork-App-Id":I,...oe()};!H&&f&&(V["X-Fork-User-Id"]=f),!H&&m&&(V["X-Fork-User-Hash"]=m);let q=typeof P=="string"?P.toUpperCase():"POST",te=new URL(`${d}${G}`),X={method:q,headers:V};q==="GET"?(te.searchParams.set("appId",I),te.searchParams.set("containerId",x)):X.body=JSON.stringify({appId:I,containerId:x,...A&&typeof A=="object"?A:{}});let U=await fetch(te.toString(),X),ne=await U.json().catch(()=>({}));if(!U.ok){let _e=typeof ne?.error=="string"?ne.error:`Fork data API ${U.status}`;k.postMessage({type:"slot:fork-data-response",id:F,error:_e,status:U.status},"*");return}k.postMessage({type:"slot:fork-data-response",id:F,data:ne,status:U.status},"*");}catch(V){k.postMessage({type:"slot:fork-data-response",id:F,error:V.message},"*");}}}};return window.addEventListener("message",S),()=>{window.removeEventListener("message",S),v.current=false;}},[g?.bundleUrl,e,_,L,x,I,w,d,H,m,f]),useEffect(()=>{g?.bundleUrl&&v.current&&_(t||{});},[t,g?.bundleUrl,_]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let O=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:h,src:O,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Vt({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var ds=5600,xr=2147483002;function fs(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ps(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Ar(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function gs(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function Ir({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=useState(false),[s,i]=useState(false),[a,u]=useState(null),[b,g]=useState(null),[d,w]=useState(null),I=useRef(0),f=n?48:40,m=fs(r),x=!!(m&&r?.state==="complete"&&r.unreadCompletedCount>0),H=x?m:b?.key??null,h=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(H&&H!==a&&(x||b)),M=h||v,N=x?r?.label:b?.label,D=v?"Built":r?.label??"Fork this app",j=v?N:r?.detail,_=Ar(r?.label??"Fork this app",r?.detail),L=Ar(D,j),O=v?Math.min(420,Math.max(326,L,b?.width??0,I.current+40)):L,S=v?46:40,c=M?[D,j].filter(Boolean).join(" "):gs(r,t)??"Fork this app",F=M?`${D}:${j??""}`:"idle",$=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!M;useEffect(()=>{if(typeof document>"u")return;let X=document.createElement("div");return X.setAttribute("data-fork-button-host","true"),X.style.position="relative",X.style.zIndex=String(xr),document.body.appendChild(X),w(X),()=>{X.remove(),w(null);}},[]),useEffect(()=>{h&&(I.current=_);},[_,h]),useEffect(()=>{!x||!m||!r?.label||g(X=>{if(X?.key===m)return X;let U=Math.min(420,Math.max(326,Ar("Built",r.label),I.current+40));return {key:m,label:r.label,width:U,startedAt:Date.now()}});},[r?.label,m,x]),useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&g(null);},[r?.state,r?.unreadCompletedCount]),useEffect(()=>{if(!H||!v||H===a)return;let X,U=b?.key===H?b.startedAt:Date.now(),ne=()=>{if(Date.now()-U>=ds&&!ps()){u(H);return}X=window.setTimeout(ne,250);};return X=window.setTimeout(ne,250),()=>{X!==void 0&&window.clearTimeout(X);}},[H,a,b?.key,b?.startedAt,v]);let P=M?{position:"fixed",bottom:24,right:24,zIndex:xr,width:`min(${O}px, calc(100vw - 32px))`,height:S,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:v?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":"center",gap:v?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:v?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:xr,width:f,height:f,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},A={minWidth:0,maxWidth:h?286:v?82:j?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},k={minWidth:0,maxWidth:v?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:v?1:0,color:"#64748b",fontSize:h?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},C={minWidth:0,flex:v?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},G={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:v?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},te=jsxs(Fragment,{children:[jsx("style",{children:`
5
5
  @keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
6
6
  @keyframes __forkButtonTextSwap {
7
7
  from { opacity: 0; transform: translateY(2px); }
@@ -16,7 +16,7 @@ import*as vr from'react';import vr__default,{createContext,useSyncExternalStore,
16
16
  70% { opacity: 1; transform: scale(1.18); }
17
17
  100% { opacity: 1; transform: scale(1); }
18
18
  }
19
- `}),jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:P,title:c,"aria-label":c,children:[M&&r?jsxs(Fragment,{children:[h?jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(37, 99, 235, 0.18)",borderTopColor:"#2563eb",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):jsx("span",{"aria-hidden":true,style:G}),jsxs("span",{style:C,children:[jsx("span",{style:A,children:D}),j&&jsx("span",{style:k,children:j})]},F)]}):jsx(Vt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),$&&jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#2563eb",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return d?createPortal(te,d):te}var Ss={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Fs={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},xs={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},As={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Rr(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 Cn({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
19
+ `}),jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:P,title:c,"aria-label":c,children:[M&&r?jsxs(Fragment,{children:[h?jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(17, 24, 39, 0.18)",borderTopColor:"#111827",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):jsx("span",{"aria-hidden":true,style:G}),jsxs("span",{style:C,children:[jsx("span",{style:A,children:D}),j&&jsx("span",{style:k,children:j})]},F)]}):jsx(Vt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),$&&jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#111827",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return d?createPortal(te,d):te}var Ss={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Fs={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},xs={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},As={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Rr(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 Cn({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
20
20
  @keyframes __fork-spin {
21
21
  from { transform: rotate(0deg); }
22
22
  to { transform: rotate(360deg); }
@@ -56,7 +56,7 @@ import*as vr from'react';import vr__default,{createContext,useSyncExternalStore,
56
56
  scrollbar-width: thin;
57
57
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
58
58
  }
59
- `}),jsxs("div",{className:"__fork-panel",style:yo,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!_e&&confirm("Kill all forks in this container?")){z(true);try{let R=await fe();`${R?.deleted??0}`,Q([]),W(null),ie(!1),v("");}catch(R){console.error("[Fork] Reset failed:",R);}finally{z(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(Vt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:mo}):ee.length===0&&!Ie?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ie?jsxs("div",{ref:Ut,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{We(l=>!l);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(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:Je||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:rn}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Pe&&jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[ee.map(l=>{let R=l.id===se,B=or===l.id,he=ge===l.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>$t(l.id),onMouseLeave:()=>$t(null),onClick:()=>{l.id!==se&&ho(l.id);},disabled:!!ge,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:B?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",fontWeight:R?600:400,opacity:ge&&!he?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:R&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:he?"Switching...":l.name})]},l.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Se?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:ct,type:"text",value:Te,placeholder:"Container name",disabled:ge==="__new__",onChange:l=>Fe(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),Zr(Te)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),me(false),Fe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:l=>{l.currentTarget.style.borderColor="#1c4587",l.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{Zr(Te);},disabled:!Te.trim()||ge==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Te.trim()||ge==="__new__"?"#e5e7eb":"#1c4587",color:!Te.trim()||ge==="__new__"?"#9ca3af":"#ffffff",cursor:!Te.trim()||ge==="__new__"?"default":"pointer",flexShrink:0},children:ge==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pt(true),onMouseLeave:()=>Pt(false),onClick:()=>{ge||(Le(null),Fe(""),me(true));},disabled:!!ge,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:sr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",opacity:ge&&ge!=="__new__"?.55:1},children:"+ New container"}),ot&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:ot})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rn}),e==="running"&&jsx("span",{title:Xe?`Estimated ~${Xe} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Xe?"#1c4587":"#9ca3af",backgroundColor:Xe?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Xe?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Xe?`~${Xe}m`:"~ m"})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[ut&&jsx("button",{type:"button",role:"switch","aria-checked":!le,"aria-label":le?"Turn Fork back on":"Turn Fork off",title:le?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ae(!le);},onMouseEnter:()=>Mt(true),onMouseLeave:()=>Mt(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:le?Tt?"#9ca3af":"#d1d5db":Tt?"#27599c":"#1c4587",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:le?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!x&&jsxs(Fragment,{children:[qr&&jsx("button",{onClick:$e?po:fo,onMouseEnter:()=>P(true),onMouseLeave:()=>P(false),title:$e?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:$?"#4b5563":"#9ca3af",backgroundColor:$?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:$e?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:tn,onMouseEnter:()=>F(true),onMouseLeave:()=>F(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]})]}),jsxs("div",{ref:de,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(K||re)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{W(null),ie(false),ce.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let R=(K?E.find(B=>B.id===K)?.targetId:null)??st;return R?jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${R}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:R})]}):null})()]}),!K&&!re&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),E.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),E.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:E.map(l=>{let R=l.summary||"Untitled fork";return jsxs("button",{onClick:()=>{ie(false),W(l.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:B=>B.currentTarget.style.background="#fafafa",onMouseLeave:B=>B.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:R}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Hs(l.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},l.id)})})]}),K&&dt.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:dt.map((l,R)=>jsx("div",{style:{marginBottom:R<dt.length-1?10:0},children:l.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:l.text})]}):H==="item"&&R===dt.length-1?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:jsx(BadgeCheck,{style:{width:16,height:16}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),b&&e!=="running"&&jsx("button",{onClick:B=>{B.stopPropagation(),en();},disabled:te,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:te?"default":"pointer",opacity:te?.4:1,height:28,flexShrink:0},children:"Undo"})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:l.text}),b&&R===dt.length-1&&e!=="running"&&jsxs("button",{onClick:B=>{B.stopPropagation(),en();},onMouseEnter:()=>ne(R),onMouseLeave:()=>ne(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:U===R?"rgba(0,0,0,0.06)":"transparent",color:U===R?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),U===R&&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"})]})]})]})},R))}),e==="running"&&(K||re)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>q(!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(Us,{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(Cn,{events:r})})})]})}),e==="error"&&(K||re)&&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 l=t?.prompt||Ht.current;l&&u(l,st);},onMouseEnter:()=>G(true),onMouseLeave:()=>G(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:C?"#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:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:ue,value:h,onChange:l=>{v(l.target.value),l.target.style.height="auto",l.target.style.height=Math.min(l.target.scrollHeight,160)+"px";},onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Yr()),l.key==="Escape"&&!x&&tn();},placeholder:K?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:Yr,disabled:!h.trim(),onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:h.trim()?1:.25,transform:A&&h.trim()?"scale(1.1)":"scale(1)",background:h.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:h.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return x?lr:$e&&p?createPortal(lr,p.document.body):jsx(Bs,{children:lr})}function Hn(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 $r(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:b,recordForkActivityEvent:g}=ye(),[d,w]=useState("idle"),[I,f]=useState(null),[m,x]=useState([]),[H,h]=useState(null),v=useRef(null),M=useCallback(()=>{w("prompting"),x([]),h(null),f(null);},[]),N=useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]);useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&w(L=>L==="idle"?"prompting":L);},[i?.preview_session_id,i?.target.id,e]);let D=useCallback(async(L,O,S)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),x([]),h(null),f(null);let c;if(i){let P=S?.forkId??i.fork_id??void 0,A=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...oe()},body:JSON.stringify({prompt:L,...e?{boundary_id:e}:{},...P&&!S?.forceNew?{fork_id:P}:{},...S?.forceNew?{force_new:!0}:{}})});if(!A.ok){let G=await A.json().catch(()=>({}));throw new Error(G.error||`API error: ${A.status}`)}let k=await A.json();k.container_id&&Ye(k.container_id,k.container_name),ft(k.fork_id),c=await(await fetch(`${o}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...oe()}})).json();}else if(S?.forkId){let P={prompt:L};r&&(P.userId=r),n&&(P.userHash=n);let A=await fetch(`${o}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}else {let P={userId:r,prompt:L,boundaryId:e,appId:s};O&&(P.containerId=O),n&&(P.userHash=n),S?.forceNew&&(P.force_new=!0);let A=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}f(c),b(c,{targetKind:"module",targetId:e});let F=new URLSearchParams({key:t});i?(F.set("previewSessionId",i.preview_session_id),F.set("previewForkId",c.id)):r&&F.set("userId",r),n&&F.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${c.id}/events?${F.toString()}`);v.current=$,$.onmessage=P=>{try{let A=JSON.parse(P.data);if(g(c.id,A),x(k=>[...k,A]),A.type==="complete"){let k=A.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let C={...c,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};f(C),w("complete"),$.close();});}else if(A.type==="error"){let k=A.data;h(k.error||"Unknown error"),w("error"),$.close();}}catch{}},$.onerror=()=>{let P={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(P["X-Fork-User-Id"]=r),!i&&n&&(P["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:P}).then(A=>A.json()).then(A=>{f(A),A.status==="complete"?(u(e,A.id),a().catch(()=>{}),w("complete")):A.status==="error"&&(h(A.error||"Fork generation failed"),w("error"));}).catch(()=>{h("Connection lost"),w("error");}),$.close();};}catch(c){h(c.message),w("error");}},[t,s,o,e,i,u,a,g,b,n,r]),j=useCallback(async L=>{try{let O={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(O["X-Fork-User-Id"]=r),!i&&n&&(O["X-Fork-User-Hash"]=n);let S=await fetch(`${o}/api/v1/forks/${L}`,{headers:O});if(!S.ok)return;let c=await S.json(),F=c.boundaryId??e;if(b(c,{targetKind:"module",targetId:F}),c.status==="complete"){w("complete"),f(c),h(null),x([]);return}if(c.status==="error"){w("error"),f(c),h(c.error||"Fork generation failed"),x([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;w("running"),f(c),h(null),x([]);let $=new URLSearchParams({key:t});i?($.set("previewSessionId",i.preview_session_id),$.set("previewForkId",c.id)):r&&$.set("userId",r),n&&$.set("userHash",n);let P=new EventSource(`${o}/api/v1/forks/${c.id}/events?${$.toString()}`);v.current&&v.current.close(),v.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(g(c.id,k),x(C=>[...C,k]),k.type==="complete"){let C=k.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let G={...c,status:"complete",moduleUrl:C.moduleUrl,cssUrls:C.cssUrls,summary:C.summary,completedAt:new Date().toISOString()};f(G),w("complete"),P.close();});}else if(k.type==="error"){let C=k.data;h(C.error||"Unknown error"),w("error"),P.close();}}catch{}},P.onerror=()=>{P.close();};}catch{}},[t,o,e,i,u,g,a,b,n,r]),_=useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let L={userId:r,boundaryId:e,appId:s};n&&(L.userHash=n);let O=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return await a().catch(()=>{}),S.removed?(f(null),w("prompting")):S.fork&&(f(S.fork),w("complete")),S}catch(L){throw h(L.message),L}},[t,s,o,e,a,n,r]);return {state:d,fork:I,events:m,error:H,open:M,close:N,startFork:D,undoFork:_,adoptRunningFork:j}}var Ks=0;function Bn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:b}=$r(e),[g,d]=useState(false),w=useRef(null),I=useRef(t),f=useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),m=useCallback(()=>{f(),d(true),s();},[f,s]),x=useCallback(()=>{f(),d(false),i();},[f,i]),H=useCallback(async h=>{f(),d(true),await b(h);},[b,f]);return useEffect(()=>{let h=I.current;I.current=t,t==="complete"&&h==="running"&&g&&(f(),w.current=setTimeout(()=>{w.current=null,d(false),i();},Ks)),(t==="running"||t==="prompting")&&f();},[t,g,f,i]),useEffect(()=>f,[f]),{state:t,fork:r,events:n,error:o,isOpen:g,open:m,close:x,submit:a,undo:u,adoptRunningFork:H}}function Pr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:b}=ye(),[g,d]=useState("idle"),[w,I]=useState(null),[f,m]=useState([]),[x,H]=useState(null),h=useRef(null),v=useCallback(()=>{d("prompting"),m([]),H(null),I(null);},[]),M=useCallback(()=>{d("idle"),h.current&&(h.current.close(),h.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&d(_=>_==="idle"?"prompting":_);},[o?.preview_session_id,o?.target.kind]);let N=useCallback(async(_,L,O,S)=>{try{d("running"),m([]),H(null),I(null);let c;if(o){let A=S?.forkId??o.fork_id??void 0,k=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...oe()},body:JSON.stringify({prompt:_,...L?{slot_id:L}:{},...A&&!S?.forceNew?{fork_id:A}:{},...S?.forceNew?{force_new:!0}:{}})});if(!k.ok){let V=await k.json().catch(()=>({}));throw new Error(V.error||`API error: ${k.status}`)}let C=await k.json();C.container_id&&Ye(C.container_id,C.container_name),ft(C.fork_id),c=await(await fetch(`${n}/api/v1/forks/${C.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...oe()}})).json();}else if(S?.forkId){let A={prompt:_};t&&(A.userId=t),r&&(A.userHash=r);let k=await fetch(`${n}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}else {let A={userId:t,prompt:_};L&&(A.slotId=L),O&&(A.containerId=O),r&&(A.userHash=r),S?.forceNew&&(A.force_new=!0);let k=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}I(c);let F=L??c.slotId;F&&u(c,{targetKind:"slot",targetId:F});let $=new URLSearchParams({key:e});o?($.set("previewSessionId",o.preview_session_id),$.set("previewForkId",c.id)):t&&$.set("userId",t),r&&$.set("userHash",r);let P=new EventSource(`${n}/api/v1/forks/${c.id}/events?${$.toString()}`);h.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(b(c.id,k),m(C=>[...C,k]),k.type==="complete"){let C=k.data,G={...c,status:"complete",bundleUrl:C.bundleUrl,summary:C.summary,completedAt:new Date().toISOString()};I(G),d("complete"),L&&C.bundleUrl&&s(L,G),P.close();}else if(k.type==="error"){let C=k.data;H(C.error||"Unknown error"),d("error"),P.close();}}catch{}},P.onerror=()=>{let A={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(A["X-Fork-User-Id"]=t),!o&&r&&(A["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:A}).then(k=>k.json()).then(k=>{I(k),k.status==="complete"?(d("complete"),L&&k.bundleUrl&&s(L,k)):k.status==="error"&&(H(k.error||"Fork generation failed"),d("error"));}).catch(()=>{H("Connection lost"),d("error");}),P.close();};}catch(c){H(c.message),d("error");}},[e,n,o,b,s,u,r,t]),D=useCallback(async _=>{try{let L={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(L["X-Fork-User-Id"]=t),!o&&r&&(L["X-Fork-User-Hash"]=r);let O=await fetch(`${n}/api/v1/forks/${_}`,{headers:L});if(!O.ok)return;let S=await O.json();if(S.slotId&&u(S,{targetKind:"slot",targetId:S.slotId}),S.status==="complete"){d("complete"),I(S),H(null),m([]);return}if(S.status==="error"){d("error"),I(S),H(S.error||"Fork generation failed"),m([]);return}if(S.status!=="pending"&&S.status!=="running"&&S.status!=="building")return;d("running"),I(S),H(null),m([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",S.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let F=new EventSource(`${n}/api/v1/forks/${S.id}/events?${c.toString()}`);h.current&&h.current.close(),h.current=F;let $=S.slotId;F.onmessage=P=>{try{let A=JSON.parse(P.data);if(b(S.id,A),m(k=>[...k,A]),A.type==="complete"){let k=A.data,C={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};I(C),d("complete"),$&&k.bundleUrl&&s($,C),F.close();}else if(A.type==="error"){let k=A.data;H(k.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{F.close();};}catch{}},[e,n,o,b,s,u,r,t]),j=useCallback(async _=>{try{let L={userId:t,slotId:_};r&&(L.userHash=r);let O=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return a(_),S.removed?(i(_),I(null),d("prompting")):S.fork&&(s(_,S.fork),I(S.fork)),S}catch(L){throw H(L.message),L}},[e,t,r,n,i,s]);return {state:g,fork:w,events:f,error:x,open:v,close:M,startFork:N,undoFork:j,adoptRunningFork:D}}var Vs=0;function jn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=Pr(),[b,g]=useState(false),d=useRef(null),w=useRef(e),I=useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),f=useCallback(()=>{I(),g(true),o();},[I,o]),m=useCallback(()=>{I(),g(false),s();},[I,s]),x=useCallback(async H=>{I(),g(true),await u(H);},[u,I]);return useEffect(()=>{let H=w.current;w.current=e,e==="complete"&&H==="running"&&b&&(I(),d.current=setTimeout(()=>{d.current=null,g(false),s();},Vs)),(e==="running"||e==="prompting")&&I();},[e,b,I,s]),useEffect(()=>I,[I]),{state:e,fork:t,events:r,error:n,isOpen:b,open:f,close:m,submit:i,undo:a,adoptRunningFork:x}}var qs=new Set(["pending","running","building"]);function Mr(e){let t=Hn(e),r=jn(),n=Bn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:b,forkActivities:g,markForkActivitySeen:d}=ye(),w=t.type==="slot"?r:n,I=t.type==="slot"?"slot":"boundary",f=t.id,m=t.title,x=t.type==="slot"?"slot":"module",H=g.find(D=>D.targetKind===x&&D.targetId===t.id&&qs.has(D.status)),h=g.find(D=>D.targetKind===x&&D.targetId===t.id&&D.status==="complete"&&D.unread),v=useCallback(()=>{d();let D=H??h;if(D){w.adoptRunningFork(D.id);return}w.open();},[w,d,H,h]),M=useCallback((D,j,_,L)=>t.type==="slot"?r.submit(D,j??t.id,_,L):n.submit(D,_,L),[n,r,t]),N=useCallback(D=>t.type==="slot"?r.undo(D??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:f,targetLabel:m,historyMode:I,submit:M,undo:N,buttonProps:{onClick:v,hasNotification:b.unreadCompletedCount>0,activity:b},panelProps:{state:w.state,fork:w.fork,events:w.events,error:w.error,...t.type==="slot"?{slotId:f,targetLabel:m,historyMode:I}:{targetId:f,targetLabel:m,historyMode:I},onSubmit:M,onUndo:N,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function xt(e){let{embedded:t,completeVariant:r}=e,n=Mr(e);return t?jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?jsx(Yt,{...n.panelProps,completeVariant:r}):jsx(Ir,{...n.buttonProps})}function Xs({boundaryId:e,title:t}){return jsx(xt,{boundaryId:e,title:t})}function Hr(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 Kn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Or(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function zn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Wn(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Jn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Ur(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g+=1){let{rect:d,borderRadius:w}=e[g],I=d.left-.5,f=d.top-.5,m=d.width+1,x=d.height+1,H=Math.min(w+.5,m/2,x/2),h=Jn(I,f,m,x,H),v=`__fork-glow-${g}`,M=document.createElementNS(t,"filter");M.setAttribute("id",v),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),M.appendChild(N),o.appendChild(M);let D=`__fork-mask-${g}`,j=document.createElementNS(t,"mask");j.setAttribute("id",D),j.setAttribute("maskUnits","userSpaceOnUse"),j.setAttribute("x",String(I-200)),j.setAttribute("y",String(f-200)),j.setAttribute("width",String(m+400)),j.setAttribute("height",String(x+400));let _=document.createElementNS(t,"rect");_.setAttribute("x",String(I-200)),_.setAttribute("y",String(f-200)),_.setAttribute("width",String(m+400)),_.setAttribute("height",String(x+400)),_.setAttribute("fill","white"),j.appendChild(_);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),j.appendChild(L),o.appendChild(j);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${D})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",h),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),S.appendChild(c),O.appendChild(S),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",h),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(c,F),c.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let g=0;g<s.length;g+=2){let d=s[g],w=s[g+1],I=d.__group;if(!I)continue;let f=w.getTotalLength(),m=d.getTotalLength();if(f<=0)continue;let x=f*.35;w.setAttribute("stroke-dasharray",`${x} ${f-x}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*f,opacity:.92,offset:.06},{strokeDashoffset:-2*f,opacity:.92,offset:.92},{strokeDashoffset:-2.25*f,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let H=m*.35;d.setAttribute("stroke-dasharray",`${H} ${m-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*m,offset:.06},{strokeDashoffset:-2*m,offset:.92},{strokeDashoffset:-2.25*m,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,u=()=>{if(a)return;a=true,clearTimeout(b);for(let d of i)try{d.cancel();}catch{}let g=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});g.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Vn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:u}of e){let b=document.createElementNS(t,"path");b.setAttribute("d",Jn(a.left,a.top,a.width,a.height,u)),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Gn(e,t){if(Ys(t.selector))return Xn(e,t);let n=Xn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(qn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Nr(e,g=>g===s);if(i)return i;let a=s.toLowerCase(),u=Nr(e,g=>g.toLowerCase()===a);if(u)return u;let b=Nr(e,g=>g.toLowerCase().includes(a));if(b)return b}}let o=Qs(t.selector);if(o&&o!==t.selector&&qn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function qn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Xn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Br(t.label),o=Br(t.textHint);return r.find(i=>{let a=Br(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function Ys(e){return e.trim()==="[data-fork-new]"}function Br(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Qs(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Nr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let u=a.width*a.height;u<n&&(r=s,n=u);}return r}var Dr=2147483600,Zs=1600,ei=3e4,ti=300,je=10;function ri(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let a=e.getBoundingClientRect(),u=Math.min(a.width,a.height);return Math.max(4,i/100*u)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function ni(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+je+8?a="bottom":a==="bottom"&&i-t.bottom<n+je+8?a="top":a==="left"&&t.left<r+je+8?a="right":a==="right"&&s-t.right<r+je+8&&(a="left");let u=0,b=0;return a==="top"?(u=t.top-n-je,b=t.left+t.width/2-r/2):a==="bottom"?(u=t.bottom+je,b=t.left+t.width/2-r/2):a==="left"?(u=t.top+t.height/2-n/2,b=t.left-r-je):(u=t.top+t.height/2-n/2,b=t.right+je),b=Math.max(8,Math.min(b,s-r-8)),u=Math.max(8,Math.min(u,i-n-8)),{top:u,left:b,placement:a}}function oi(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function si(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
59
+ `}),jsxs("div",{className:"__fork-panel",style:yo,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!_e&&confirm("Kill all forks in this container?")){z(true);try{let R=await fe();`${R?.deleted??0}`,Q([]),W(null),ie(!1),v("");}catch(R){console.error("[Fork] Reset failed:",R);}finally{z(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(Vt,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:mo}):ee.length===0&&!Ie?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ie?jsxs("div",{ref:Ut,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{We(l=>!l);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(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:Je||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:rn}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Pe&&jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[ee.map(l=>{let R=l.id===se,B=or===l.id,he=ge===l.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>$t(l.id),onMouseLeave:()=>$t(null),onClick:()=>{l.id!==se&&ho(l.id);},disabled:!!ge,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:B?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",fontWeight:R?600:400,opacity:ge&&!he?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:R&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:he?"Switching...":l.name})]},l.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Se?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:ct,type:"text",value:Te,placeholder:"Container name",disabled:ge==="__new__",onChange:l=>Fe(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),Zr(Te)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),me(false),Fe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:l=>{l.currentTarget.style.borderColor="#111827",l.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{Zr(Te);},disabled:!Te.trim()||ge==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Te.trim()||ge==="__new__"?"#e5e7eb":"#111827",color:!Te.trim()||ge==="__new__"?"#9ca3af":"#ffffff",cursor:!Te.trim()||ge==="__new__"?"default":"pointer",flexShrink:0},children:ge==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pt(true),onMouseLeave:()=>Pt(false),onClick:()=>{ge||(Le(null),Fe(""),me(true));},disabled:!!ge,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:sr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",opacity:ge&&ge!=="__new__"?.55:1},children:"+ New container"}),ot&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:ot})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rn}),e==="running"&&jsx("span",{title:Xe?`Estimated ~${Xe} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Xe?"#111827":"#9ca3af",backgroundColor:Xe?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Xe?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Xe?`~${Xe}m`:"~ m"})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[ut&&jsx("button",{type:"button",role:"switch","aria-checked":!le,"aria-label":le?"Turn Fork back on":"Turn Fork off",title:le?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ae(!le);},onMouseEnter:()=>Mt(true),onMouseLeave:()=>Mt(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:le?Tt?"#9ca3af":"#d1d5db":Tt?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:le?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!x&&jsxs(Fragment,{children:[qr&&jsx("button",{onClick:$e?po:fo,onMouseEnter:()=>P(true),onMouseLeave:()=>P(false),title:$e?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:$?"#4b5563":"#9ca3af",backgroundColor:$?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:$e?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:tn,onMouseEnter:()=>F(true),onMouseLeave:()=>F(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]})]}),jsxs("div",{ref:de,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(K||re)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{W(null),ie(false),ce.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let R=(K?E.find(B=>B.id===K)?.targetId:null)??st;return R?jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${R}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:R})]}):null})()]}),!K&&!re&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),E.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),E.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:E.map(l=>{let R=l.summary||"Untitled fork";return jsxs("button",{onClick:()=>{ie(false),W(l.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:B=>B.currentTarget.style.background="#fafafa",onMouseLeave:B=>B.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:R}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Hs(l.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#111827"},children:"running"})]}):null]})]},l.id)})})]}),K&&dt.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:dt.map((l,R)=>jsx("div",{style:{marginBottom:R<dt.length-1?10:0},children:l.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:l.text})]}):H==="item"&&R===dt.length-1?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:jsx(BadgeCheck,{style:{width:16,height:16}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),b&&e!=="running"&&jsx("button",{onClick:B=>{B.stopPropagation(),en();},disabled:te,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:te?"default":"pointer",opacity:te?.4:1,height:28,flexShrink:0},children:"Undo"})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:l.text}),b&&R===dt.length-1&&e!=="running"&&jsxs("button",{onClick:B=>{B.stopPropagation(),en();},onMouseEnter:()=>ne(R),onMouseLeave:()=>ne(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:U===R?"rgba(0,0,0,0.06)":"transparent",color:U===R?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),U===R&&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"})]})]})]})},R))}),e==="running"&&(K||re)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>q(!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(Us,{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(Cn,{events:r})})})]})}),e==="error"&&(K||re)&&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 l=t?.prompt||Ht.current;l&&u(l,st);},onMouseEnter:()=>G(true),onMouseLeave:()=>G(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:C?"#e5e7eb":"#f3f4f6",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:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:ue,value:h,onChange:l=>{v(l.target.value),l.target.style.height="auto",l.target.style.height=Math.min(l.target.scrollHeight,160)+"px";},onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Yr()),l.key==="Escape"&&!x&&tn();},placeholder:K?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:Yr,disabled:!h.trim(),onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:h.trim()?1:.25,transform:A&&h.trim()?"scale(1.1)":"scale(1)",background:h.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:h.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return x?lr:$e&&p?createPortal(lr,p.document.body):jsx(Bs,{children:lr})}function Hn(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 $r(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:b,recordForkActivityEvent:g}=ye(),[d,w]=useState("idle"),[I,f]=useState(null),[m,x]=useState([]),[H,h]=useState(null),v=useRef(null),M=useCallback(()=>{w("prompting"),x([]),h(null),f(null);},[]),N=useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]);useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&w(L=>L==="idle"?"prompting":L);},[i?.preview_session_id,i?.target.id,e]);let D=useCallback(async(L,O,S)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),x([]),h(null),f(null);let c;if(i){let P=S?.forkId??i.fork_id??void 0,A=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...oe()},body:JSON.stringify({prompt:L,...e?{boundary_id:e}:{},...P&&!S?.forceNew?{fork_id:P}:{},...S?.forceNew?{force_new:!0}:{}})});if(!A.ok){let G=await A.json().catch(()=>({}));throw new Error(G.error||`API error: ${A.status}`)}let k=await A.json();k.container_id&&Ye(k.container_id,k.container_name),ft(k.fork_id),c=await(await fetch(`${o}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...oe()}})).json();}else if(S?.forkId){let P={prompt:L};r&&(P.userId=r),n&&(P.userHash=n);let A=await fetch(`${o}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}else {let P={userId:r,prompt:L,boundaryId:e,appId:s};O&&(P.containerId=O),n&&(P.userHash=n),S?.forceNew&&(P.force_new=!0);let A=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(P)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}f(c),b(c,{targetKind:"module",targetId:e});let F=new URLSearchParams({key:t});i?(F.set("previewSessionId",i.preview_session_id),F.set("previewForkId",c.id)):r&&F.set("userId",r),n&&F.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${c.id}/events?${F.toString()}`);v.current=$,$.onmessage=P=>{try{let A=JSON.parse(P.data);if(g(c.id,A),x(k=>[...k,A]),A.type==="complete"){let k=A.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let C={...c,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};f(C),w("complete"),$.close();});}else if(A.type==="error"){let k=A.data;h(k.error||"Unknown error"),w("error"),$.close();}}catch{}},$.onerror=()=>{let P={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(P["X-Fork-User-Id"]=r),!i&&n&&(P["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:P}).then(A=>A.json()).then(A=>{f(A),A.status==="complete"?(u(e,A.id),a().catch(()=>{}),w("complete")):A.status==="error"&&(h(A.error||"Fork generation failed"),w("error"));}).catch(()=>{h("Connection lost"),w("error");}),$.close();};}catch(c){h(c.message),w("error");}},[t,s,o,e,i,u,a,g,b,n,r]),j=useCallback(async L=>{try{let O={Authorization:`Bearer ${t}`,...oe()};!i&&r&&(O["X-Fork-User-Id"]=r),!i&&n&&(O["X-Fork-User-Hash"]=n);let S=await fetch(`${o}/api/v1/forks/${L}`,{headers:O});if(!S.ok)return;let c=await S.json(),F=c.boundaryId??e;if(b(c,{targetKind:"module",targetId:F}),c.status==="complete"){w("complete"),f(c),h(null),x([]);return}if(c.status==="error"){w("error"),f(c),h(c.error||"Fork generation failed"),x([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;w("running"),f(c),h(null),x([]);let $=new URLSearchParams({key:t});i?($.set("previewSessionId",i.preview_session_id),$.set("previewForkId",c.id)):r&&$.set("userId",r),n&&$.set("userHash",n);let P=new EventSource(`${o}/api/v1/forks/${c.id}/events?${$.toString()}`);v.current&&v.current.close(),v.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(g(c.id,k),x(C=>[...C,k]),k.type==="complete"){let C=k.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let G={...c,status:"complete",moduleUrl:C.moduleUrl,cssUrls:C.cssUrls,summary:C.summary,completedAt:new Date().toISOString()};f(G),w("complete"),P.close();});}else if(k.type==="error"){let C=k.data;h(C.error||"Unknown error"),w("error"),P.close();}}catch{}},P.onerror=()=>{P.close();};}catch{}},[t,o,e,i,u,g,a,b,n,r]),_=useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let L={userId:r,boundaryId:e,appId:s};n&&(L.userHash=n);let O=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return await a().catch(()=>{}),S.removed?(f(null),w("prompting")):S.fork&&(f(S.fork),w("complete")),S}catch(L){throw h(L.message),L}},[t,s,o,e,a,n,r]);return {state:d,fork:I,events:m,error:H,open:M,close:N,startFork:D,undoFork:_,adoptRunningFork:j}}var Ks=0;function Bn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:b}=$r(e),[g,d]=useState(false),w=useRef(null),I=useRef(t),f=useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),m=useCallback(()=>{f(),d(true),s();},[f,s]),x=useCallback(()=>{f(),d(false),i();},[f,i]),H=useCallback(async h=>{f(),d(true),await b(h);},[b,f]);return useEffect(()=>{let h=I.current;I.current=t,t==="complete"&&h==="running"&&g&&(f(),w.current=setTimeout(()=>{w.current=null,d(false),i();},Ks)),(t==="running"||t==="prompting")&&f();},[t,g,f,i]),useEffect(()=>f,[f]),{state:t,fork:r,events:n,error:o,isOpen:g,open:m,close:x,submit:a,undo:u,adoptRunningFork:H}}function Pr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:b}=ye(),[g,d]=useState("idle"),[w,I]=useState(null),[f,m]=useState([]),[x,H]=useState(null),h=useRef(null),v=useCallback(()=>{d("prompting"),m([]),H(null),I(null);},[]),M=useCallback(()=>{d("idle"),h.current&&(h.current.close(),h.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&d(_=>_==="idle"?"prompting":_);},[o?.preview_session_id,o?.target.kind]);let N=useCallback(async(_,L,O,S)=>{try{d("running"),m([]),H(null),I(null);let c;if(o){let A=S?.forkId??o.fork_id??void 0,k=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...oe()},body:JSON.stringify({prompt:_,...L?{slot_id:L}:{},...A&&!S?.forceNew?{fork_id:A}:{},...S?.forceNew?{force_new:!0}:{}})});if(!k.ok){let V=await k.json().catch(()=>({}));throw new Error(V.error||`API error: ${k.status}`)}let C=await k.json();C.container_id&&Ye(C.container_id,C.container_name),ft(C.fork_id),c=await(await fetch(`${n}/api/v1/forks/${C.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...oe()}})).json();}else if(S?.forkId){let A={prompt:_};t&&(A.userId=t),r&&(A.userHash=r);let k=await fetch(`${n}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}else {let A={userId:t,prompt:_};L&&(A.slotId=L),O&&(A.containerId=O),r&&(A.userHash=r),S?.forceNew&&(A.force_new=!0);let k=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!k.ok){let C=await k.json().catch(()=>({}));throw new Error(C.error||`API error: ${k.status}`)}c=await k.json();}I(c);let F=L??c.slotId;F&&u(c,{targetKind:"slot",targetId:F});let $=new URLSearchParams({key:e});o?($.set("previewSessionId",o.preview_session_id),$.set("previewForkId",c.id)):t&&$.set("userId",t),r&&$.set("userHash",r);let P=new EventSource(`${n}/api/v1/forks/${c.id}/events?${$.toString()}`);h.current=P,P.onmessage=A=>{try{let k=JSON.parse(A.data);if(b(c.id,k),m(C=>[...C,k]),k.type==="complete"){let C=k.data,G={...c,status:"complete",bundleUrl:C.bundleUrl,summary:C.summary,completedAt:new Date().toISOString()};I(G),d("complete"),L&&C.bundleUrl&&s(L,G),P.close();}else if(k.type==="error"){let C=k.data;H(C.error||"Unknown error"),d("error"),P.close();}}catch{}},P.onerror=()=>{let A={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(A["X-Fork-User-Id"]=t),!o&&r&&(A["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:A}).then(k=>k.json()).then(k=>{I(k),k.status==="complete"?(d("complete"),L&&k.bundleUrl&&s(L,k)):k.status==="error"&&(H(k.error||"Fork generation failed"),d("error"));}).catch(()=>{H("Connection lost"),d("error");}),P.close();};}catch(c){H(c.message),d("error");}},[e,n,o,b,s,u,r,t]),D=useCallback(async _=>{try{let L={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(L["X-Fork-User-Id"]=t),!o&&r&&(L["X-Fork-User-Hash"]=r);let O=await fetch(`${n}/api/v1/forks/${_}`,{headers:L});if(!O.ok)return;let S=await O.json();if(S.slotId&&u(S,{targetKind:"slot",targetId:S.slotId}),S.status==="complete"){d("complete"),I(S),H(null),m([]);return}if(S.status==="error"){d("error"),I(S),H(S.error||"Fork generation failed"),m([]);return}if(S.status!=="pending"&&S.status!=="running"&&S.status!=="building")return;d("running"),I(S),H(null),m([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",S.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let F=new EventSource(`${n}/api/v1/forks/${S.id}/events?${c.toString()}`);h.current&&h.current.close(),h.current=F;let $=S.slotId;F.onmessage=P=>{try{let A=JSON.parse(P.data);if(b(S.id,A),m(k=>[...k,A]),A.type==="complete"){let k=A.data,C={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};I(C),d("complete"),$&&k.bundleUrl&&s($,C),F.close();}else if(A.type==="error"){let k=A.data;H(k.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{F.close();};}catch{}},[e,n,o,b,s,u,r,t]),j=useCallback(async _=>{try{let L={userId:t,slotId:_};r&&(L.userHash=r);let O=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(L)});if(!O.ok){let c=await O.json().catch(()=>({}));throw new Error(c.error||`API error: ${O.status}`)}let S=await O.json();return a(_),S.removed?(i(_),I(null),d("prompting")):S.fork&&(s(_,S.fork),I(S.fork)),S}catch(L){throw H(L.message),L}},[e,t,r,n,i,s]);return {state:g,fork:w,events:f,error:x,open:v,close:M,startFork:N,undoFork:j,adoptRunningFork:D}}var Vs=0;function jn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=Pr(),[b,g]=useState(false),d=useRef(null),w=useRef(e),I=useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),f=useCallback(()=>{I(),g(true),o();},[I,o]),m=useCallback(()=>{I(),g(false),s();},[I,s]),x=useCallback(async H=>{I(),g(true),await u(H);},[u,I]);return useEffect(()=>{let H=w.current;w.current=e,e==="complete"&&H==="running"&&b&&(I(),d.current=setTimeout(()=>{d.current=null,g(false),s();},Vs)),(e==="running"||e==="prompting")&&I();},[e,b,I,s]),useEffect(()=>I,[I]),{state:e,fork:t,events:r,error:n,isOpen:b,open:f,close:m,submit:i,undo:a,adoptRunningFork:x}}var qs=new Set(["pending","running","building"]);function Mr(e){let t=Hn(e),r=jn(),n=Bn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:b,forkActivities:g,markForkActivitySeen:d}=ye(),w=t.type==="slot"?r:n,I=t.type==="slot"?"slot":"boundary",f=t.id,m=t.title,x=t.type==="slot"?"slot":"module",H=g.find(D=>D.targetKind===x&&D.targetId===t.id&&qs.has(D.status)),h=g.find(D=>D.targetKind===x&&D.targetId===t.id&&D.status==="complete"&&D.unread),v=useCallback(()=>{d();let D=H??h;if(D){w.adoptRunningFork(D.id);return}w.open();},[w,d,H,h]),M=useCallback((D,j,_,L)=>t.type==="slot"?r.submit(D,j??t.id,_,L):n.submit(D,_,L),[n,r,t]),N=useCallback(D=>t.type==="slot"?r.undo(D??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:f,targetLabel:m,historyMode:I,submit:M,undo:N,buttonProps:{onClick:v,hasNotification:b.unreadCompletedCount>0,activity:b},panelProps:{state:w.state,fork:w.fork,events:w.events,error:w.error,...t.type==="slot"?{slotId:f,targetLabel:m,historyMode:I}:{targetId:f,targetLabel:m,historyMode:I},onSubmit:M,onUndo:N,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function xt(e){let{embedded:t,completeVariant:r}=e,n=Mr(e);return t?jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?jsx(Yt,{...n.panelProps,completeVariant:r}):jsx(Ir,{...n.buttonProps})}function Xs({boundaryId:e,title:t}){return jsx(xt,{boundaryId:e,title:t})}function Hr(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 Kn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Or(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function zn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Wn(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Jn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Ur(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g+=1){let{rect:d,borderRadius:w}=e[g],I=d.left-.5,f=d.top-.5,m=d.width+1,x=d.height+1,H=Math.min(w+.5,m/2,x/2),h=Jn(I,f,m,x,H),v=`__fork-glow-${g}`,M=document.createElementNS(t,"filter");M.setAttribute("id",v),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),M.appendChild(N),o.appendChild(M);let D=`__fork-mask-${g}`,j=document.createElementNS(t,"mask");j.setAttribute("id",D),j.setAttribute("maskUnits","userSpaceOnUse"),j.setAttribute("x",String(I-200)),j.setAttribute("y",String(f-200)),j.setAttribute("width",String(m+400)),j.setAttribute("height",String(x+400));let _=document.createElementNS(t,"rect");_.setAttribute("x",String(I-200)),_.setAttribute("y",String(f-200)),_.setAttribute("width",String(m+400)),_.setAttribute("height",String(x+400)),_.setAttribute("fill","white"),j.appendChild(_);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),j.appendChild(L),o.appendChild(j);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${D})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",h),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),S.appendChild(c),O.appendChild(S),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",h),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(c,F),c.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let g=0;g<s.length;g+=2){let d=s[g],w=s[g+1],I=d.__group;if(!I)continue;let f=w.getTotalLength(),m=d.getTotalLength();if(f<=0)continue;let x=f*.35;w.setAttribute("stroke-dasharray",`${x} ${f-x}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*f,opacity:.92,offset:.06},{strokeDashoffset:-2*f,opacity:.92,offset:.92},{strokeDashoffset:-2.25*f,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let H=m*.35;d.setAttribute("stroke-dasharray",`${H} ${m-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*m,offset:.06},{strokeDashoffset:-2*m,offset:.92},{strokeDashoffset:-2.25*m,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,u=()=>{if(a)return;a=true,clearTimeout(b);for(let d of i)try{d.cancel();}catch{}let g=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});g.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Vn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:u}of e){let b=document.createElementNS(t,"path");b.setAttribute("d",Jn(a.left,a.top,a.width,a.height,u)),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Gn(e,t){if(Ys(t.selector))return Xn(e,t);let n=Xn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(qn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Nr(e,g=>g===s);if(i)return i;let a=s.toLowerCase(),u=Nr(e,g=>g.toLowerCase()===a);if(u)return u;let b=Nr(e,g=>g.toLowerCase().includes(a));if(b)return b}}let o=Qs(t.selector);if(o&&o!==t.selector&&qn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function qn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Xn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Br(t.label),o=Br(t.textHint);return r.find(i=>{let a=Br(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function Ys(e){return e.trim()==="[data-fork-new]"}function Br(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Qs(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Nr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let u=a.width*a.height;u<n&&(r=s,n=u);}return r}var Dr=2147483600,Zs=1600,ei=3e4,ti=300,je=10;function ri(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let a=e.getBoundingClientRect(),u=Math.min(a.width,a.height);return Math.max(4,i/100*u)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function ni(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+je+8?a="bottom":a==="bottom"&&i-t.bottom<n+je+8?a="top":a==="left"&&t.left<r+je+8?a="right":a==="right"&&s-t.right<r+je+8&&(a="left");let u=0,b=0;return a==="top"?(u=t.top-n-je,b=t.left+t.width/2-r/2):a==="bottom"?(u=t.bottom+je,b=t.left+t.width/2-r/2):a==="left"?(u=t.top+t.height/2-n/2,b=t.left-r-je):(u=t.top+t.height/2-n/2,b=t.right+je),b=Math.max(8,Math.min(b,s-r-8)),u=Math.max(8,Math.min(u,i-n-8)),{top:u,left:b,placement:a}}function oi(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Dr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function si(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
60
60
  @keyframes __fork-highlight-pulse {
61
61
  0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
62
62
  50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fork-api/chat-sdk",
3
- "version": "0.1.172",
3
+ "version": "0.1.173",
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",