@fork-api/chat-sdk 0.1.168 → 0.1.171
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 +8 -8
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +8 -8
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
`);return ft&&cr===o||(cr=o,ft=(async()=>{try{let s=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(s.status===204)return null;if(!s.ok){let 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 Ut(a),a}catch(s){return console.warn("[fork-preview] auto admin activate threw",s),null}finally{cr=null,ft=null;}})()),ft}function bo(){return De()}function wo(){return null}function Nt(){return mr.useSyncExternalStore(lr,bo,wo)}function te(){let e=De();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Bt(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let s=await o.json(),i={};for(let[a,u]of Object.entries(s.modules)){let k=u.moduleUrl??u.bundleUrl??null,g=u.legacyModuleUrl??u.legacyBundleUrl??null;i[a]={forkId:u.forkId,moduleUrl:k,legacyModuleUrl:g,bundleUrl:u.bundleUrl??k,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,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var vo="fork:manifest:v1";function pr(e,t,r){return `${vo}:${e}:${t}:${r}`}function So(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(pr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Fo(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(pr(e,t,r),JSON.stringify(n));}catch{}}function xo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(pr(e,t,r));}catch{}}function Ao(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,a]of r){let u=t.slots[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,a]of o){let u=t.modules[i];if(!u||u.forkId!==a.forkId||u.buildId!==a.buildId)return true}return false}var sn=mr.createContext(null),Ro=12e3,Eo=45e3,tn="fork:activity:v1",Co=new Set(["pending","running","building"]),$o="Setting up environment";function Ae(e){return Co.has(e)}function Po(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function To(e,t){let r=Po(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 rn(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function Dt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function pt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Qe(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Ze(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function Mo(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function Lo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Ae(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function Ho(e){let t=e.filter(o=>Ae(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():$o,detail:s?Mo(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 gt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Oo(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:gt(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(s=>gt(e,s)):[]};return r}function nn(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:gt(e,a),createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function on(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:gt(e,s),cssUrls:(o.cssUrls??[]).map(i=>gt(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function Uo(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]=mr.useState(()=>(st(t),ur(t))),[k,g]=mr.useState({}),[d,w]=mr.useState(i?{userId:i,userHash:void 0}:null),[A,f]=mr.useState(!!i||u),[p,I]=mr.useState({}),[M,h]=mr.useState(!o),[v,T]=mr.useState(0),[N,D]=mr.useState(null),[O,E]=mr.useState([]),[L,B]=mr.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),S=mr.useRef(new Map),c=mr.useRef(new Map),[F,P]=mr.useState(0),C=mr.useRef(new Set),x=mr.useRef(new Map),y=mr.useRef(void 0),_=mr.useRef(new Map),z=mr.useRef([]),V=mr.useRef(new Set),Q=mr.useRef(false);or(),mr.useEffect(()=>{return dr(t,r).then(()=>{}),()=>{}},[]);let j=Nt();mr.useEffect(()=>{u||j||!o||!d?.userHash||fr(t,r,{appId:o,userId:d.userId,userHash:d.userHash});},[t,o,d?.userHash,d?.userId,r,u,j?.preview_session_id]),s&&y.current!==s&&(sr(s),y.current=s),mr.useEffect(()=>{a&&(u||(f(false),fetch(a,{credentials:"include"}).then(b=>{if(!b.ok)throw new Error(`Auth endpoint returned ${b.status}`);return b.json()}).then(b=>{if(!b.userId||typeof b.userId!="string")throw new Error("authUrl response must include userId");w({userId:b.userId,userHash:typeof b.userHash=="string"?b.userHash:void 0});}).catch(b=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",b.message);}).finally(()=>{f(true);})));},[a,u]),mr.useEffect(()=>{!a&&i&&(w({userId:i,userHash:void 0}),f(true));},[i,a]);let q=d?.userId??"",de=d?.userHash,K=j?"":q,G=j?void 0:de,we=!!o,ve=mr.useCallback(async()=>{if(!we){D(null),I({}),h(true),T(m=>m+1);return}if(!A){h(false);return}if(!j&&!K||!o){D(null),I({}),h(true),T(m=>m+1);return}if(h(false),!j){try{let m=await Bt({baseUrl:r,apiKey:t,appId:o,userId:K,userHash:G});m&&(D(m.containerId),g(nn(r,m,K,o)),I(on(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch fork manifest:",m.message),D(null),g({}),I({});}finally{T(m=>m+1),h(true);}return}if(D(j.container_id??null),j.container_id){try{let m=await Bt({baseUrl:r,apiKey:t,appId:o,userId:K,containerId:j.container_id,extraHeaders:te()});m&&(g(nn(r,m,K,o)),I(on(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch preview container manifest:",m.message),g({}),I({});}finally{T(m=>m+1),h(true);}return}let b=new URLSearchParams({appId:o,userId:K});G&&b.set("userHash",G);try{let m=await fetch(`${r}/api/v1/boundaries/manifest?${b.toString()}`,{headers:{Authorization:`Bearer ${t}`,...te()}});if(!m.ok)throw new Error(`${m.status}`);let H=await m.json();I(Oo(r,H));}catch(m){console.error("[ForkProvider] Failed to fetch module override manifest:",m.message),I({});}finally{T(m=>m+1),h(true);}},[t,o,r,A,we,G,K,j?.preview_session_id,j?.fork_id,j?.container_id]);mr.useEffect(()=>{if(!K||o&&(!j||j.container_id))return;let b=new URLSearchParams({userId:K});G&&b.set("userHash",G),fetch(`${r}/api/v1/forks/active?${b.toString()}`,{headers:{Authorization:`Bearer ${t}`,...te()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{m&&typeof m=="object"&&g(m);}).catch(()=>{});},[t,o,K,G,r,j?.preview_session_id,j?.fork_id]),mr.useEffect(()=>{ve();},[ve]);let _e=mr.useCallback((b,m)=>{g(H=>({...H,[b]:m}));},[]),ye=mr.useCallback(b=>{g(m=>{let H={...m};return delete H[b],H});},[]),Me=mr.useCallback(b=>{C.current.add(b);},[]),We=mr.useCallback(b=>C.current.has(b)?(C.current.delete(b),true):false,[]),Ce=mr.useCallback((b,m)=>{x.current.set(b,m);},[]),$e=mr.useCallback((b,m)=>x.current.get(b)!==m?false:(x.current.delete(b),true),[]),Je=mr.useCallback(b=>{if(!o)return;let m=JSON.stringify(b);S.current.get(b.id)===m||c.current.get(b.id)?.signature===m||(c.current.set(b.id,{boundary:b,signature:m}),P(X=>X+1));},[o]);mr.useEffect(()=>{if(!o||c.current.size===0)return;let b=setTimeout(()=>{let m=Array.from(c.current.values());m.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:m.map(H=>H.boundary)})}).then(H=>{if(!H.ok)throw new Error(`${H.status}`)}).then(()=>{for(let H of m)c.current.get(H.boundary.id)?.signature===H.signature&&(c.current.delete(H.boundary.id),S.current.set(H.boundary.id,H.signature));}).catch(H=>{console.error("[ForkProvider] Failed to register module boundaries:",H.message);});},50);return ()=>{clearTimeout(b);}},[t,o,r,F]);let tr=mr.useCallback(b=>p[b],[p]),at=j?`preview:${j.preview_session_id}`:K,Et=`${t}:${o||"no-app"}:${N||"no-container"}:${at||"anonymous"}`,Ct=`${t}:${o||"no-app"}:${at||"anonymous"}`,re=`${tn}:seen:${Et}`,ge=`${tn}:tracked:${Et}`;mr.useEffect(()=>{z.current=O;},[O]);let $t=mr.useCallback(()=>{let b={Authorization:`Bearer ${t}`,...te()};return o&&(b["X-Fork-App-Id"]=o),!j&&K&&(b["X-Fork-User-Id"]=K),!j&&G&&(b["X-Fork-User-Hash"]=G),b},[t,o,j,G,K]);mr.useEffect(()=>{if(typeof window>"u")return;let b=window.__FORK_RUNTIME__,m={dataFetch:async(H,X,J="POST")=>{if(!o||!N)throw new Error("Fork data is unavailable until appId and containerId are resolved");let W=typeof H=="string"&&H.startsWith("/")?H:`/${String(H||"")}`,ne=W.startsWith("/api/v1/data")?W:`/api/v1/data${W}`,ue=J.toUpperCase(),Z=new URL(`${r}${ne}`),le={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...te()};!j&&K&&(le["X-Fork-User-Id"]=K),!j&&G&&(le["X-Fork-User-Hash"]=G);let ce={method:ue,headers:le};ue==="GET"?(Z.searchParams.set("appId",o),Z.searchParams.set("containerId",N)):ce.body=JSON.stringify({appId:o,containerId:N,...X&&typeof X=="object"?X:{}});let oe=await fetch(Z.toString(),ce),se=await oe.json().catch(()=>({}));if(!oe.ok)throw new Error(typeof se?.error=="string"?se.error:`Fork data API ${oe.status}`);return se}};return window.__FORK_RUNTIME__=m,()=>{window.__FORK_RUNTIME__===m&&(window.__FORK_RUNTIME__=b);}},[t,o,r,N,j,G,K]);let Pe=mr.useCallback(async()=>{if(!N)return;let b=new URLSearchParams({container_id:N}),m=await fetch(`${r}/api/v1/forks?${b.toString()}`,{headers:$t()}).catch(()=>null);if(!m||!m.ok)return;let H=await m.json().catch(()=>({})),X=Array.isArray(H.forks)?H.forks:[],J=Qe(re),W=Qe(ge),ne=false,ue=new Map(z.current.map(le=>[le.id,le])),Z=[];for(let le of X){let ce=rn(le);Ae(ce.status)&&!W.has(ce.id)&&(W.add(ce.id),ne=true);let oe=ue.get(ce.id),se=oe?Ae(oe.status):false,Se=pt(ce);ce.status==="complete"&&(W.has(ce.id)||se)&&!J.has(Se)&&!V.current.has(Se)&&!oe?.unread&&(Q.current||W.has(ce.id)||se)&&(V.current.add(Se),Z.push(ce));}if(E(le=>{let ce=new Map(le.map(fe=>[fe.id,fe])),oe=new Set,se=new Map;for(let fe of X){let Fe=rn(fe);oe.add(Fe.id);let ie=ce.get(Fe.id),Te=ie?Ae(ie.status):false,Re=pt(Fe),rt=Fe.status==="complete"&&(W.has(Fe.id)||Te)&&!J.has(Re),xe=Dt(ie,{...Fe,unread:rt});se.set(Fe.id,xe);}for(let fe of le)oe.has(fe.id)||(Ae(fe.status)||fe.unread)&&se.set(fe.id,fe);let Se=[...se.values()].sort((fe,Fe)=>Date.parse(Fe.updatedAt)-Date.parse(fe.updatedAt));return z.current=Se,Se}),ne&&Ze(ge,W),Z.length>0){for(let le of Z)le.targetKind==="module"&&Ce(le.targetId,le.id);ve().catch(()=>{});}Q.current=true;},[re,ge,r,$t,N,ve,Ce]),lt=mr.useCallback((b,m)=>{let H=To(b,m);if(!H)return;let X=b.containerId??b._containerId;if(X&&!N&&D(X),Ae(H.status)){let ne=Qe(ge);ne.has(H.id)||(ne.add(H.id),Ze(ge,ne));}let J=new Map(z.current.map(ne=>[ne.id,ne]));J.set(H.id,Dt(J.get(H.id),H));let W=[...J.values()].sort((ne,ue)=>Date.parse(ue.updatedAt)-Date.parse(ne.updatedAt));z.current=W,E(W);},[ge,N]),Be=mr.useCallback((b,m)=>{let H=Lo(m),X=Qe(re),J=Qe(ge),W=z.current.find(oe=>oe.id===b),ne=W?Ae(W.status):false;H.status&&Ae(H.status)&&!J.has(b)&&(J.add(b),Ze(ge,J));let ue=W?Dt(W,{...W,...H}):null,Z=ue?pt(ue):null,le=!!(ue&&ue.status==="complete"&&(J.has(b)||ne)&&Z&&!X.has(Z)&&!V.current.has(Z)&&!W?.unread),ce=m.type==="complete"&&W?.targetKind==="module"?W.targetId:null;if(E(oe=>{let se=oe.find(Te=>Te.id===b);if(!se)return oe;let Se=Dt(se,{...se,...H}),fe=Se.status==="complete"&&(J.has(b)||Ae(se.status))&&!X.has(pt(Se)),Fe={...Se,unread:fe},ie=oe.map(Te=>Te.id===b?Fe:Te).sort((Te,Re)=>Date.parse(Re.updatedAt)-Date.parse(Te.updatedAt));return z.current=ie,ie}),le&&ue&&Z&&V.current.add(Z),m.type==="complete"){let oe=m.data&&typeof m.data=="object"?m.data:{},se=typeof oe.boundaryId=="string"?oe.boundaryId:ce;se&&Ce(se,b),ve().catch(()=>{});}},[re,ge,ve,Ce]),Le=mr.useCallback(b=>{let m=Qe(re),H=Qe(ge),X=false,J=false;for(let W of z.current){if(W.status!=="complete"||b&&W.id!==b)continue;let ne=pt(W);m.has(ne)||(m.add(ne),X=true),H.delete(W.id)&&(J=true);}E(W=>{let ne=W.map(ue=>ue.status!=="complete"||b&&ue.id!==b?ue:{...ue,unread:false});return z.current=ne,ne}),X&&Ze(re,m),J&&Ze(ge,H);},[re,ge]);mr.useEffect(()=>{Q.current=false,V.current.clear(),E([]);for(let b of _.current.values())b.close();_.current.clear(),N&&Pe();},[N,Pe]),mr.useEffect(()=>{if(typeof document>"u")return;let b=()=>{let m=document.visibilityState!=="hidden";B(m),m&&N&&Pe();};return document.addEventListener("visibilitychange",b),window.addEventListener("focus",b),window.addEventListener("online",b),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("focus",b),window.removeEventListener("online",b);}},[N,Pe]),mr.useEffect(()=>{let b=O.filter(X=>Ae(X.status));if(!N||b.length===0)return;let m=L?Ro:Eo,H=window.setInterval(()=>{Pe();},m);return ()=>window.clearInterval(H)},[N,L,O,Pe]),mr.useEffect(()=>{for(let b of _.current.values())b.close();_.current.clear();},[t,r,j?.preview_session_id,G,K]),mr.useEffect(()=>{let b=new Set(O.filter(m=>Ae(m.status)).map(m=>m.id));for(let[m,H]of _.current.entries())b.has(m)||(H.close(),_.current.delete(m));for(let m of b){if(_.current.has(m))continue;let H=new URLSearchParams({key:t});j?(H.set("previewSessionId",j.preview_session_id),H.set("previewForkId",m)):K&&H.set("userId",K),G&&H.set("userHash",G);let X=new EventSource(`${r}/api/v1/forks/${m}/events?${H.toString()}`);X.onmessage=J=>{try{Be(m,JSON.parse(J.data));}catch{}},X.onerror=()=>{X.close(),_.current.delete(m);},_.current.set(m,X);}},[t,r,O,j,Be,G,K]),mr.useEffect(()=>()=>{for(let b of _.current.values())b.close();_.current.clear();},[]);let Ve=Ho(O),ct=mr.useCallback(async()=>{if(!K)throw new Error("Reset requires a resolved user identity.");let b=new URLSearchParams({userId:K});G&&b.set("userHash",G);let m={Authorization:`Bearer ${t}`,...te()};o&&(m["X-Fork-App-Id"]=o);let H=await fetch(`${r}/api/v1/forks/all?${b.toString()}`,{method:"DELETE",headers:m});if(!H.ok){let J=await H.json().catch(()=>({}));throw new Error(J.error||`API error: ${H.status}`)}let X=await H.json().catch(()=>({}));g({}),I({}),h(true),T(J=>J+1),E([]),V.current.clear(),Ze(re,new Set),Ze(ge,new Set),C.current.clear(),x.current.clear();try{for(let J=sessionStorage.length-1;J>=0;J-=1){let W=sessionStorage.key(J);W&&W.startsWith("__fork_animated_")&&sessionStorage.removeItem(W);}}catch{}return X},[re,ge,t,o,r,G,K]);return go.jsx(sn.Provider,{value:{apiKey:t,userId:K,userHash:G,baseUrl:r,appId:o,forks:k,moduleOverridesEnabled:we,moduleManifestReady:M,moduleManifestVersion:v,currentContainerId:N,forkActivities:O,activitySummary:Ve,previewSession:j,trackForkActivity:lt,recordForkActivityEvent:Be,markForkActivitySeen:Le,refreshForkActivities:Pe,setSlotFork:_e,clearSlotFork:ye,skipAnimationForSlot:Me,shouldSkipAnimation:We,queueBoundaryAnimation:Ce,consumeBoundaryAnimation:$e,registerBoundary:Je,getBoundaryOverride:tr,refreshModuleManifest:ve,resetAllForks:ct,highlightScope:Ct},children:n})}function he(){let e=mr.useContext(sn);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function jt(e){return he().forks[e]}var mt=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 hr(e,t){let r;try{r=mr.Children.only(e);}catch{let o=mr.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 ln=new Set;function cn(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Ko(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 dn(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 un(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],A=d.left-.5,f=d.top-.5,p=d.width+1,I=d.height+1,M=Math.min(w+.5,p/2,I/2),h=dn(A,f,p,I,M),v=`__fork-glow-${g}`,T=document.createElementNS(t,"filter");T.setAttribute("id",v),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),T.appendChild(N),o.appendChild(T);let D=`__fork-mask-${g}`,O=document.createElementNS(t,"mask");O.setAttribute("id",D),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(A-200)),O.setAttribute("y",String(f-200)),O.setAttribute("width",String(p+400)),O.setAttribute("height",String(I+400));let E=document.createElementNS(t,"rect");E.setAttribute("x",String(A-200)),E.setAttribute("y",String(f-200)),E.setAttribute("width",String(p+400)),E.setAttribute("height",String(I+400)),E.setAttribute("fill","white"),O.appendChild(E);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),O.appendChild(L),o.appendChild(O);let B=document.createElementNS(t,"g");B.setAttribute("mask",`url(#${D})`),B.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),B.appendChild(S),n.appendChild(B);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=B;}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],A=d.__group,f=w.getTotalLength(),p=d.getTotalLength();if(f<=0)continue;let I=f*.35;w.setAttribute("stroke-dasharray",`${I} ${f-I}`),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 M=p*.35;d.setAttribute("stroke-dasharray",`${M} ${p-M}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*p,offset:.06},{strokeDashoffset:-2*p,offset:.92},{strokeDashoffset:-2.25*p,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(A.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(k);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);},k=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Wo(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 k=a.left,g=a.top,d=a.width,w=a.height,A=Math.min(u,d/2,w/2),f=dn(k,g,d,w,A),p=document.createElementNS(t,"path");p.setAttribute("d",f),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),p.setAttribute("stroke-width","1.5"),p.setAttribute("stroke-dasharray","8 4"),p.setAttribute("stroke-linecap","round"),p.setAttribute("filter","url(#__fork-removed-shadow)"),p.setAttribute("opacity","0"),n.appendChild(p),p.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Jo(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 Vo=mr__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return go.jsx("div",{ref:r,style:n,children:go.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Jo(e.hostProps,t.hostProps)),gr=class extends mr__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 fn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){hr(t,e);let i=jt(e),{baseUrl:a,apiKey:u,appId:k,shouldSkipAnimation:g}=he(),[d,w]=mr.useState(null),A=mr.useRef(null),f=mr.useRef(null),p=mr.useRef(null),I=mr.useRef(false),M=mr.useRef(null),h=mr.useRef(null),v=!!(n||o),T=mr.useRef(null);v&&!T.current&&(T.current=new mt(e));let N=mr.useRef(o);if(N.current=o,mr.useEffect(()=>{if(v)return ()=>{T.current?.destroy(),T.current=null;}},[v,e]),v&&T.current&&n)for(let[B,S]of Object.entries(n))T.current.set(B,S);mr.useEffect(()=>{if(!v)return;T.current||(T.current=new mt(e));let B=T.current,S=Object.keys(N.current||{}).map(c=>B.on(c,(...F)=>N.current?.[c]?.(...F)));return ()=>S.forEach(c=>c())},[v,e]),mr.useEffect(()=>{if(ln.has(e))return;ln.add(e);let B={id:e,appId:k,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(B)}).catch(()=>{});},[e,a,u,r,k,s]);let D=i?.id||null;mr.useEffect(()=>{if(i?.bundleUrl,A.current,f.current,!i?.bundleUrl||!D){return}let B=`${a}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,c=sessionStorage.getItem(S),F=g(e),P=!F&&c!==D;if(F&&D&&sessionStorage.setItem(S,D),P&&f.current){let z=cn(f.current);p.current=z,I.current=true,`${e}${z.length}`;}window.__FORK_REACT__=mr__namespace.default,window.__FORK_REACT_DOM__=po__namespace,window.__FORK_REACT_JSX__=go__namespace;let C=Date.now(),x=`${a}${i.bundleUrl.replace("bundle.js","component.css")}?t=${C}`,y=document.createElement("link");y.rel="stylesheet",y.href=x,y.dataset.forkSlot=e,document.head.appendChild(y);let _=document.createElement("script");return _.src=B+"?t="+C,_.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(f.current&&p.current&&I.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 j=getComputedStyle(f.current).backgroundColor;Q.style.backgroundColor=j&&j!=="rgba(0, 0, 0, 0)"&&j!=="transparent"?j:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(Q);let q=f.current.querySelectorAll("*"),de=Q.querySelectorAll("*");for(let K=0;K<q.length;K++)q[K].scrollTop!==0&&(de[K].scrollTop=q[K].scrollTop),q[K].scrollLeft!==0&&(de[K].scrollLeft=q[K].scrollLeft);M.current=Q;}w(()=>z.default),A.current=D;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},_.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(_),()=>{_.remove(),y.remove(),h.current&&(clearTimeout(h.current),h.current=null),M.current&&(M.current.remove(),M.current=null);}},[D,a,e]),mr.useEffect(()=>{if(!I.current||!d||!f.current){`${e}${I.current}`,f.current;return}let B=p.current;if(!B){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!f.current)return;let S=cn(f.current),c=Ko(B,S),F=zo(B,S),P=M.current;if(`${e}${c.length}${F.length}`,F.length>0&&P){let C=Wo(F);h.current=setTimeout(()=>{h.current=null;let x=400;P.animate([{opacity:1},{opacity:0}],{duration:x,fill:"forwards"}),C.animate([{opacity:1},{opacity:0}],{duration:x,fill:"forwards"}),setTimeout(()=>{P.remove(),C.remove(),M.current=null,c.length>0&&(un(c));},x);},3500);}else P&&(P.remove(),M.current=null),c.length>0&&(un(c));p.current=null,I.current=false,D&&(sessionStorage.setItem(`__fork_animated_${e}`,D),`${e}`);});});},[d]);let O={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return go.jsx("div",{ref:f,style:O,children:t});if(!d)return go.jsx("div",{ref:f,style:O,children:t});let L=t?.props??{};return go.jsx(gr,{slotId:e,resetKey:D,fallback:go.jsx("div",{ref:f,style:O,children:t}),children:go.jsx(Vo,{component:d,containerRef:f,wrapperStyle:O,hostProps:L})})}var gn=new Set;function Go(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 mn(e,t=new Set){return mr.Children.forEach(e,r=>{if(!mr.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&&mn(n.children,t);}),t}function Yo({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:a="iframe",shared:u,events:k}){if(hr(r,e),a==="direct")return go.jsx(fn,{slotId:e,githubRepo:s,shared:u,events:k,entityBindings:o,children:r});let g=jt(e),{baseUrl:d,apiKey:w,appId:A,userId:f,userHash:p,currentContainerId:I,previewSession:M}=he(),h=mr.useRef(null),v=mr.useRef(false),T=mr.useRef(null),N=mr.useRef(i);N.current=i;let D=mr.useRef(t);D.current=t;let O=mr.useRef(n);O.current=n,mr.useEffect(()=>{if(typeof process<"u")return;let S=mn(r),c=new Set(i?Object.keys(i):[]),F=[...S].filter(P=>!c.has(P));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
|
-
`+F.map(
|
|
4
|
-
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),mr.useEffect(()=>{gn.has(e)||(gn.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:A,label:e,propsShape:t?Go(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,d,w,s,A,o]);let E=mr.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},"*"),T.current=null;}else T.current=S;},[]),L=mr.useCallback((S,c)=>{let F=O.current;return !F||F.length===0?false:F.some(P=>{let[C,x]=P.split(" "),y=c.split("?")[0];return S.toUpperCase()===C.toUpperCase()&&y.startsWith(x)})},[]);if(mr.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:O.current||[]},"*"),O.current,T.current?E(T.current):E(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:P}=c.data,C=N.current?.[F];C?(C(...P||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(c.data?.type==="slot:fetch"){let{id:F,method:P,url:C,body:x}=c.data,y=h.current?.contentWindow;if(!y)return;let _=P||"GET";if(!L(_,C)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${_} ${C} \u2014 not in allowedFetches`),y.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${_} ${C}`},"*");return}try{let z={method:_};x&&_!=="GET"&&(z.headers={"Content-Type":"application/json"},z.body=JSON.stringify(x));let V=await fetch(C,z),Q=await V.json();`${e}${F}${V.status}`,y.postMessage({type:"slot:fetch-response",id:F,data:Q,status:V.status},"*");}catch(z){console.error(`[ForkSlot:${e}] fetch #${F} failed:`,z.message),y.postMessage({type:"slot:fetch-response",id:F,error:z.message},"*");}}else if(c.data?.type==="slot:fork-data"){let{id:F,path:P,method:C,body:x}=c.data,y=h.current?.contentWindow;if(!y)return;if(!I||!A){y.postMessage({type:"slot:fork-data-response",id:F,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let _=typeof P=="string"&&P.startsWith("/")?P:`/${String(P||"")}`,z=_.startsWith("/api/v1/data")?_:`/api/v1/data${_}`;try{let V={Authorization:`Bearer ${w}`,"Content-Type":"application/json","X-Fork-App-Id":A,...te()};!M&&f&&(V["X-Fork-User-Id"]=f),!M&&p&&(V["X-Fork-User-Hash"]=p);let Q=typeof C=="string"?C.toUpperCase():"POST",j=new URL(`${d}${z}`),q={method:Q,headers:V};Q==="GET"?(j.searchParams.set("appId",A),j.searchParams.set("containerId",I)):q.body=JSON.stringify({appId:A,containerId:I,...x&&typeof x=="object"?x:{}});let de=await fetch(j.toString(),q),K=await de.json().catch(()=>({}));if(!de.ok){let G=typeof K?.error=="string"?K.error:`Fork data API ${de.status}`;y.postMessage({type:"slot:fork-data-response",id:F,error:G,status:de.status},"*");return}y.postMessage({type:"slot:fork-data-response",id:F,data:K,status:de.status},"*");}catch(V){y.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,E,L,I,A,w,d,M,p,f]),mr.useEffect(()=>{g?.bundleUrl&&v.current&&E(t||{});},[t,g?.bundleUrl,E]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,go.jsx(go.Fragment,{children:r});`${e}${g.bundleUrl}`;let B=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return go.jsx("iframe",{ref:h,src:B,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function zt({style:e={width:20,height:20},...t}){return go.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[go.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"}),go.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),go.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"}),go.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"}),go.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 rs=5600,kr=2147483002;function ns(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function os(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function br(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 ss(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 wr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=mr.useState(false),[s,i]=mr.useState(false),[a,u]=mr.useState(null),[k,g]=mr.useState(null),[d,w]=mr.useState(null),A=mr.useRef(0),f=n?48:40,p=ns(r),I=!!(p&&r?.state==="complete"&&r.unreadCompletedCount>0),M=I?p:k?.key??null,h=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(M&&M!==a&&(I||k)),T=h||v,N=I?r?.label:k?.label,D=v?"Built":r?.label??"Fork this app",O=v?N:r?.detail,E=br(r?.label??"Fork this app",r?.detail),L=br(D,O),B=v?Math.min(420,Math.max(326,L,k?.width??0,A.current+40)):L,S=v?46:40,c=T?[D,O].filter(Boolean).join(" "):ss(r,t)??"Fork this app",F=T?`${D}:${O??""}`:"idle",P=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!T;mr.useEffect(()=>{if(typeof document>"u")return;let q=document.createElement("div");return q.setAttribute("data-fork-button-host","true"),q.style.position="relative",q.style.zIndex=String(kr),document.body.appendChild(q),w(q),()=>{q.remove(),w(null);}},[]),mr.useEffect(()=>{h&&(A.current=E);},[E,h]),mr.useEffect(()=>{!I||!p||!r?.label||g(q=>{if(q?.key===p)return q;let de=Math.min(420,Math.max(326,br("Built",r.label),A.current+40));return {key:p,label:r.label,width:de,startedAt:Date.now()}});},[r?.label,p,I]),mr.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&g(null);},[r?.state,r?.unreadCompletedCount]),mr.useEffect(()=>{if(!M||!v||M===a)return;let q,de=k?.key===M?k.startedAt:Date.now(),K=()=>{if(Date.now()-de>=rs&&!os()){u(M);return}q=window.setTimeout(K,250);};return q=window.setTimeout(K,250),()=>{q!==void 0&&window.clearTimeout(q);}},[M,a,k?.key,k?.startedAt,v]);let C=T?{position:"fixed",bottom:24,right:24,zIndex:kr,width:`min(${B}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:kr,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"},x={minWidth:0,maxWidth:h?286:v?82:O?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},y={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},_={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"},z={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:v?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},j=go.jsxs(go.Fragment,{children:[go.jsx("style",{children:`
|
|
1
|
+
'use strict';var wr=require('react'),ko=require('react-dom'),bo=require('react/jsx-runtime'),wo=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 wr__namespace=/*#__PURE__*/_interopNamespace(wr);var ko__namespace=/*#__PURE__*/_interopNamespace(ko);var bo__namespace=/*#__PURE__*/_interopNamespace(bo);var wo__namespace=/*#__PURE__*/_interopNamespace(wo);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=wr__namespace),(r=e[Ge])["react-dom"]||(r["react-dom"]=ko__namespace),(n=e[Ge])["react/jsx-runtime"]||(n["react/jsx-runtime"]=bo__namespace),(o=e[Ge])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=wo__namespace),e[Ge]}function ur(e){return Object.assign(cr(),e)}var vo="__fork_preview_session__";function Ut(e){return `${vo}${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 rn(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function So(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Ut(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:rn(r)?(window.sessionStorage.removeItem(Ut(e)),null):r}catch{return null}}function fr(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Ut(e),JSON.stringify(t)):window.sessionStorage.removeItem(Ut(e));}catch{}}function at(e){ae.apiKey!==e&&(ae.apiKey=e,ae.session=So(e),Nt());}function Ne(){return ae.session?rn(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 nn="__fork_preview";function on(){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(nn);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 an()!==null}function sn(){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(nn);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 an(){if(Qe)return Qe;let e=on();return e?(Qe=e,sn(),Qe):null}async function hr(e,t){at(e);let r=Ne();if(r)return Qe=null,r;let n=Qe??on();if(Qe=null,!n)return null;sn();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
|
+
`);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 xo(){return Ne()}function Ao(){return null}function jt(){return wr.useSyncExternalStore(pr,xo,Ao)}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,m=u.legacyModuleUrl??u.legacyBundleUrl??null;i[a]={forkId:u.forkId,moduleUrl:b,legacyModuleUrl:m,bundleUrl:u.bundleUrl??b,legacyBundleUrl:u.legacyBundleUrl??m,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 Io="fork:manifest:v1";function kr(e,t,r){return `${Io}:${e}:${t}:${r}`}function _o(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 Ro(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(kr(e,t,r),JSON.stringify(n));}catch{}}function Eo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(kr(e,t,r));}catch{}}function Co(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 fn=wr.createContext(null),To=12e3,Mo=45e3,ln="fork:activity:v1",Lo=new Set(["pending","running","building"]),Ho="Setting up environment";function Ee(e){return Lo.has(e)}function Oo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function Bo(e,t){let r=Oo(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 cn(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{}}function Uo(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function No(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 Do(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():Ho,detail:s?Uo(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function mt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function 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 un(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 dn(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 Ko(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]=wr.useState(()=>(at(t),mr(t))),[b,m]=wr.useState({}),[d,w]=wr.useState(i?{userId:i,userHash:void 0}:null),[I,f]=wr.useState(!!i||u),[g,x]=wr.useState({}),[H,y]=wr.useState(!o),[v,M]=wr.useState(0),[U,N]=wr.useState(null),[D,R]=wr.useState(false),[T,O]=wr.useState([]),[S,c]=wr.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),F=wr.useRef(new Map),C=wr.useRef(new Map),[$,A]=wr.useState(0),k=wr.useRef(new Set),E=wr.useRef(new Map),G=wr.useRef(void 0),V=wr.useRef(new Map),q=wr.useRef([]),te=wr.useRef(new Set),X=wr.useRef(false);cr(),wr.useEffect(()=>{return hr(t,r).then(()=>{}),()=>{}},[]);let j=jt();wr.useEffect(()=>{u||j||!o||!d?.userHash||yr(t,r,{appId:o,userId:d.userId,userHash:d.userHash});},[t,o,d?.userHash,d?.userId,r,u,j?.preview_session_id]),s&&G.current!==s&&(ur(s),G.current=s),wr.useEffect(()=>{a&&(u||(f(false),fetch(a,{credentials:"include"}).then(h=>{if(!h.ok)throw new Error(`Auth endpoint returned ${h.status}`);return h.json()}).then(h=>{if(!h.userId||typeof h.userId!="string")throw new Error("authUrl response must include userId");w({userId:h.userId,userHash:typeof h.userHash=="string"?h.userHash:void 0});}).catch(h=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",h.message);}).finally(()=>{f(true);})));},[a,u]),wr.useEffect(()=>{!a&&i&&(w({userId:i,userHash:void 0}),f(true));},[i,a]);let ne=d?.userId??"",_e=d?.userHash,z=j?"":ne,ee=j?void 0:_e,ve=!!o,ie=wr.useCallback(async()=>{if(!ve){N(null),R(false),x({}),y(true),M(p=>p+1);return}if(!I){y(false);return}if(!j&&!z||!o){N(null),R(false),x({}),y(true),M(p=>p+1);return}if(y(false),!j){try{let p=await Kt({baseUrl:r,apiKey:t,appId:o,userId:z,userHash:ee});p&&(N(p.containerId),R(!!p.forksPaused),m(un(r,p,z,o)),x(dn(r,p)));}catch(p){console.error("[ForkProvider] Failed to fetch fork manifest:",p.message),N(null),R(false),m({}),x({});}finally{M(p=>p+1),y(true);}return}if(R(false),N(j.container_id??null),j.container_id){try{let p=await Kt({baseUrl:r,apiKey:t,appId:o,userId:z,containerId:j.container_id,extraHeaders:oe()});p&&(m(un(r,p,z,o)),x(dn(r,p)));}catch(p){console.error("[ForkProvider] Failed to fetch preview container manifest:",p.message),m({}),x({});}finally{M(p=>p+1),y(true);}return}let h=new URLSearchParams({appId:o,userId:z});ee&&h.set("userHash",ee);try{let p=await fetch(`${r}/api/v1/boundaries/manifest?${h.toString()}`,{headers:{Authorization:`Bearer ${t}`,...oe()}});if(!p.ok)throw new Error(`${p.status}`);let L=await p.json();x(jo(r,L));}catch(p){console.error("[ForkProvider] Failed to fetch module override manifest:",p.message),x({});}finally{M(p=>p+1),y(true);}},[t,o,r,I,ve,ee,z,j?.preview_session_id,j?.fork_id,j?.container_id]);wr.useEffect(()=>{if(!z||o&&(!j||j.container_id))return;let h=new URLSearchParams({userId:z});ee&&h.set("userHash",ee),fetch(`${r}/api/v1/forks/active?${h.toString()}`,{headers:{Authorization:`Bearer ${t}`,...oe()}}).then(p=>{if(!p.ok)throw new Error(`${p.status}`);return p.json()}).then(p=>{p&&typeof p=="object"&&m(p);}).catch(()=>{});},[t,o,z,ee,r,j?.preview_session_id,j?.fork_id]),wr.useEffect(()=>{ie();},[ie]);let Me=wr.useCallback(async h=>{if(!(j||!o||!z)){R(h),h&&(m({}),x({}),M(p=>p+1));try{let p=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:h,userId:z,userHash:ee})});if(!p.ok)throw new Error(`${p.status}`);h||await ie();}catch(p){console.error("[ForkProvider] Failed to persist fork pause state:",p?.message??p),ie().catch(()=>{});}}},[t,o,r,ie,j,ee,z]),ze=wr.useCallback((h,p)=>{m(L=>({...L,[h]:p}));},[]),nt=wr.useCallback(h=>{m(p=>{let L={...p};return delete L[h],L});},[]),Pe=wr.useCallback(h=>{k.current.add(h);},[]),We=wr.useCallback(h=>k.current.has(h)?(k.current.delete(h),true):false,[]),Je=wr.useCallback((h,p)=>{E.current.set(h,p);},[]),Ct=wr.useCallback((h,p)=>E.current.get(h)!==p?false:(E.current.delete(h),true),[]),or=wr.useCallback(h=>{if(!o)return;let p=JSON.stringify(h);F.current.get(h.id)===p||C.current.get(h.id)?.signature===p||(C.current.set(h.id,{boundary:h,signature:p}),A(Q=>Q+1));},[o]);wr.useEffect(()=>{if(!o||C.current.size===0)return;let h=setTimeout(()=>{let p=Array.from(C.current.values());p.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:p.map(L=>L.boundary)})}).then(L=>{if(!L.ok)throw new Error(`${L.status}`)}).then(()=>{for(let L of p)C.current.get(L.boundary.id)?.signature===L.signature&&(C.current.delete(L.boundary.id),F.current.set(L.boundary.id,L.signature));}).catch(L=>{console.error("[ForkProvider] Failed to register module boundaries:",L.message);});},50);return ()=>{clearTimeout(h);}},[t,o,r,$]);let $t=wr.useCallback(h=>g[h],[g]),ge=j?`preview:${j.preview_session_id}`:z,Ve=`${t}:${o||"no-app"}:${U||"no-container"}:${ge||"anonymous"}`,sr=j?`op:${j.operator_id}`:z,Pt=`${t}:${o||"no-app"}:${sr||"anonymous"}`,Se=`${ln}:seen:${Ve}`,me=`${ln}:tracked:${Ve}`;wr.useEffect(()=>{q.current=T;},[T]);let Te=wr.useCallback(()=>{let h={Authorization:`Bearer ${t}`,...oe()};return o&&(h["X-Fork-App-Id"]=o),!j&&z&&(h["X-Fork-User-Id"]=z),!j&&ee&&(h["X-Fork-User-Hash"]=ee),h},[t,o,j,ee,z]);wr.useEffect(()=>{if(typeof window>"u")return;let h=window.__FORK_RUNTIME__,p={dataFetch:async(L,Q,K="POST")=>{if(!o||!U)throw new Error("Fork data is unavailable until appId and containerId are resolved");let W=typeof L=="string"&&L.startsWith("/")?L:`/${String(L||"")}`,re=W.startsWith("/api/v1/data")?W:`/api/v1/data${W}`,se=K.toUpperCase(),ce=new URL(`${r}${re}`),ue={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...oe()};!j&&z&&(ue["X-Fork-User-Id"]=z),!j&&ee&&(ue["X-Fork-User-Hash"]=ee);let de={method:se,headers:ue};se==="GET"?(ce.searchParams.set("appId",o),ce.searchParams.set("containerId",U)):de.body=JSON.stringify({appId:o,containerId:U,...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__=p,()=>{window.__FORK_RUNTIME__===p&&(window.__FORK_RUNTIME__=h);}},[t,o,r,U,j,ee,z]);let Fe=wr.useCallback(async()=>{if(!U)return;let h=new URLSearchParams({container_id:U}),p=await fetch(`${r}/api/v1/forks?${h.toString()}`,{headers:Te()}).catch(()=>null);if(!p||!p.ok)return;let L=await p.json().catch(()=>({})),Q=Array.isArray(L.forks)?L.forks:[],K=Ze(Se),W=Ze(me),re=false,se=new Map(q.current.map(ue=>[ue.id,ue])),ce=[];for(let ue of Q){let de=cn(ue);Ee(de.status)&&!W.has(de.id)&&(W.add(de.id),re=true);let fe=se.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=cn(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);ie().catch(()=>{});}X.current=true;},[Se,me,r,Te,U,ie,Je]),ct=wr.useCallback((h,p)=>{let L=Bo(h,p);if(!L)return;let Q=h.containerId??h._containerId;if(Q&&!U&&N(Q),Ee(L.status)){let re=Ze(me);re.has(L.id)||(re.add(L.id),et(me,re)),R(false);}let K=new Map(q.current.map(re=>[re.id,re]));K.set(L.id,zt(K.get(L.id),L));let W=[...K.values()].sort((re,se)=>Date.parse(se.updatedAt)-Date.parse(re.updatedAt));q.current=W,O(W);},[me,U]),ot=wr.useCallback((h,p)=>{let L=No(p),Q=Ze(Se),K=Ze(me),W=q.current.find(fe=>fe.id===h),re=W?Ee(W.status):false;L.status&&Ee(L.status)&&!K.has(h)&&(K.add(h),et(me,K));let se=W?zt(W,{...W,...L}):null,ce=se?gt(se):null,ue=!!(se&&se.status==="complete"&&(K.has(h)||re)&&ce&&!Q.has(ce)&&!te.current.has(ce)&&!W?.unread),de=p.type==="complete"&&W?.targetKind==="module"?W.targetId:null;if(O(fe=>{let J=fe.find(Ie=>Ie.id===h);if(!J)return fe;let xe=zt(J,{...J,...L}),le=xe.status==="complete"&&(K.has(h)||Ee(J.status))&&!Q.has(gt(xe)),Ae={...xe,unread:le},we=fe.map(Ie=>Ie.id===h?Ae:Ie).sort((Ie,ut)=>Date.parse(ut.updatedAt)-Date.parse(Ie.updatedAt));return q.current=we,we}),ue&&se&&ce&&te.current.add(ce),p.type==="complete"){let fe=p.data&&typeof p.data=="object"?p.data:{},J=typeof fe.boundaryId=="string"?fe.boundaryId:de;J&&Je(J,h),ie().catch(()=>{});}},[Se,me,ie,Je]),Le=wr.useCallback(h=>{let p=Ze(Se),L=Ze(me),Q=false,K=false;for(let W of q.current){if(W.status!=="complete"||h&&W.id!==h)continue;let re=gt(W);p.has(re)||(p.add(re),Q=true),L.delete(W.id)&&(K=true);}O(W=>{let re=W.map(se=>se.status!=="complete"||h&&se.id!==h?se:{...se,unread:false});return q.current=re,re}),Q&&et(Se,p),K&&et(me,L);},[Se,me]);wr.useEffect(()=>{X.current=false,te.current.clear(),O([]);for(let h of V.current.values())h.close();V.current.clear(),U&&Fe();},[U,Fe]),wr.useEffect(()=>{if(typeof document>"u")return;let h=()=>{let p=document.visibilityState!=="hidden";c(p),p&&U&&Fe();};return document.addEventListener("visibilitychange",h),window.addEventListener("focus",h),window.addEventListener("online",h),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("focus",h),window.removeEventListener("online",h);}},[U,Fe]),wr.useEffect(()=>{let h=T.filter(Q=>Ee(Q.status));if(!U||h.length===0)return;let p=S?To:Mo,L=window.setInterval(()=>{Fe();},p);return ()=>window.clearInterval(L)},[U,S,T,Fe]),wr.useEffect(()=>{for(let h of V.current.values())h.close();V.current.clear();},[t,r,j?.preview_session_id,ee,z]),wr.useEffect(()=>{let h=new Set(T.filter(p=>Ee(p.status)).map(p=>p.id));for(let[p,L]of V.current.entries())h.has(p)||(L.close(),V.current.delete(p));for(let p of h){if(V.current.has(p))continue;let L=new URLSearchParams({key:t});j?(L.set("previewSessionId",j.preview_session_id),L.set("previewForkId",p)):z&&L.set("userId",z),ee&&L.set("userHash",ee);let Q=new EventSource(`${r}/api/v1/forks/${p}/events?${L.toString()}`);Q.onmessage=K=>{try{ot(p,JSON.parse(K.data));}catch{}},Q.onerror=()=>{Q.close(),V.current.delete(p);},V.current.set(p,Q);}},[t,r,T,j,ot,ee,z]),wr.useEffect(()=>()=>{for(let h of V.current.values())h.close();V.current.clear();},[]);let ir=Do(T),qe=wr.useCallback(async()=>{if(!z)throw new Error("Reset requires a resolved user identity.");let h=new URLSearchParams({userId:z});ee&&h.set("userHash",ee);let p={Authorization:`Bearer ${t}`,...oe()};o&&(p["X-Fork-App-Id"]=o);let L=await fetch(`${r}/api/v1/forks/all?${h.toString()}`,{method:"DELETE",headers:p});if(!L.ok){let K=await L.json().catch(()=>({}));throw new Error(K.error||`API error: ${L.status}`)}let Q=await L.json().catch(()=>({}));m({}),x({}),y(true),M(K=>K+1),O([]),te.current.clear(),et(Se,new Set),et(me,new Set),k.current.clear(),E.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 bo.jsx(fn.Provider,{value:{apiKey:t,userId:z,userHash:ee,baseUrl:r,appId:o,forks:b,moduleOverridesEnabled:ve,moduleManifestReady:H,moduleManifestVersion:v,currentContainerId:U,forksPaused:D,setForksPaused:Me,forkActivities:T,activitySummary:ir,previewSession:j,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:ie,resetAllForks:qe,highlightScope:Pt},children:n})}function ye(){let e=wr.useContext(fn);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 vr(e,t){let r;try{r=wr.Children.only(e);}catch{let o=wr.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 gn=new Set;function mn(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 Xo(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 yn(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 hn(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 m=0;m<e.length;m++){let{rect:d,borderRadius:w}=e[m],I=d.left-.5,f=d.top-.5,g=d.width+1,x=d.height+1,H=Math.min(w+.5,g/2,x/2),y=yn(I,f,g,x,H),v=`__fork-glow-${m}`,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 U=document.createElementNS(t,"feGaussianBlur");U.setAttribute("in","SourceGraphic"),U.setAttribute("stdDeviation","8"),M.appendChild(U),o.appendChild(M);let N=`__fork-mask-${m}`,D=document.createElementNS(t,"mask");D.setAttribute("id",N),D.setAttribute("maskUnits","userSpaceOnUse"),D.setAttribute("x",String(I-200)),D.setAttribute("y",String(f-200)),D.setAttribute("width",String(g+400)),D.setAttribute("height",String(x+400));let R=document.createElementNS(t,"rect");R.setAttribute("x",String(I-200)),R.setAttribute("y",String(f-200)),R.setAttribute("width",String(g+400)),R.setAttribute("height",String(x+400)),R.setAttribute("fill","white"),D.appendChild(R);let T=document.createElementNS(t,"path");T.setAttribute("d",y),T.setAttribute("fill","black"),D.appendChild(T),o.appendChild(D);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${N})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",y),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",y),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 m=0;m<s.length;m+=2){let d=s[m],w=s[m+1],I=d.__group,f=w.getTotalLength(),g=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=g*.35;d.setAttribute("stroke-dasharray",`${H} ${g-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*g,offset:.06},{strokeDashoffset:-2*g,offset:.92},{strokeDashoffset:-2.25*g,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 m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Go(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,m=a.top,d=a.width,w=a.height,I=Math.min(u,d/2,w/2),f=yn(b,m,d,w,I),g=document.createElementNS(t,"path");g.setAttribute("d",f),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Yo(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 Qo=wr__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return bo.jsx("div",{ref:r,style:n,children:bo.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Yo(e.hostProps,t.hostProps)),br=class extends wr__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 kn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){vr(t,e);let i=Wt(e),{baseUrl:a,apiKey:u,appId:b,shouldSkipAnimation:m}=ye(),[d,w]=wr.useState(null),I=wr.useRef(null),f=wr.useRef(null),g=wr.useRef(null),x=wr.useRef(false),H=wr.useRef(null),y=wr.useRef(null),v=!!(n||o),M=wr.useRef(null);v&&!M.current&&(M.current=new ht(e));let U=wr.useRef(o);if(U.current=o,wr.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);wr.useEffect(()=>{if(!v)return;M.current||(M.current=new ht(e));let O=M.current,S=Object.keys(U.current||{}).map(c=>O.on(c,(...F)=>U.current?.[c]?.(...F)));return ()=>S.forEach(c=>c())},[v,e]),wr.useEffect(()=>{if(gn.has(e))return;gn.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 N=i?.id||null;wr.useEffect(()=>{if(i?.bundleUrl,I.current,f.current,!i?.bundleUrl||!N){return}let O=`${a}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,c=sessionStorage.getItem(S),F=m(e),C=!F&&c!==N;if(F&&N&&sessionStorage.setItem(S,N),C&&f.current){let G=mn(f.current);g.current=G,x.current=true,`${e}${G.length}`;}window.__FORK_REACT__=wr__namespace.default,window.__FORK_REACT_DOM__=ko__namespace,window.__FORK_REACT_JSX__=bo__namespace;let $=Date.now(),A=`${a}${i.bundleUrl.replace("bundle.js","component.css")}?t=${$}`,k=document.createElement("link");k.rel="stylesheet",k.href=A,k.dataset.forkSlot=e,document.head.appendChild(k);let E=document.createElement("script");return E.src=O+"?t="+$,E.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(f.current&&g.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("*"),j=q.querySelectorAll("*");for(let ne=0;ne<X.length;ne++)X[ne].scrollTop!==0&&(j[ne].scrollTop=X[ne].scrollTop),X[ne].scrollLeft!==0&&(j[ne].scrollLeft=X[ne].scrollLeft);H.current=q;}w(()=>G.default),I.current=N;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},E.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(E),()=>{E.remove(),k.remove(),y.current&&(clearTimeout(y.current),y.current=null),H.current&&(H.current.remove(),H.current=null);}},[N,a,e]),wr.useEffect(()=>{if(!x.current||!d||!f.current){`${e}${x.current}`,f.current;return}let O=g.current;if(!O){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!f.current)return;let S=mn(f.current),c=qo(O,S),F=Xo(O,S),C=H.current;if(`${e}${c.length}${F.length}`,F.length>0&&C){let $=Go(F);y.current=setTimeout(()=>{y.current=null;let A=400;C.animate([{opacity:1},{opacity:0}],{duration:A,fill:"forwards"}),$.animate([{opacity:1},{opacity:0}],{duration:A,fill:"forwards"}),setTimeout(()=>{C.remove(),$.remove(),H.current=null,c.length>0&&(hn(c));},A);},3500);}else C&&(C.remove(),H.current=null),c.length>0&&(hn(c));g.current=null,x.current=false,N&&(sessionStorage.setItem(`__fork_animated_${e}`,N),`${e}`);});});},[d]);let D={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return bo.jsx("div",{ref:f,style:D,children:t});if(!d)return bo.jsx("div",{ref:f,style:D,children:t});let T=t?.props??{};return bo.jsx(br,{slotId:e,resetKey:N,fallback:bo.jsx("div",{ref:f,style:D,children:t}),children:bo.jsx(Qo,{component:d,containerRef:f,wrapperStyle:D,hostProps:T})})}var wn=new Set;function ts(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 vn(e,t=new Set){return wr.Children.forEach(e,r=>{if(!wr.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&&vn(n.children,t);}),t}function rs({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:a="iframe",shared:u,events:b}){if(vr(r,e),a==="direct")return bo.jsx(kn,{slotId:e,githubRepo:s,shared:u,events:b,entityBindings:o,children:r});let m=Wt(e),{baseUrl:d,apiKey:w,appId:I,userId:f,userHash:g,currentContainerId:x,previewSession:H}=ye(),y=wr.useRef(null),v=wr.useRef(false),M=wr.useRef(null),U=wr.useRef(i);U.current=i;let N=wr.useRef(t);N.current=t;let D=wr.useRef(n);D.current=n,wr.useEffect(()=>{if(typeof process<"u")return;let S=vn(r),c=new Set(i?Object.keys(i):[]),F=[...S].filter(C=>!c.has(C));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
|
+
`+F.map(C=>` - ${C}`).join(`
|
|
4
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),wr.useEffect(()=>{wn.has(e)||(wn.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?ts(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 R=wr.useCallback(S=>{let c=y.current;if(c?.contentWindow&&v.current){let F=U.current?Object.keys(U.current):[];c.contentWindow.postMessage({type:"slot:props",props:S,callbackNames:F},"*"),M.current=null;}else M.current=S;},[]),T=wr.useCallback((S,c)=>{let F=D.current;return !F||F.length===0?false:F.some(C=>{let[$,A]=C.split(" "),k=c.split("?")[0];return S.toUpperCase()===$.toUpperCase()&&k.startsWith(A)})},[]);if(wr.useEffect(()=>{if(!m?.bundleUrl)return;let S=async c=>{if(c.source===y.current?.contentWindow){if(c.data?.type==="slot:ready")v.current=true,y.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:D.current||[]},"*"),D.current,M.current?R(M.current):R(N.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}=c.data,$=U.current?.[F];$?($(...C||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(c.data?.type==="slot:fetch"){let{id:F,method:C,url:$,body:A}=c.data,k=y.current?.contentWindow;if(!k)return;let E=C||"GET";if(!T(E,$)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${E} ${$} \u2014 not in allowedFetches`),k.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${E} ${$}`},"*");return}try{let G={method:E};A&&E!=="GET"&&(G.headers={"Content-Type":"application/json"},G.body=JSON.stringify(A));let V=await fetch($,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:C,method:$,body:A}=c.data,k=y.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 E=typeof C=="string"&&C.startsWith("/")?C:`/${String(C||"")}`,G=E.startsWith("/api/v1/data")?E:`/api/v1/data${E}`;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&&g&&(V["X-Fork-User-Hash"]=g);let q=typeof $=="string"?$.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 j=await fetch(te.toString(),X),ne=await j.json().catch(()=>({}));if(!j.ok){let _e=typeof ne?.error=="string"?ne.error:`Fork data API ${j.status}`;k.postMessage({type:"slot:fork-data-response",id:F,error:_e,status:j.status},"*");return}k.postMessage({type:"slot:fork-data-response",id:F,data:ne,status:j.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;}},[m?.bundleUrl,e,R,T,x,I,w,d,H,g,f]),wr.useEffect(()=>{m?.bundleUrl&&v.current&&R(t||{});},[t,m?.bundleUrl,R]),!m||m.status!=="complete"||!m.bundleUrl)return `${e}${m?.status||"none"}${m?.bundleUrl||"none"}`,bo.jsx(bo.Fragment,{children:r});`${e}${m.bundleUrl}`;let O=`${d}${m.bundleUrl.replace("/bundle.js","/host")}`;return bo.jsx("iframe",{ref:y,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 bo.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[bo.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"}),bo.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),bo.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"}),bo.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"}),bo.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 as=5600,Fr=2147483002;function ls(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function cs(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function xr(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 us(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 Ar({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=wr.useState(false),[s,i]=wr.useState(false),[a,u]=wr.useState(null),[b,m]=wr.useState(null),[d,w]=wr.useState(null),I=wr.useRef(0),f=n?48:40,g=ls(r),x=!!(g&&r?.state==="complete"&&r.unreadCompletedCount>0),H=x?g:b?.key??null,y=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(H&&H!==a&&(x||b)),M=y||v,U=x?r?.label:b?.label,N=v?"Built":r?.label??"Fork this app",D=v?U:r?.detail,R=xr(r?.label??"Fork this app",r?.detail),T=xr(N,D),O=v?Math.min(420,Math.max(326,T,b?.width??0,I.current+40)):T,S=v?46:40,c=M?[N,D].filter(Boolean).join(" "):us(r,t)??"Fork this app",F=M?`${N}:${D??""}`:"idle",C=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!M;wr.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(Fr),document.body.appendChild(X),w(X),()=>{X.remove(),w(null);}},[]),wr.useEffect(()=>{y&&(I.current=R);},[R,y]),wr.useEffect(()=>{!x||!g||!r?.label||m(X=>{if(X?.key===g)return X;let j=Math.min(420,Math.max(326,xr("Built",r.label),I.current+40));return {key:g,label:r.label,width:j,startedAt:Date.now()}});},[r?.label,g,x]),wr.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&m(null);},[r?.state,r?.unreadCompletedCount]),wr.useEffect(()=>{if(!H||!v||H===a)return;let X,j=b?.key===H?b.startedAt:Date.now(),ne=()=>{if(Date.now()-j>=as&&!cs()){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 $=M?{position:"fixed",bottom:24,right:24,zIndex:Fr,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:Fr,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:y?286:v?82:D?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:y?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},E={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=bo.jsxs(bo.Fragment,{children:[bo.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
|
-
`}),
|
|
19
|
+
`}),bo.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:$,title:c,"aria-label":c,children:[M&&r?bo.jsxs(bo.Fragment,{children:[y?bo.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"}}):bo.jsx("span",{"aria-hidden":true,style:G}),bo.jsxs("span",{style:E,children:[bo.jsx("span",{style:A,children:N}),D&&bo.jsx("span",{style:k,children:D})]},F)]}):bo.jsx(Vt,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),C&&bo.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?ko.createPortal(te,d):te}var ks={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},bs={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},ws={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},vs={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function _r(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 Rn({events:e}){let t=wr.useRef(null);return wr.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),bo.jsxs(bo.Fragment,{children:[bo.jsx("style",{children:`
|
|
20
20
|
@keyframes __fork-spin {
|
|
21
21
|
from { transform: rotate(0deg); }
|
|
22
22
|
to { transform: rotate(360deg); }
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
.__fork-stream::-webkit-scrollbar-thumb:hover {
|
|
35
35
|
background: rgba(255, 255, 255, 0.3);
|
|
36
36
|
}
|
|
37
|
-
`}),go.jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&go.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[go.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,s=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",i=o&&!s&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=ps[r.type]||lucideReact.Code,u=gs[r.type]||"#9ca3af";if(r.type==="tool_use"){let k=String(r.data.category||"");a=ms[k]||lucideReact.Wrench,u=hs[k]||"#fbbf24";}return i?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,u="#4ade80"),go.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[go.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:u,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),go.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Sr(r)})]},n)})]})]})}var An=35,As="Setting up environment",Is="Built Custom Feature",In=360,wt=380;function _s(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function Rs(e){return e.length<=An?e:e.slice(0,An-3).trimEnd()+"..."}function Es({events:e}){let[t,r]=mr.useState("Setting up environment..."),[n,o]=mr.useState(true),s=mr.useRef(t),i=mr.useRef(false);return mr.useEffect(()=>{if(!i.current){for(let u of e)if(u.type==="status"&&String(u.data.message||"").includes("Agent started")){i.current=true;break}}let a="Setting up environment...";if(i.current)for(let u=e.length-1;u>=0;u--){let k=e[u];if(k.type==="tool_use"||k.type==="build_start"||k.type==="build_complete"){a=Rs(Sr(k));break}}if(a!==s.current){o(false);let u=setTimeout(()=>{r(a),s.current=a,o(true);},200);return ()=>clearTimeout(u)}},[e]),go.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Cs({children:e}){let[t,r]=mr.useState(null);return mr.useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?po.createPortal(e,t):null}function qt({state:e,fork:t,events:r,error:n,slotId:o,targetId:s,targetLabel:i,historyMode:a="slot",onSubmit:u,onUndo:k,onClose:g,baseUrl:d,apiKey:w,userId:A,userHash:f,appId:p,embedded:I=false,completeVariant:M="bubble"}){let[h,v]=mr.useState(""),[T,N]=mr.useState([]),[D,O]=mr.useState(false),[E,L]=mr.useState(false),[B,S]=mr.useState(false),[c,F]=mr.useState(false),[P,C]=mr.useState(false),[x,y]=mr.useState(false),[_,z]=mr.useState(false),[V,Q]=mr.useState(false),[j,q]=mr.useState(false),[de,K]=mr.useState(null),[G,we]=mr.useState(false),[ve,_e]=mr.useState([]),[ye,Me]=mr.useState(null),[We,Ce]=mr.useState(false),[$e,Je]=mr.useState(false),[tr,at]=mr.useState(false),[Et,Ct]=mr.useState(null),[re,ge]=mr.useState(null),[$t,Pe]=mr.useState(false),[lt,Be]=mr.useState(false),[Le,Ve]=mr.useState(""),ct=mr.useRef(null),[b,m]=mr.useState(null),[H,X]=mr.useState(false),[J,W]=mr.useState(null),[ne,ue]=mr.useState([]),[Z,le]=mr.useState(null),[ce,oe]=mr.useState(false),se=mr.useRef(false),Se=mr.useRef(null),fe=mr.useRef(null),{resetAllForks:Fe,previewSession:ie,currentContainerId:Te}=he(),Re=ie?.container_id??Te,rt=!!(ie&&H),xe=J!==null,Br=mr.useRef(g);mr.useEffect(()=>{Br.current=g;});let rr=mr.useRef(null),Pt=mr.useRef(false),Dr=typeof window<"u"&&"documentPictureInPicture"in window,oo=async()=>{if(!(!Dr||xe))try{let l=await window.documentPictureInPicture.requestWindow({width:In,height:640});l.document.body.style.margin="0",l.document.body.style.padding="0",l.document.body.style.height="100vh",l.document.body.style.overflow="hidden",l.document.body.style.background="#ffffff";try{let R=document.adoptedStyleSheets??[];R.length>0&&(l.document.adoptedStyleSheets=[...R]);}catch{}l.addEventListener("pagehide",()=>{rr.current=null,W(null),Pt.current||Br.current(),Pt.current=!1;},{once:!0}),rr.current=l,W(l);}catch(l){console.warn("[Fork] PiP open failed:",l);}},so=()=>{J&&(Pt.current=true,J.close());};mr.useEffect(()=>()=>{Pt.current=true,rr.current?.close();},[]);let nt=s??o??"",io=(i||nt).replace(/[-_]+/g," ").replace(/\b\w/g,l=>l.toUpperCase()),Tt=mr.useRef(""),jr=()=>{let l={Authorization:`Bearer ${w}`,...te()};return p&&(l["X-Fork-App-Id"]=p),!ie&&A&&(l["X-Fork-User-Id"]=A),!ie&&f&&(l["X-Fork-User-Hash"]=f),l},ot=I?true:E&&!B,ao=r.find(l=>{let R=l.data;return l.type==="status"&&R.summary})?.data?.summary||t?.summary||As,qe=r.find(l=>{let R=l.data;return (l.type==="status"||l.type==="complete")&&typeof R?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;mr.useEffect(()=>{if(a==="none"){O(true);return}if(!d||!w)return;if(!Z){N([]),O(true);return}let l=new AbortController;return fetch(`${d}/api/v1/forks/${encodeURIComponent(Z)}/messages`,{headers:jr(),signal:l.signal}).then(R=>R.ok?R.json():[]).then(R=>{if(l.signal.aborted)return;let U=[];for(let me of R){let He=me.forkId??Z;me.role==="user"?U.push({type:"user",text:me.content,forkId:He}):U.push({type:"applied",text:me.content,forkId:He});}N(U),O(true);}).catch(()=>{l.signal.aborted||O(true);}),()=>{l.abort();}},[w,p,d,a,Z,ie?.fork_id,ie?.preview_session_id,f,A,t?.id,t?.completedAt]),mr.useEffect(()=>{if(a==="none"||!d||!w||!We)return;if(!ye){ue([]);return}let l=new AbortController,R=new URLSearchParams({container_id:ye});return fetch(`${d}/api/v1/forks?${R.toString()}`,{headers:jr(),signal:l.signal}).then(U=>U.ok?U.json():{forks:[]}).then(U=>{l.signal.aborted||ue(U.forks??[]);}).catch(()=>{}),()=>{l.abort();}},[w,p,d,a,ye,We,t?.id,t?.completedAt,ie?.fork_id,ie?.preview_session_id,f,A]),mr.useEffect(()=>{e==="complete"&&Q(false);},[e]);let Kr=ne.some(l=>l.status==="pending"||l.status==="running"||l.status==="building");mr.useEffect(()=>{if(!Kr||!d||!w||!ye)return;let l=new URLSearchParams({container_id:ye}),R={Authorization:`Bearer ${w}`,...te()};p&&(R["X-Fork-App-Id"]=p);let me=setInterval(async()=>{try{let He=await fetch(`${d}/api/v1/forks?${l.toString()}`,{headers:R});if(!He.ok)return;let uo=await He.json();ue(uo.forks??[]);}catch{}},3e3);return ()=>clearInterval(me)},[Kr,d,w,p,ye]),mr.useEffect(()=>{if(I&&a==="none"){_e([]),Me(null),Ce(true),X(false);return}if(ie){let l=false;return Ce(false),X(false),m(null),fetch(`${d}/api/v1/preview/${encodeURIComponent(ie.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${w}`,...te()}}).then(R=>{if(!R.ok)throw new Error(`${R.status}`);return R.json()}).then(R=>{l||(_e(R.containers),Me(R.currentContainerId??ie.container_id??null),X(true));}).catch(R=>{l||(X(false),m(R instanceof Error?R.message:String(R)),Re?(_e([{id:Re,name:ie.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),Me(Re)):(_e([]),Me(null)));}).finally(()=>{l||Ce(true);}),()=>{l=true;}}Re?(_e([{id:Re,name:"Primary container",createdAt:""}]),Me(Re)):(_e([]),Me(null)),Ce(true),X(false);},[w,Re,d,I,a,ie?.container_id,ie?.container_name,ie?.preview_session_id]);let Mt=mr.useRef(void 0);mr.useEffect(()=>{if(We){if(Mt.current===void 0){Mt.current=ye;return}Mt.current!==ye&&(Mt.current=ye,N([]),O(false));}},[ye,We]);let Lt=mr.useRef(null);mr.useEffect(()=>{if(!$e)return;let l=U=>{if(!Lt.current)return;let me=typeof U.composedPath=="function"?U.composedPath():[];Lt.current.contains(U.target)||me.includes(Lt.current)||Je(false);},R=U=>{U.key==="Escape"&&Je(false);};return document.addEventListener("mousedown",l,true),document.addEventListener("keydown",R,true),()=>{document.removeEventListener("mousedown",l,true),document.removeEventListener("keydown",R,true);}},[$e]),mr.useEffect(()=>{if(I||!ot||B||xe)return;let l=R=>{(typeof R.composedPath=="function"?R.composedPath():[]).some(He=>He instanceof Element&&He.hasAttribute("data-fork-panel-host"))||(S(true),L(false),setTimeout(()=>g(),wt));};return document.addEventListener("mousedown",l,true),()=>{document.removeEventListener("mousedown",l,true);}},[I,ot,B,xe,g]),mr.useEffect(()=>{$e||(Be(false),Ve(""));},[$e]),mr.useEffect(()=>{lt&&(ct.current?.focus(),ct.current?.select());},[lt]),mr.useEffect(()=>{if(I)return;let l=requestAnimationFrame(()=>L(true));return ()=>cancelAnimationFrame(l)},[I]),mr.useEffect(()=>{let l=I||xe;if((l||ot)&&(e==="prompting"||e==="complete")){let R=setTimeout(()=>Se.current?.focus(),l?100:wt+100);return ()=>clearTimeout(R)}},[ot,I,xe,e]),mr.useEffect(()=>{if(e==="complete"&&Tt.current){let R=r.find(U=>U.type==="complete")?.data?.summary||t?.summary||Is;N(U=>U[U.length-1]?.type==="applied"?U:[...U,{type:"applied",text:R}]),v(""),setTimeout(()=>Se.current?.focus(),200);}},[e,io,r,t?.summary]),mr.useEffect(()=>{fe.current&&(fe.current.scrollTop=fe.current.scrollHeight);},[T,e]);let zr=()=>{if(h.trim()){Tt.current=h.trim();let l={},R=ce||!Z;R?(l.forceNew=true,se.current=true,ce||oe(true)):l.forkId=Z,R||N(U=>[...U,{type:"user",text:h.trim(),forkId:Z}]),u(h.trim(),nt,ye,l),v("");}};mr.useEffect(()=>{if(se.current){if(e==="error"){se.current=false;return}t?.id&&(le(t.id),oe(false),se.current=false);}},[t?.id,e]),mr.useEffect(()=>{t?.id&&(se.current||e!=="running"&&e!=="complete"||(le(l=>l??t.id),oe(false)));},[t?.id,e]);let Wr=l=>{Ge(l.session.containerId,l.session.containerName),Me(l.session.containerId),_e(R=>{let U=R.filter(me=>me.id!==l.container.id);return [{...l.container,isPrimary:true,hasAccess:true},...U.map(me=>({...me,isPrimary:false}))]}),le(null),oe(false),se.current=false,N([]),O(false),Tt.current="";},lo=async l=>{if(!(!ie||!rt||re)){ge(l),m(null);try{let R=await fetch(`${d}/api/v1/preview/${encodeURIComponent(ie.preview_session_id)}/containers/${encodeURIComponent(l)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${w}`,...te()}});if(!R.ok){let U=await R.json().catch(()=>({}));throw new Error(U.error||`API error: ${R.status}`)}Wr(await R.json()),Je(!1);}catch(R){m(R instanceof Error?R.message:String(R));}finally{ge(null);}}},Jr=async l=>{if(!ie||!rt||re)return;let R=l.trim();if(R){ge("__new__"),m(null);try{let U=await fetch(`${d}/api/v1/preview/${encodeURIComponent(ie.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,...te()},body:JSON.stringify({name:R})});if(!U.ok){let me=await U.json().catch(()=>({}));throw new Error(me.error||`API error: ${U.status}`)}Wr(await U.json()),Be(!1),Ve(""),Je(!1);}catch(U){m(U instanceof Error?U.message:String(U));}finally{ge(null);}}},Vr=async()=>{if(!(!k||j||!nt)){q(true);try{let l=await k(nt);N(R=>{let U=[...R];return U.length>=2&&U[U.length-1]?.type==="applied"?U.splice(-2,2):U.length>=1&&U[U.length-1]?.type==="applied"&&U.splice(-1,1),U}),l?.removed&&N([]);}catch{}finally{q(false);}}},qr=()=>{if(I){g();return}if(xe){J?.close();return}S(true),L(false),setTimeout(()=>g(),wt);},co=I||xe?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:In,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:ot?"translateX(0)":"translateX(100%)",transition:`transform ${wt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${wt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Xr=ve.find(l=>l.id===ye)?.name??(We?"Fork":"Loading..."),ut=ce?[]:Z?T.filter(l=>l.forkId===Z||l.forkId==null):T,nr=go.jsxs(go.Fragment,{children:[go.jsx("style",{children:`
|
|
37
|
+
`}),bo.jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&bo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[bo.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,s=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",i=o&&!s&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=ks[r.type]||lucideReact.Code,u=bs[r.type]||"#9ca3af";if(r.type==="tool_use"){let b=String(r.data.category||"");a=ws[b]||lucideReact.Wrench,u=vs[b]||"#fbbf24";}return i?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,u="#4ade80"),bo.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[bo.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:u,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),bo.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:_r(r)})]},n)})]})]})}var $n=35,Cs="Setting up environment",$s="Built Custom Feature",Pn=360,vt=380;function Ps(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function Ts(e){return e.length<=$n?e:e.slice(0,$n-3).trimEnd()+"..."}function Ms({events:e}){let[t,r]=wr.useState("Setting up environment..."),[n,o]=wr.useState(true),s=wr.useRef(t),i=wr.useRef(false);return wr.useEffect(()=>{if(!i.current){for(let u of e)if(u.type==="status"&&String(u.data.message||"").includes("Agent started")){i.current=true;break}}let a="Setting up environment...";if(i.current)for(let u=e.length-1;u>=0;u--){let b=e[u];if(b.type==="tool_use"||b.type==="build_start"||b.type==="build_complete"){a=Ts(_r(b));break}}if(a!==s.current){o(false);let u=setTimeout(()=>{r(a),s.current=a,o(true);},200);return ()=>clearTimeout(u)}},[e]),bo.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Ls({children:e}){let[t,r]=wr.useState(null);return wr.useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?ko.createPortal(e,t):null}function Yt({state:e,fork:t,events:r,error:n,slotId:o,targetId:s,targetLabel:i,historyMode:a="slot",onSubmit:u,onUndo:b,onClose:m,baseUrl:d,apiKey:w,userId:I,userHash:f,appId:g,embedded:x=false,completeVariant:H="bubble"}){let[y,v]=wr.useState(""),[M,U]=wr.useState([]),[N,D]=wr.useState(false),[R,T]=wr.useState(false),[O,S]=wr.useState(false),[c,F]=wr.useState(false),[C,$]=wr.useState(false),[A,k]=wr.useState(false),[E,G]=wr.useState(false),[V,q]=wr.useState(false),[te,X]=wr.useState(false),[j,ne]=wr.useState(null),[_e,z]=wr.useState(false),[ee,ve]=wr.useState([]),[ie,Me]=wr.useState(null),[ze,nt]=wr.useState(false),[Pe,We]=wr.useState(false),[Je,Ct]=wr.useState(false),[or,$t]=wr.useState(null),[ge,Ve]=wr.useState(null),[sr,Pt]=wr.useState(false),[Se,me]=wr.useState(false),[Te,Fe]=wr.useState(""),ct=wr.useRef(null),[ot,Le]=wr.useState(null),[ir,qe]=wr.useState(false),[h,p]=wr.useState(null),[L,Q]=wr.useState([]),[K,W]=wr.useState(null),[re,se]=wr.useState(false),ce=wr.useRef(false),ue=wr.useRef(null),de=wr.useRef(null),{resetAllForks:fe,previewSession:J,currentContainerId:xe,forksPaused:le,setForksPaused:Ae}=ye(),we=J?.container_id??xe,Ie=!!(J&&ir),ut=!J&&!!xe,[Tt,Mt]=wr.useState(false),$e=h!==null,Jr=wr.useRef(m);wr.useEffect(()=>{Jr.current=m;});let ar=wr.useRef(null),Lt=wr.useRef(false),Vr=typeof window<"u"&&"documentPictureInPicture"in window,co=async()=>{if(!(!Vr||$e))try{let l=await window.documentPictureInPicture.requestWindow({width:Pn,height:640});l.document.body.style.margin="0",l.document.body.style.padding="0",l.document.body.style.height="100vh",l.document.body.style.overflow="hidden",l.document.body.style.background="#ffffff";try{let _=document.adoptedStyleSheets??[];_.length>0&&(l.document.adoptedStyleSheets=[..._]);}catch{}l.addEventListener("pagehide",()=>{ar.current=null,p(null),Lt.current||Jr.current(),Lt.current=!1;},{once:!0}),ar.current=l,p(l);}catch(l){console.warn("[Fork] PiP open failed:",l);}},uo=()=>{h&&(Lt.current=true,h.close());};wr.useEffect(()=>()=>{Lt.current=true,ar.current?.close();},[]);let st=s??o??"",fo=(i||st).replace(/[-_]+/g," ").replace(/\b\w/g,l=>l.toUpperCase()),Ht=wr.useRef(""),qr=()=>{let l={Authorization:`Bearer ${w}`,...oe()};return g&&(l["X-Fork-App-Id"]=g),!J&&I&&(l["X-Fork-User-Id"]=I),!J&&f&&(l["X-Fork-User-Hash"]=f),l},it=x?true:R&&!O,po=r.find(l=>{let _=l.data;return l.type==="status"&&_.summary})?.data?.summary||t?.summary||Cs,Xe=r.find(l=>{let _=l.data;return (l.type==="status"||l.type==="complete")&&typeof _?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;wr.useEffect(()=>{if(a==="none"){D(true);return}if(!d||!w)return;if(!K){U([]),D(true);return}let l=new AbortController;return fetch(`${d}/api/v1/forks/${encodeURIComponent(K)}/messages`,{headers:qr(),signal:l.signal}).then(_=>_.ok?_.json():[]).then(_=>{if(l.signal.aborted)return;let B=[];for(let he of _){let He=he.forkId??K;he.role==="user"?B.push({type:"user",text:he.content,forkId:He}):B.push({type:"applied",text:he.content,forkId:He});}U(B),D(true);}).catch(()=>{l.signal.aborted||D(true);}),()=>{l.abort();}},[w,g,d,a,K,J?.fork_id,J?.preview_session_id,f,I,t?.id,t?.completedAt]),wr.useEffect(()=>{if(a==="none"||!d||!w||!ze)return;if(!ie){Q([]);return}let l=new AbortController,_=new URLSearchParams({container_id:ie});return fetch(`${d}/api/v1/forks?${_.toString()}`,{headers:qr(),signal:l.signal}).then(B=>B.ok?B.json():{forks:[]}).then(B=>{l.signal.aborted||Q(B.forks??[]);}).catch(()=>{}),()=>{l.abort();}},[w,g,d,a,ie,ze,t?.id,t?.completedAt,J?.fork_id,J?.preview_session_id,f,I]),wr.useEffect(()=>{e==="complete"&&q(false);},[e]);let Xr=L.some(l=>l.status==="pending"||l.status==="running"||l.status==="building");wr.useEffect(()=>{if(!Xr||!d||!w||!ie)return;let l=new URLSearchParams({container_id:ie}),_={Authorization:`Bearer ${w}`,...oe()};g&&(_["X-Fork-App-Id"]=g);let he=setInterval(async()=>{try{let He=await fetch(`${d}/api/v1/forks?${l.toString()}`,{headers:_});if(!He.ok)return;let ho=await He.json();Q(ho.forks??[]);}catch{}},3e3);return ()=>clearInterval(he)},[Xr,d,w,g,ie]),wr.useEffect(()=>{if(x&&a==="none"){ve([]),Me(null),nt(true),qe(false);return}if(J){let l=false;return nt(false),qe(false),Le(null),fetch(`${d}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${w}`,...oe()}}).then(_=>{if(!_.ok)throw new Error(`${_.status}`);return _.json()}).then(_=>{l||(ve(_.containers),Me(_.currentContainerId??J.container_id??null),qe(true));}).catch(_=>{l||(qe(false),Le(_ instanceof Error?_.message:String(_)),we?(ve([{id:we,name:J.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),Me(we)):(ve([]),Me(null)));}).finally(()=>{l||nt(true);}),()=>{l=true;}}we?(ve([{id:we,name:"Primary container",createdAt:""}]),Me(we)):(ve([]),Me(null)),nt(true),qe(false);},[w,we,d,x,a,J?.container_id,J?.container_name,J?.preview_session_id]);let Ot=wr.useRef(void 0);wr.useEffect(()=>{if(ze){if(Ot.current===void 0){Ot.current=ie;return}Ot.current!==ie&&(Ot.current=ie,U([]),D(false));}},[ie,ze]);let Bt=wr.useRef(null);wr.useEffect(()=>{if(!Pe)return;let l=B=>{if(!Bt.current)return;let he=typeof B.composedPath=="function"?B.composedPath():[];Bt.current.contains(B.target)||he.includes(Bt.current)||We(false);},_=B=>{B.key==="Escape"&&We(false);};return document.addEventListener("mousedown",l,true),document.addEventListener("keydown",_,true),()=>{document.removeEventListener("mousedown",l,true),document.removeEventListener("keydown",_,true);}},[Pe]),wr.useEffect(()=>{if(x||!it||O||$e)return;let l=_=>{(typeof _.composedPath=="function"?_.composedPath():[]).some(He=>He instanceof Element&&He.hasAttribute("data-fork-panel-host"))||(S(true),T(false),setTimeout(()=>m(),vt));};return document.addEventListener("mousedown",l,true),()=>{document.removeEventListener("mousedown",l,true);}},[x,it,O,$e,m]),wr.useEffect(()=>{Pe||(me(false),Fe(""));},[Pe]),wr.useEffect(()=>{Se&&(ct.current?.focus(),ct.current?.select());},[Se]),wr.useEffect(()=>{if(x)return;let l=requestAnimationFrame(()=>T(true));return ()=>cancelAnimationFrame(l)},[x]),wr.useEffect(()=>{let l=x||$e;if((l||it)&&(e==="prompting"||e==="complete")){let _=setTimeout(()=>ue.current?.focus(),l?100:vt+100);return ()=>clearTimeout(_)}},[it,x,$e,e]),wr.useEffect(()=>{if(e==="complete"&&Ht.current){let _=r.find(B=>B.type==="complete")?.data?.summary||t?.summary||$s;U(B=>B[B.length-1]?.type==="applied"?B:[...B,{type:"applied",text:_}]),v(""),setTimeout(()=>ue.current?.focus(),200);}},[e,fo,r,t?.summary]),wr.useEffect(()=>{de.current&&(de.current.scrollTop=de.current.scrollHeight);},[M,e]);let Gr=()=>{if(y.trim()){Ht.current=y.trim();let l={},_=re||!K;_?(l.forceNew=true,ce.current=true,re||se(true)):l.forkId=K,_||U(B=>[...B,{type:"user",text:y.trim(),forkId:K}]),u(y.trim(),st,ie,l),v("");}};wr.useEffect(()=>{if(ce.current){if(e==="error"){ce.current=false;return}t?.id&&(W(t.id),se(false),ce.current=false);}},[t?.id,e]),wr.useEffect(()=>{t?.id&&(ce.current||e!=="running"&&e!=="complete"||(W(l=>l??t.id),se(false)));},[t?.id,e]);let Yr=l=>{Ye(l.session.containerId,l.session.containerName),Me(l.session.containerId),ve(_=>{let B=_.filter(he=>he.id!==l.container.id);return [{...l.container,isPrimary:true,hasAccess:true},...B.map(he=>({...he,isPrimary:false}))]}),W(null),se(false),ce.current=false,U([]),D(false),Ht.current="";},go=async l=>{if(!(!J||!Ie||ge)){Ve(l),Le(null);try{let _=await fetch(`${d}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers/${encodeURIComponent(l)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${w}`,...oe()}});if(!_.ok){let B=await _.json().catch(()=>({}));throw new Error(B.error||`API error: ${_.status}`)}Yr(await _.json()),We(!1);}catch(_){Le(_ instanceof Error?_.message:String(_));}finally{Ve(null);}}},Qr=async l=>{if(!J||!Ie||ge)return;let _=l.trim();if(_){Ve("__new__"),Le(null);try{let B=await fetch(`${d}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,...oe()},body:JSON.stringify({name:_})});if(!B.ok){let he=await B.json().catch(()=>({}));throw new Error(he.error||`API error: ${B.status}`)}Yr(await B.json()),me(!1),Fe(""),We(!1);}catch(B){Le(B instanceof Error?B.message:String(B));}finally{Ve(null);}}},Zr=async()=>{if(!(!b||te||!st)){X(true);try{let l=await b(st);U(_=>{let B=[..._];return B.length>=2&&B[B.length-1]?.type==="applied"?B.splice(-2,2):B.length>=1&&B[B.length-1]?.type==="applied"&&B.splice(-1,1),B}),l?.removed&&U([]);}catch{}finally{X(false);}}},en=()=>{if(x){m();return}if($e){h?.close();return}S(true),T(false),setTimeout(()=>m(),vt);},mo=x||$e?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:Pn,maxWidth:"100vw",background:"#ffffff",boxShadow:it?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:it?"translateX(0)":"translateX(100%)",transition:`transform ${vt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${vt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},tn=ee.find(l=>l.id===ie)?.name??(ze?"Fork":"Loading..."),dt=re?[]:K?M.filter(l=>l.forkId===K||l.forkId==null):M,lr=bo.jsxs(bo.Fragment,{children:[bo.jsx("style",{children:`
|
|
38
38
|
@keyframes __fork-pulse {
|
|
39
39
|
0%, 100% { opacity: 1; }
|
|
40
40
|
50% { opacity: 0.5; }
|
|
@@ -56,9 +56,9 @@
|
|
|
56
56
|
scrollbar-width: thin;
|
|
57
57
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
58
58
|
}
|
|
59
|
-
`}),go.jsxs("div",{className:"__fork-panel",style:co,children:[go.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:[go.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[go.jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!G&&confirm("Kill all forks in this container?")){we(true);try{let R=await Fe();`${R?.deleted??0}`,ue([]),le(null),oe(!1),v("");}catch(R){console.error("[Fork] Reset failed:",R);}finally{we(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:go.jsx(zt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?go.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ao}):ve.length===0&&!rt?go.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):rt?go.jsxs("div",{ref:Lt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[go.jsxs("button",{type:"button",onClick:()=>{Je(l=>!l);},onMouseEnter:()=>at(true),onMouseLeave:()=>at(false),"aria-haspopup":"menu","aria-expanded":$e,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:tr||$e?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[go.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Xr}),go.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:$e?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),$e&&go.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:[ve.map(l=>{let R=l.id===ye,U=Et===l.id,me=re===l.id;return go.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Ct(l.id),onMouseLeave:()=>Ct(null),onClick:()=>{l.id!==ye&&lo(l.id);},disabled:!!re,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:U?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",fontWeight:R?600:400,opacity:re&&!me?.55:1},children:[go.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:R&&go.jsx(lucideReact.Check,{style:{width:12,height:12}})}),go.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:me?"Switching...":l.name})]},l.id)}),go.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),lt?go.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[go.jsx("input",{ref:ct,type:"text",value:Le,placeholder:"Container name",disabled:re==="__new__",onChange:l=>Ve(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),Jr(Le)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),Be(false),Ve(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus: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";}}),go.jsx("button",{type:"button",onClick:()=>{Jr(Le);},disabled:!Le.trim()||re==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Le.trim()||re==="__new__"?"#e5e7eb":"#1c4587",color:!Le.trim()||re==="__new__"?"#9ca3af":"#ffffff",cursor:!Le.trim()||re==="__new__"?"default":"pointer",flexShrink:0},children:re==="__new__"?go.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):go.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):go.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pe(true),onMouseLeave:()=>Pe(false),onClick:()=>{re||(m(null),Ve(""),Be(true));},disabled:!!re,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:$t?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",opacity:re&&re!=="__new__"?.55:1},children:"+ New container"}),b&&go.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:b})]})]}):go.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Xr}),e==="running"&&go.jsx("span",{title:qe?`Estimated ~${qe} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:qe?"#1c4587":"#9ca3af",backgroundColor:qe?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:qe?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:qe?`~${qe}m`:"~ m"})]}),!I&&go.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Dr&&go.jsx("button",{onClick:xe?so:oo,onMouseEnter:()=>C(true),onMouseLeave:()=>C(false),title:xe?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:P?"#4b5563":"#9ca3af",backgroundColor:P?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:xe?go.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):go.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),go.jsx("button",{onClick:qr,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:go.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),go.jsxs("div",{ref:fe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(Z||ce)&&go.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[go.jsx("button",{onClick:()=>{le(null),oe(false),se.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let R=(Z?ne.find(U=>U.id===Z)?.targetId:null)??nt;return R?go.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 ",go.jsx("span",{style:{color:"#6b7280"},children:R})]}):null})()]}),!Z&&!ce&&go.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[go.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:go.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),ne.length===0&&go.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),ne.length>0&&go.jsx("div",{style:{display:"flex",flexDirection:"column"},children:ne.map(l=>{let R=l.summary||"Untitled fork";return go.jsxs("button",{onClick:()=>{oe(false),le(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:U=>U.currentTarget.style.background="#fafafa",onMouseLeave:U=>U.currentTarget.style.background="#ffffff",children:[go.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[go.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:R}),go.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:_s(l.updatedAt)})]}),go.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[go.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),go.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),go.jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?go.jsxs(go.Fragment,{children:[go.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),go.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},l.id)})})]}),Z&&ut.length>0&&go.jsx("div",{style:{padding:"16px 16px 0 16px"},children:ut.map((l,R)=>go.jsx("div",{style:{marginBottom:R<ut.length-1?10:0},children:l.type==="user"?go.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[go.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:go.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),go.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})]}):M==="item"&&R===ut.length-1?go.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[go.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:go.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),go.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[go.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),go.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),k&&e!=="running"&&go.jsx("button",{onClick:U=>{U.stopPropagation(),Vr();},disabled:j,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:j?"default":"pointer",opacity:j?.4:1,height:28,flexShrink:0},children:"Undo"})]}):go.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[go.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:go.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),go.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:[go.jsx("span",{style:{flex:1},children:l.text}),k&&R===ut.length-1&&e!=="running"&&go.jsxs("button",{onClick:U=>{U.stopPropagation(),Vr();},onMouseEnter:()=>K(R),onMouseLeave:()=>K(null),disabled:j,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:de===R?"rgba(0,0,0,0.06)":"transparent",color:de===R?"#6b7280":"#d1d5db",cursor:j?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:j?.4:1,flexShrink:0},children:[go.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),de===R&&go.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"&&(Z||ce)&&go.jsx("div",{style:{padding:16},children:go.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:[go.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[go.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[go.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:go.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),go.jsx(Es,{events:r})]}),go.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:go.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),go.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:go.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:go.jsx(Sn,{events:r})})})]})}),e==="error"&&(Z||ce)&&go.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[go.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:go.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),go.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),go.jsxs("button",{onClick:()=>{let l=t?.prompt||Tt.current;l&&u(l,nt);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:_?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[go.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&go.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:go.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:[go.jsx("textarea",{ref:Se,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(),zr()),l.key==="Escape"&&!I&&qr();},placeholder:Z?"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"}}),go.jsx("button",{onClick:zr,disabled:!h.trim(),onMouseEnter:()=>y(true),onMouseLeave:()=>y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:h.trim()?1:.25,transform:x&&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:go.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return I?nr:xe&&J?po.createPortal(nr,J.document.body):go.jsx(Cs,{children:nr})}function En(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 xr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:k,recordForkActivityEvent:g}=he(),[d,w]=mr.useState("idle"),[A,f]=mr.useState(null),[p,I]=mr.useState([]),[M,h]=mr.useState(null),v=mr.useRef(null),T=mr.useCallback(()=>{w("prompting"),I([]),h(null),f(null);},[]),N=mr.useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]);mr.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=mr.useCallback(async(L,B,S)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),I([]),h(null),f(null);let c;if(i){let C=S?.forkId??i.fork_id??void 0,x=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...te()},body:JSON.stringify({prompt:L,...e?{boundary_id:e}:{},...C&&!S?.forceNew?{fork_id:C}:{},...S?.forceNew?{force_new:!0}:{}})});if(!x.ok){let z=await x.json().catch(()=>({}));throw new Error(z.error||`API error: ${x.status}`)}let y=await x.json();y.container_id&&Ge(y.container_id,y.container_name),dt(y.fork_id),c=await(await fetch(`${o}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...te()}})).json();}else if(S?.forkId){let C={prompt:L};r&&(C.userId=r),n&&(C.userHash=n);let x=await fetch(`${o}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(C)});if(!x.ok){let y=await x.json().catch(()=>({}));throw new Error(y.error||`API error: ${x.status}`)}c=await x.json();}else {let C={userId:r,prompt:L,boundaryId:e,appId:s};B&&(C.containerId=B),n&&(C.userHash=n),S?.forceNew&&(C.force_new=!0);let x=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(C)});if(!x.ok){let y=await x.json().catch(()=>({}));throw new Error(y.error||`API error: ${x.status}`)}c=await x.json();}f(c),k(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 P=new EventSource(`${o}/api/v1/forks/${c.id}/events?${F.toString()}`);v.current=P,P.onmessage=C=>{try{let x=JSON.parse(C.data);if(g(c.id,x),I(y=>[...y,x]),x.type==="complete"){let y=x.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let _={...c,status:"complete",moduleUrl:y.moduleUrl,cssUrls:y.cssUrls,summary:y.summary,completedAt:new Date().toISOString()};f(_),w("complete"),P.close();});}else if(x.type==="error"){let y=x.data;h(y.error||"Unknown error"),w("error"),P.close();}}catch{}},P.onerror=()=>{let C={Authorization:`Bearer ${t}`,...te()};!i&&r&&(C["X-Fork-User-Id"]=r),!i&&n&&(C["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:C}).then(x=>x.json()).then(x=>{f(x),x.status==="complete"?(u(e,x.id),a().catch(()=>{}),w("complete")):x.status==="error"&&(h(x.error||"Fork generation failed"),w("error"));}).catch(()=>{h("Connection lost"),w("error");}),P.close();};}catch(c){h(c.message),w("error");}},[t,s,o,e,i,u,a,g,k,n,r]),O=mr.useCallback(async L=>{try{let B={Authorization:`Bearer ${t}`,...te()};!i&&r&&(B["X-Fork-User-Id"]=r),!i&&n&&(B["X-Fork-User-Hash"]=n);let S=await fetch(`${o}/api/v1/forks/${L}`,{headers:B});if(!S.ok)return;let c=await S.json(),F=c.boundaryId??e;if(k(c,{targetKind:"module",targetId:F}),c.status==="complete"){w("complete"),f(c),h(null),I([]);return}if(c.status==="error"){w("error"),f(c),h(c.error||"Fork generation failed"),I([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;w("running"),f(c),h(null),I([]);let P=new URLSearchParams({key:t});i?(P.set("previewSessionId",i.preview_session_id),P.set("previewForkId",c.id)):r&&P.set("userId",r),n&&P.set("userHash",n);let C=new EventSource(`${o}/api/v1/forks/${c.id}/events?${P.toString()}`);v.current&&v.current.close(),v.current=C,C.onmessage=x=>{try{let y=JSON.parse(x.data);if(g(c.id,y),I(_=>[..._,y]),y.type==="complete"){let _=y.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let z={...c,status:"complete",moduleUrl:_.moduleUrl,cssUrls:_.cssUrls,summary:_.summary,completedAt:new Date().toISOString()};f(z),w("complete"),C.close();});}else if(y.type==="error"){let _=y.data;h(_.error||"Unknown error"),w("error"),C.close();}}catch{}},C.onerror=()=>{C.close();};}catch{}},[t,o,e,i,u,g,a,k,n,r]),E=mr.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 B=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(L)});if(!B.ok){let c=await B.json().catch(()=>({}));throw new Error(c.error||`API error: ${B.status}`)}let S=await B.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:A,events:p,error:M,open:T,close:N,startFork:D,undoFork:E,adoptRunningFork:O}}var Ms=0;function Pn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:k}=xr(e),[g,d]=mr.useState(false),w=mr.useRef(null),A=mr.useRef(t),f=mr.useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),p=mr.useCallback(()=>{f(),d(true),s();},[f,s]),I=mr.useCallback(()=>{f(),d(false),i();},[f,i]),M=mr.useCallback(async h=>{f(),d(true),await k(h);},[k,f]);return mr.useEffect(()=>{let h=A.current;A.current=t,t==="complete"&&h==="running"&&g&&(f(),w.current=setTimeout(()=>{w.current=null,d(false),i();},Ms)),(t==="running"||t==="prompting")&&f();},[t,g,f,i]),mr.useEffect(()=>f,[f]),{state:t,fork:r,events:n,error:o,isOpen:g,open:p,close:I,submit:a,undo:u,adoptRunningFork:M}}function Ar(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:k}=he(),[g,d]=mr.useState("idle"),[w,A]=mr.useState(null),[f,p]=mr.useState([]),[I,M]=mr.useState(null),h=mr.useRef(null),v=mr.useCallback(()=>{d("prompting"),p([]),M(null),A(null);},[]),T=mr.useCallback(()=>{d("idle"),h.current&&(h.current.close(),h.current=null);},[]);mr.useEffect(()=>{o&&o.target.kind==="slot"&&d(E=>E==="idle"?"prompting":E);},[o?.preview_session_id,o?.target.kind]);let N=mr.useCallback(async(E,L,B,S)=>{try{d("running"),p([]),M(null),A(null);let c;if(o){let x=S?.forkId??o.fork_id??void 0,y=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...te()},body:JSON.stringify({prompt:E,...L?{slot_id:L}:{},...x&&!S?.forceNew?{fork_id:x}:{},...S?.forceNew?{force_new:!0}:{}})});if(!y.ok){let V=await y.json().catch(()=>({}));throw new Error(V.error||`API error: ${y.status}`)}let _=await y.json();_.container_id&&Ge(_.container_id,_.container_name),dt(_.fork_id),c=await(await fetch(`${n}/api/v1/forks/${_.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...te()}})).json();}else if(S?.forkId){let x={prompt:E};t&&(x.userId=t),r&&(x.userHash=r);let y=await fetch(`${n}/api/v1/forks/${encodeURIComponent(S.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!y.ok){let _=await y.json().catch(()=>({}));throw new Error(_.error||`API error: ${y.status}`)}c=await y.json();}else {let x={userId:t,prompt:E};L&&(x.slotId=L),B&&(x.containerId=B),r&&(x.userHash=r),S?.forceNew&&(x.force_new=!0);let y=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!y.ok){let _=await y.json().catch(()=>({}));throw new Error(_.error||`API error: ${y.status}`)}c=await y.json();}A(c);let F=L??c.slotId;F&&u(c,{targetKind:"slot",targetId:F});let P=new URLSearchParams({key:e});o?(P.set("previewSessionId",o.preview_session_id),P.set("previewForkId",c.id)):t&&P.set("userId",t),r&&P.set("userHash",r);let C=new EventSource(`${n}/api/v1/forks/${c.id}/events?${P.toString()}`);h.current=C,C.onmessage=x=>{try{let y=JSON.parse(x.data);if(k(c.id,y),p(_=>[..._,y]),y.type==="complete"){let _=y.data,z={...c,status:"complete",bundleUrl:_.bundleUrl,summary:_.summary,completedAt:new Date().toISOString()};A(z),d("complete"),L&&_.bundleUrl&&s(L,z),C.close();}else if(y.type==="error"){let _=y.data;M(_.error||"Unknown error"),d("error"),C.close();}}catch{}},C.onerror=()=>{let x={Authorization:`Bearer ${e}`,...te()};!o&&t&&(x["X-Fork-User-Id"]=t),!o&&r&&(x["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:x}).then(y=>y.json()).then(y=>{A(y),y.status==="complete"?(d("complete"),L&&y.bundleUrl&&s(L,y)):y.status==="error"&&(M(y.error||"Fork generation failed"),d("error"));}).catch(()=>{M("Connection lost"),d("error");}),C.close();};}catch(c){M(c.message),d("error");}},[e,n,o,k,s,u,r,t]),D=mr.useCallback(async E=>{try{let L={Authorization:`Bearer ${e}`,...te()};!o&&t&&(L["X-Fork-User-Id"]=t),!o&&r&&(L["X-Fork-User-Hash"]=r);let B=await fetch(`${n}/api/v1/forks/${E}`,{headers:L});if(!B.ok)return;let S=await B.json();if(S.slotId&&u(S,{targetKind:"slot",targetId:S.slotId}),S.status==="complete"){d("complete"),A(S),M(null),p([]);return}if(S.status==="error"){d("error"),A(S),M(S.error||"Fork generation failed"),p([]);return}if(S.status!=="pending"&&S.status!=="running"&&S.status!=="building")return;d("running"),A(S),M(null),p([]);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 P=S.slotId;F.onmessage=C=>{try{let x=JSON.parse(C.data);if(k(S.id,x),p(y=>[...y,x]),x.type==="complete"){let y=x.data,_={...S,status:"complete",bundleUrl:y.bundleUrl,summary:y.summary,completedAt:new Date().toISOString()};A(_),d("complete"),P&&y.bundleUrl&&s(P,_),F.close();}else if(x.type==="error"){let y=x.data;M(y.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{F.close();};}catch{}},[e,n,o,k,s,u,r,t]),O=mr.useCallback(async E=>{try{let L={userId:t,slotId:E};r&&(L.userHash=r);let B=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(L)});if(!B.ok){let c=await B.json().catch(()=>({}));throw new Error(c.error||`API error: ${B.status}`)}let S=await B.json();return a(E),S.removed?(i(E),A(null),d("prompting")):S.fork&&(s(E,S.fork),A(S.fork)),S}catch(L){throw M(L.message),L}},[e,t,r,n,i,s]);return {state:g,fork:w,events:f,error:I,open:v,close:T,startFork:N,undoFork:O,adoptRunningFork:D}}var Us=0;function Ln(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=Ar(),[k,g]=mr.useState(false),d=mr.useRef(null),w=mr.useRef(e),A=mr.useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),f=mr.useCallback(()=>{A(),g(true),o();},[A,o]),p=mr.useCallback(()=>{A(),g(false),s();},[A,s]),I=mr.useCallback(async M=>{A(),g(true),await u(M);},[u,A]);return mr.useEffect(()=>{let M=w.current;w.current=e,e==="complete"&&M==="running"&&k&&(A(),d.current=setTimeout(()=>{d.current=null,g(false),s();},Us)),(e==="running"||e==="prompting")&&A();},[e,k,A,s]),mr.useEffect(()=>A,[A]),{state:e,fork:t,events:r,error:n,isOpen:k,open:f,close:p,submit:i,undo:a,adoptRunningFork:I}}var Ns=new Set(["pending","running","building"]);function _r(e){let t=En(e),r=Ln(),n=Pn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:k,forkActivities:g,markForkActivitySeen:d}=he(),w=t.type==="slot"?r:n,A=t.type==="slot"?"slot":"boundary",f=t.id,p=t.title,I=t.type==="slot"?"slot":"module",M=g.find(D=>D.targetKind===I&&D.targetId===t.id&&Ns.has(D.status)),h=g.find(D=>D.targetKind===I&&D.targetId===t.id&&D.status==="complete"&&D.unread),v=mr.useCallback(()=>{d();let D=M??h;if(D){w.adoptRunningFork(D.id);return}w.open();},[w,d,M,h]),T=mr.useCallback((D,O,E,L)=>t.type==="slot"?r.submit(D,O??t.id,E,L):n.submit(D,E,L),[n,r,t]),N=mr.useCallback(D=>t.type==="slot"?r.undo(D??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:f,targetLabel:p,historyMode:A,submit:T,undo:N,buttonProps:{onClick:v,hasNotification:k.unreadCompletedCount>0,activity:k},panelProps:{state:w.state,fork:w.fork,events:w.events,error:w.error,...t.type==="slot"?{slotId:f,targetLabel:p,historyMode:A}:{targetId:f,targetLabel:p,historyMode:A},onSubmit:T,onUndo:N,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function Ft(e){let{embedded:t,completeVariant:r}=e,n=_r(e);return t?go.jsx(qt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?go.jsx(qt,{...n.panelProps,completeVariant:r}):go.jsx(wr,{...n.buttonProps})}function Bs({boundaryId:e,title:t}){return go.jsx(Ft,{boundaryId:e,title:t})}function Er(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 Hn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Cr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function On(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(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 Un(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Nn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function $r(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let g=0;g<e.length;g+=1){let{rect:d,borderRadius:w}=e[g],A=d.left-.5,f=d.top-.5,p=d.width+1,I=d.height+1,M=Math.min(w+.5,p/2,I/2),h=Nn(A,f,p,I,M),v=`__fork-glow-${g}`,T=document.createElementNS(t,"filter");T.setAttribute("id",v),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),T.appendChild(N),o.appendChild(T);let D=`__fork-mask-${g}`,O=document.createElementNS(t,"mask");O.setAttribute("id",D),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(A-200)),O.setAttribute("y",String(f-200)),O.setAttribute("width",String(p+400)),O.setAttribute("height",String(I+400));let E=document.createElementNS(t,"rect");E.setAttribute("x",String(A-200)),E.setAttribute("y",String(f-200)),E.setAttribute("width",String(p+400)),E.setAttribute("height",String(I+400)),E.setAttribute("fill","white"),O.appendChild(E);let L=document.createElementNS(t,"path");L.setAttribute("d",h),L.setAttribute("fill","black"),O.appendChild(L),o.appendChild(O);let B=document.createElementNS(t,"g");B.setAttribute("mask",`url(#${D})`),B.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),B.appendChild(S),n.appendChild(B);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=B;}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],A=d.__group;if(!A)continue;let f=w.getTotalLength(),p=d.getTotalLength();if(f<=0)continue;let I=f*.35;w.setAttribute("stroke-dasharray",`${I} ${f-I}`),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 M=p*.35;d.setAttribute("stroke-dasharray",`${M} ${p-M}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*p,offset:.06},{strokeDashoffset:-2*p,offset:.92},{strokeDashoffset:-2.25*p,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(A.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(k);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);},k=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Bn(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 k=document.createElementNS(t,"path");k.setAttribute("d",Nn(a.left,a.top,a.width,a.height,u)),k.setAttribute("fill","none"),k.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),k.setAttribute("stroke-width","1.5"),k.setAttribute("stroke-dasharray","8 4"),k.setAttribute("stroke-linecap","round"),k.setAttribute("filter","url(#__fork-removed-shadow)"),k.setAttribute("opacity","0"),n.appendChild(k),k.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 Kn(e,t){if(js(t.selector))return jn(e,t);let n=jn(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(Dn(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=Tr(e,g=>g===s);if(i)return i;let a=s.toLowerCase(),u=Tr(e,g=>g.toLowerCase()===a);if(u)return u;let k=Tr(e,g=>g.toLowerCase().includes(a));if(k)return k}}let o=Ks(t.selector);if(o&&o!==t.selector&&Dn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function Dn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function jn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Pr(t.label),o=Pr(t.textHint);return r.find(i=>{let a=Pr(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function js(e){return e.trim()==="[data-fork-new]"}function Pr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ks(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Tr(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 Mr=2147483600,zs=1600,Ws=3e4,Js=300,Ke=10;function Vs(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 qs(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+Ke+8?a="bottom":a==="bottom"&&i-t.bottom<n+Ke+8?a="top":a==="left"&&t.left<r+Ke+8?a="right":a==="right"&&s-t.right<r+Ke+8&&(a="left");let u=0,k=0;return a==="top"?(u=t.top-n-Ke,k=t.left+t.width/2-r/2):a==="bottom"?(u=t.bottom+Ke,k=t.left+t.width/2-r/2):a==="left"?(u=t.top+t.height/2-n/2,k=t.left-r-Ke):(u=t.top+t.height/2-n/2,k=t.right+Ke),k=Math.max(8,Math.min(k,s-r-8)),u=Math.max(8,Math.min(u,i-n-8)),{top:u,left:k,placement:a}}function Xs(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Mr}`,"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:${Mr-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:${Mr+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 Gs(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
59
|
+
`}),bo.jsxs("div",{className:"__fork-panel",style:mo,children:[bo.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:[bo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[bo.jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!_e&&confirm("Kill all forks in this container?")){z(true);try{let _=await fe();`${_?.deleted??0}`,Q([]),W(null),se(!1),v("");}catch(_){console.error("[Fork] Reset failed:",_);}finally{z(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:bo.jsx(Vt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?bo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:po}):ee.length===0&&!Ie?bo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ie?bo.jsxs("div",{ref:Bt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[bo.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:[bo.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),bo.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Pe&&bo.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 _=l.id===ie,B=or===l.id,he=ge===l.id;return bo.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>$t(l.id),onMouseLeave:()=>$t(null),onClick:()=>{l.id!==ie&&go(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:_?600:400,opacity:ge&&!he?.55:1},children:[bo.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:_&&bo.jsx(lucideReact.Check,{style:{width:12,height:12}})}),bo.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:he?"Switching...":l.name})]},l.id)}),bo.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Se?bo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[bo.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(),Qr(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";}}),bo.jsx("button",{type:"button",onClick:()=>{Qr(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__"?bo.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):bo.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):bo.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&&bo.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:ot})]})]}):bo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),e==="running"&&bo.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"})]}),bo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[ut&&bo.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:bo.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&&bo.jsxs(bo.Fragment,{children:[Vr&&bo.jsx("button",{onClick:$e?uo:co,onMouseEnter:()=>$(true),onMouseLeave:()=>$(false),title:$e?"Redock to sidebar":"Pop out into window",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:$e?bo.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):bo.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),bo.jsx("button",{onClick:en,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:bo.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),bo.jsxs("div",{ref:de,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(K||re)&&bo.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[bo.jsx("button",{onClick:()=>{W(null),se(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 _=(K?L.find(B=>B.id===K)?.targetId:null)??st;return _?bo.jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${_}`,children:["Forking ",bo.jsx("span",{style:{color:"#6b7280"},children:_})]}):null})()]}),!K&&!re&&bo.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[bo.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:bo.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),L.length===0&&bo.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),L.length>0&&bo.jsx("div",{style:{display:"flex",flexDirection:"column"},children:L.map(l=>{let _=l.summary||"Untitled fork";return bo.jsxs("button",{onClick:()=>{se(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:[bo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[bo.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:_}),bo.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Ps(l.updatedAt)})]}),bo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[bo.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),bo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),bo.jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?bo.jsxs(bo.Fragment,{children:[bo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),bo.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},l.id)})})]}),K&&dt.length>0&&bo.jsx("div",{style:{padding:"16px 16px 0 16px"},children:dt.map((l,_)=>bo.jsx("div",{style:{marginBottom:_<dt.length-1?10:0},children:l.type==="user"?bo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[bo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:bo.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),bo.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"&&_===dt.length-1?bo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[bo.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:bo.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),bo.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[bo.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),bo.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),b&&e!=="running"&&bo.jsx("button",{onClick:B=>{B.stopPropagation(),Zr();},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"})]}):bo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[bo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:bo.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),bo.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:[bo.jsx("span",{style:{flex:1},children:l.text}),b&&_===dt.length-1&&e!=="running"&&bo.jsxs("button",{onClick:B=>{B.stopPropagation(),Zr();},onMouseEnter:()=>ne(_),onMouseLeave:()=>ne(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:j===_?"rgba(0,0,0,0.06)":"transparent",color:j===_?"#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:[bo.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),j===_&&bo.jsx("span",{style:{position:"absolute",bottom:"calc(100% + 4px)",right:0,fontSize:10,fontWeight:500,color:"#fff",background:"#374151",borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",pointerEvents:"none",lineHeight:"16px"},children:"Undo"})]})]})]})},_))}),e==="running"&&(K||re)&&bo.jsx("div",{style:{padding:16},children:bo.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:[bo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[bo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[bo.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:bo.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),bo.jsx(Ms,{events:r})]}),bo.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:bo.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),bo.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:bo.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:bo.jsx(Rn,{events:r})})})]})}),e==="error"&&(K||re)&&bo.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[bo.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:bo.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),bo.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),bo.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:E?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[bo.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&bo.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:bo.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:[bo.jsx("textarea",{ref:ue,value:y,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(),Gr()),l.key==="Escape"&&!x&&en();},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"}}),bo.jsx("button",{onClick:Gr,disabled:!y.trim(),onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:y.trim()?1:.25,transform:A&&y.trim()?"scale(1.1)":"scale(1)",background:y.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:y.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:bo.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return x?lr:$e&&h?ko.createPortal(lr,h.document.body):bo.jsx(Ls,{children:lr})}function Mn(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function Cr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:u,trackForkActivity:b,recordForkActivityEvent:m}=ye(),[d,w]=wr.useState("idle"),[I,f]=wr.useState(null),[g,x]=wr.useState([]),[H,y]=wr.useState(null),v=wr.useRef(null),M=wr.useCallback(()=>{w("prompting"),x([]),y(null),f(null);},[]),U=wr.useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]);wr.useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&w(T=>T==="idle"?"prompting":T);},[i?.preview_session_id,i?.target.id,e]);let N=wr.useCallback(async(T,O,S)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),x([]),y(null),f(null);let c;if(i){let $=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:T,...e?{boundary_id:e}:{},...$&&!S?.forceNew?{fork_id:$}:{},...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 $={prompt:T};r&&($.userId=r),n&&($.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($)});if(!A.ok){let k=await A.json().catch(()=>({}));throw new Error(k.error||`API error: ${A.status}`)}c=await A.json();}else {let $={userId:r,prompt:T,boundaryId:e,appId:s};O&&($.containerId=O),n&&($.userHash=n),S?.forceNew&&($.force_new=!0);let A=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify($)});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 C=new EventSource(`${o}/api/v1/forks/${c.id}/events?${F.toString()}`);v.current=C,C.onmessage=$=>{try{let A=JSON.parse($.data);if(m(c.id,A),x(k=>[...k,A]),A.type==="complete"){let k=A.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let E={...c,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};f(E),w("complete"),C.close();});}else if(A.type==="error"){let k=A.data;y(k.error||"Unknown error"),w("error"),C.close();}}catch{}},C.onerror=()=>{let $={Authorization:`Bearer ${t}`,...oe()};!i&&r&&($["X-Fork-User-Id"]=r),!i&&n&&($["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:$}).then(A=>A.json()).then(A=>{f(A),A.status==="complete"?(u(e,A.id),a().catch(()=>{}),w("complete")):A.status==="error"&&(y(A.error||"Fork generation failed"),w("error"));}).catch(()=>{y("Connection lost"),w("error");}),C.close();};}catch(c){y(c.message),w("error");}},[t,s,o,e,i,u,a,m,b,n,r]),D=wr.useCallback(async T=>{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/${T}`,{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),y(null),x([]);return}if(c.status==="error"){w("error"),f(c),y(c.error||"Fork generation failed"),x([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;w("running"),f(c),y(null),x([]);let C=new URLSearchParams({key:t});i?(C.set("previewSessionId",i.preview_session_id),C.set("previewForkId",c.id)):r&&C.set("userId",r),n&&C.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${c.id}/events?${C.toString()}`);v.current&&v.current.close(),v.current=$,$.onmessage=A=>{try{let k=JSON.parse(A.data);if(m(c.id,k),x(E=>[...E,k]),k.type==="complete"){let E=k.data;u(e,c.id),a().catch(()=>{}).finally(()=>{let G={...c,status:"complete",moduleUrl:E.moduleUrl,cssUrls:E.cssUrls,summary:E.summary,completedAt:new Date().toISOString()};f(G),w("complete"),$.close();});}else if(k.type==="error"){let E=k.data;y(E.error||"Unknown error"),w("error"),$.close();}}catch{}},$.onerror=()=>{$.close();};}catch{}},[t,o,e,i,u,m,a,b,n,r]),R=wr.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let T={userId:r,boundaryId:e,appId:s};n&&(T.userHash=n);let O=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(T)});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(T){throw y(T.message),T}},[t,s,o,e,a,n,r]);return {state:d,fork:I,events:g,error:H,open:M,close:U,startFork:N,undoFork:R,adoptRunningFork:D}}var Us=0;function On(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:u,adoptRunningFork:b}=Cr(e),[m,d]=wr.useState(false),w=wr.useRef(null),I=wr.useRef(t),f=wr.useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),g=wr.useCallback(()=>{f(),d(true),s();},[f,s]),x=wr.useCallback(()=>{f(),d(false),i();},[f,i]),H=wr.useCallback(async y=>{f(),d(true),await b(y);},[b,f]);return wr.useEffect(()=>{let y=I.current;I.current=t,t==="complete"&&y==="running"&&m&&(f(),w.current=setTimeout(()=>{w.current=null,d(false),i();},Us)),(t==="running"||t==="prompting")&&f();},[t,m,f,i]),wr.useEffect(()=>f,[f]),{state:t,fork:r,events:n,error:o,isOpen:m,open:g,close:x,submit:a,undo:u,adoptRunningFork:H}}function $r(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:u,recordForkActivityEvent:b}=ye(),[m,d]=wr.useState("idle"),[w,I]=wr.useState(null),[f,g]=wr.useState([]),[x,H]=wr.useState(null),y=wr.useRef(null),v=wr.useCallback(()=>{d("prompting"),g([]),H(null),I(null);},[]),M=wr.useCallback(()=>{d("idle"),y.current&&(y.current.close(),y.current=null);},[]);wr.useEffect(()=>{o&&o.target.kind==="slot"&&d(R=>R==="idle"?"prompting":R);},[o?.preview_session_id,o?.target.kind]);let U=wr.useCallback(async(R,T,O,S)=>{try{d("running"),g([]),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:R,...T?{slot_id:T}:{},...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 E=await k.json();E.container_id&&Ye(E.container_id,E.container_name),ft(E.fork_id),c=await(await fetch(`${n}/api/v1/forks/${E.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...oe()}})).json();}else if(S?.forkId){let A={prompt:R};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 E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}c=await k.json();}else {let A={userId:t,prompt:R};T&&(A.slotId=T),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 E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}c=await k.json();}I(c);let F=T??c.slotId;F&&u(c,{targetKind:"slot",targetId:F});let C=new URLSearchParams({key:e});o?(C.set("previewSessionId",o.preview_session_id),C.set("previewForkId",c.id)):t&&C.set("userId",t),r&&C.set("userHash",r);let $=new EventSource(`${n}/api/v1/forks/${c.id}/events?${C.toString()}`);y.current=$,$.onmessage=A=>{try{let k=JSON.parse(A.data);if(b(c.id,k),g(E=>[...E,k]),k.type==="complete"){let E=k.data,G={...c,status:"complete",bundleUrl:E.bundleUrl,summary:E.summary,completedAt:new Date().toISOString()};I(G),d("complete"),T&&E.bundleUrl&&s(T,G),$.close();}else if(k.type==="error"){let E=k.data;H(E.error||"Unknown error"),d("error"),$.close();}}catch{}},$.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"),T&&k.bundleUrl&&s(T,k)):k.status==="error"&&(H(k.error||"Fork generation failed"),d("error"));}).catch(()=>{H("Connection lost"),d("error");}),$.close();};}catch(c){H(c.message),d("error");}},[e,n,o,b,s,u,r,t]),N=wr.useCallback(async R=>{try{let T={Authorization:`Bearer ${e}`,...oe()};!o&&t&&(T["X-Fork-User-Id"]=t),!o&&r&&(T["X-Fork-User-Hash"]=r);let O=await fetch(`${n}/api/v1/forks/${R}`,{headers:T});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),g([]);return}if(S.status==="error"){d("error"),I(S),H(S.error||"Fork generation failed"),g([]);return}if(S.status!=="pending"&&S.status!=="running"&&S.status!=="building")return;d("running"),I(S),H(null),g([]);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()}`);y.current&&y.current.close(),y.current=F;let C=S.slotId;F.onmessage=$=>{try{let A=JSON.parse($.data);if(b(S.id,A),g(k=>[...k,A]),A.type==="complete"){let k=A.data,E={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};I(E),d("complete"),C&&k.bundleUrl&&s(C,E),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]),D=wr.useCallback(async R=>{try{let T={userId:t,slotId:R};r&&(T.userHash=r);let O=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(T)});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(R),S.removed?(i(R),I(null),d("prompting")):S.fork&&(s(R,S.fork),I(S.fork)),S}catch(T){throw H(T.message),T}},[e,t,r,n,i,s]);return {state:m,fork:w,events:f,error:x,open:v,close:M,startFork:U,undoFork:D,adoptRunningFork:N}}var Ks=0;function Nn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:u}=$r(),[b,m]=wr.useState(false),d=wr.useRef(null),w=wr.useRef(e),I=wr.useCallback(()=>{d.current!==null&&(clearTimeout(d.current),d.current=null);},[]),f=wr.useCallback(()=>{I(),m(true),o();},[I,o]),g=wr.useCallback(()=>{I(),m(false),s();},[I,s]),x=wr.useCallback(async H=>{I(),m(true),await u(H);},[u,I]);return wr.useEffect(()=>{let H=w.current;w.current=e,e==="complete"&&H==="running"&&b&&(I(),d.current=setTimeout(()=>{d.current=null,m(false),s();},Ks)),(e==="running"||e==="prompting")&&I();},[e,b,I,s]),wr.useEffect(()=>I,[I]),{state:e,fork:t,events:r,error:n,isOpen:b,open:f,close:g,submit:i,undo:a,adoptRunningFork:x}}var zs=new Set(["pending","running","building"]);function Tr(e){let t=Mn(e),r=Nn(),n=On(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u,activitySummary:b,forkActivities:m,markForkActivitySeen:d}=ye(),w=t.type==="slot"?r:n,I=t.type==="slot"?"slot":"boundary",f=t.id,g=t.title,x=t.type==="slot"?"slot":"module",H=m.find(N=>N.targetKind===x&&N.targetId===t.id&&zs.has(N.status)),y=m.find(N=>N.targetKind===x&&N.targetId===t.id&&N.status==="complete"&&N.unread),v=wr.useCallback(()=>{d();let N=H??y;if(N){w.adoptRunningFork(N.id);return}w.open();},[w,d,H,y]),M=wr.useCallback((N,D,R,T)=>t.type==="slot"?r.submit(N,D??t.id,R,T):n.submit(N,R,T),[n,r,t]),U=wr.useCallback(N=>t.type==="slot"?r.undo(N??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:f,targetLabel:g,historyMode:I,submit:M,undo:U,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:g,historyMode:I}:{targetId:f,targetLabel:g,historyMode:I},onSubmit:M,onUndo:U,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:u}}}function xt(e){let{embedded:t,completeVariant:r}=e,n=Tr(e);return t?bo.jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?bo.jsx(Yt,{...n.panelProps,completeVariant:r}):bo.jsx(Ar,{...n.buttonProps})}function Ws({boundaryId:e,title:t}){return bo.jsx(xt,{boundaryId:e,title:t})}function Lr(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 Dn(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 Hr(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 jn(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 Kn(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 zn(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 Or(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 m=0;m<e.length;m+=1){let{rect:d,borderRadius:w}=e[m],I=d.left-.5,f=d.top-.5,g=d.width+1,x=d.height+1,H=Math.min(w+.5,g/2,x/2),y=zn(I,f,g,x,H),v=`__fork-glow-${m}`,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 U=document.createElementNS(t,"feGaussianBlur");U.setAttribute("in","SourceGraphic"),U.setAttribute("stdDeviation","8"),M.appendChild(U),o.appendChild(M);let N=`__fork-mask-${m}`,D=document.createElementNS(t,"mask");D.setAttribute("id",N),D.setAttribute("maskUnits","userSpaceOnUse"),D.setAttribute("x",String(I-200)),D.setAttribute("y",String(f-200)),D.setAttribute("width",String(g+400)),D.setAttribute("height",String(x+400));let R=document.createElementNS(t,"rect");R.setAttribute("x",String(I-200)),R.setAttribute("y",String(f-200)),R.setAttribute("width",String(g+400)),R.setAttribute("height",String(x+400)),R.setAttribute("fill","white"),D.appendChild(R);let T=document.createElementNS(t,"path");T.setAttribute("d",y),T.setAttribute("fill","black"),D.appendChild(T),o.appendChild(D);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${N})`),O.setAttribute("opacity","0");let S=document.createElementNS(t,"g");S.setAttribute("filter",`url(#${v})`);let c=document.createElementNS(t,"path");c.setAttribute("d",y),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",y),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 m=0;m<s.length;m+=2){let d=s[m],w=s[m+1],I=d.__group;if(!I)continue;let f=w.getTotalLength(),g=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=g*.35;d.setAttribute("stroke-dasharray",`${H} ${g-H}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*g,offset:.06},{strokeDashoffset:-2*g,offset:.92},{strokeDashoffset:-2.25*g,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 m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",u);},b=setTimeout(u,14500);return setTimeout(()=>{a||window.addEventListener("click",u);},500),u}function Wn(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",zn(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 qn(e,t){if(Vs(t.selector))return Vn(e,t);let n=Vn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(Jn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Ur(e,m=>m===s);if(i)return i;let a=s.toLowerCase(),u=Ur(e,m=>m.toLowerCase()===a);if(u)return u;let b=Ur(e,m=>m.toLowerCase().includes(a));if(b)return b}}let o=qs(t.selector);if(o&&o!==t.selector&&Jn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function Jn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Vn(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 Vs(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 Ur(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 Nr=2147483600,Xs=1600,Gs=3e4,Ys=300,je=10;function Qs(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 Zs(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 ei(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Nr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Nr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Nr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function ti(){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); }
|
|
63
63
|
}
|
|
64
|
-
`,document.head.appendChild(e);}function zn(e,t,r="top"){Gs();let{outline:n,glow:o,tooltip:s}=Xs(t),i=Vs(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${zs}ms ease-in-out infinite`,document.body.append(o,n,s);let a=()=>{let p=e.getBoundingClientRect();if(p.width===0&&p.height===0)return;n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,n.style.width=`${p.width}px`,n.style.height=`${p.height}px`,o.style.top=`${p.top-1}px`,o.style.left=`${p.left-1}px`,o.style.width=`${p.width+2}px`,o.style.height=`${p.height+2}px`;let I=s.getBoundingClientRect(),M=I.width||s.offsetWidth||80,h=I.height||s.offsetHeight||26,v=qs(r,p,M,h);s.style.top=`${v.top}px`,s.style.left=`${v.left}px`;};a(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(a);});let u=false,k=new ResizeObserver(a);k.observe(e);let g=()=>a(),d=()=>a();window.addEventListener("scroll",g,true),window.addEventListener("resize",d);let w=()=>{u||(u=true,clearTimeout(f),k.disconnect(),window.removeEventListener("scroll",g,true),window.removeEventListener("resize",d),window.removeEventListener("click",A,true),n.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{n.remove(),o.remove(),s.remove();},Js));},A=()=>w();setTimeout(()=>{u||window.addEventListener("click",A,{once:true,capture:true});},250);let f=setTimeout(w,Ws);return w}var Ys="fork:highlight:v1:seen";function Wn(e){return `${Ys}:${e}`}function Jn(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Qs(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var Vn=new Set;function qn(e,t,r){return `${r}::${e}:${t}`}function Lr(e,t,r){let n=qn(e,t,r);return Vn.has(n)?true:Jn(Wn(r)).has(`${e}:${t}`)}function Xn(e,t,r){let n=qn(e,t,r);Vn.add(n);let o=Wn(r),s=`${e}:${t}`,i=Jn(o);i.has(s)||(i.add(s),Qs(o,i));}var It=new Map,_t=new Map,Hr=new Map;function ei(e){for(let t of e)_t.set(t,(_t.get(t)??0)+1);}function ti(e){if(!(typeof document>"u"))for(let t of e){let r=(_t.get(t)??0)-1;if(r>0){_t.set(t,r);continue}_t.delete(t),It.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function ri(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Yn(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let r=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<n&&t.left<r}function Qn(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function ni(e){if(!e||typeof document>"u")return Promise.resolve();let t=It.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((s,i)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",u),s();},u=()=>{r.removeEventListener("load",a),r.removeEventListener("error",u),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",u,{once:true});});return It.set(e,o),o}let n=new Promise((o,s)=>{let i=document.createElement("link");i.rel="stylesheet",i.href=e,i.setAttribute("data-fork-override-href",e),i.onload=()=>o(),i.onerror=()=>{i.remove(),s(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(i);}).catch(o=>{throw It.delete(e),o});return It.set(e,n),n}var At=null;function oi(){if(At)return At;try{At=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{At=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return At}function si(e){let t=Hr.get(e);if(t)return t;let r=oi()(e).catch(n=>{throw Hr.delete(e),n});return Hr.set(e,r),r}async function ii(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>ni(s)));let o=await si(e.moduleUrl);return Qn(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Qn(n,r)}function ai(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:a,getBoundaryOverride:u,consumeBoundaryAnimation:k,highlightScope:g}=he(),[d,w]=mr.useState(null),[A,f]=mr.useState(null),p=mr.useRef(null),I=mr.useRef(null),M=mr.useRef(null),h=mr.useRef(false),v=mr.useRef(null),T=mr.useRef(null),N=mr.useRef(null),D=mr.useRef(false),O=mr.useRef(false),E=u(e.id),L=E?`override:${E.id}`:"original",B=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(mr.useEffect(()=>()=>{T.current&&(clearTimeout(T.current),T.current=null),v.current&&(v.current.remove(),v.current=null),N.current&&(N.current(),N.current=null);},[]),mr.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,B]),mr.useEffect(()=>{let S=E?.cssUrls??[];if(S.length!==0)return ei(S),()=>ti(S)},[E?.cssUrls.join("|")]),mr.useEffect(()=>{if(o&&!s&&!d||I.current===L&&d)return;let S=false;return f(null),ii(E,e.original,e.exportName).then(c=>{if(S)return;let F=E?.id?k(e.id,E.id):false;if(D.current=F,F&&p.current){let P=Er(p.current);if(P){let C=Cr(P);C.length>0&&(M.current=C,h.current=true,T.current&&(clearTimeout(T.current),T.current=null),v.current&&v.current.remove(),v.current=Hn(P));}}I.current=L,mr.startTransition(()=>{w(()=>c);});}).catch(c=>{S||f(ri(c));}),()=>{S=true;}},[k,L,o,s,i,E?.id,E?.moduleUrl,E?.integrity,E?.cssUrls.join("|"),e.exportName,e.original,d]),mr.useEffect(()=>{if(!d||!p.current)return;let S=false,c=null,F=()=>{if(S||!p.current)return false;let P=E?.highlightHint,C=E?.id,x=E?.createdAt?String(E.createdAt):"";if(!P||!C||Lr(C,x,g))return false;let y=Array.from(p.current.querySelectorAll("[data-fork-new]"));y.length,y.map(z=>z.getAttribute("data-fork-new")),P.label,P.textHint,P.selector;let _=Kn(p.current,P);return _?.tagName,_?.getAttribute("data-fork-new"),_?.getAttribute("aria-label"),_?.textContent?.trim().slice(0,60),!_||!Yn(_)?(_&&Yn(_),_?.getBoundingClientRect(),false):(Xn(C,x,g),v.current&&(v.current.remove(),v.current=null),N.current&&N.current(),N.current=zn(_,P.label,P.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(S||!p.current)return;let P=D.current,C=!O.current;O.current=true;let x=P||C,y=x?F():false;if(x&&!y&&E?.highlightHint&&E?.id&&!Lr(E.id,String(E.createdAt??""),g)){let G=[150,400,800],we=0,ve=()=>{if(S||we>=G.length)return;let _e=G[we];we+=1,c=setTimeout(()=>{if(F()){y=true;return}ve();},_e);};ve();}let _=h.current,z=!!E?.highlightHint,V=M.current;if(M.current=null,h.current=false,y||z||!_){v.current&&(v.current.remove(),v.current=null);return}let Q=Er(p.current);if(!V||!Q){v.current&&(v.current.remove(),v.current=null);return}let j=Cr(Q),q=On(V,j),de=Un(V,j),K=v.current;if(de.length>0&&K){let G=Bn(de);T.current=setTimeout(()=>{T.current=null;let we=400;K.animate([{opacity:1},{opacity:0}],{duration:we,fill:"forwards"}),G.animate([{opacity:1},{opacity:0}],{duration:we,fill:"forwards"}),setTimeout(()=>{K.remove(),G.remove(),v.current===K&&(v.current=null),q.length>0&&$r(q);},we);},3500);}else K&&(K.remove(),v.current===K&&(v.current=null)),q.length>0&&$r(q);});}),()=>{S=true,c!==null&&(clearTimeout(c),c=null);}},[d,E?.id,E?.createdAt,E?.highlightHint,g]),A)throw A;return d?go.jsx("div",{ref:p,"data-fork-boundary":e.id,style:{display:"contents"},children:go.jsx(d,{...r})}):go.jsx(go.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function ci({slotId:e,title:t,slotLabel:r}){return go.jsx(Ft,{slotId:e,title:t,slotLabel:r})}function fi(e){return e.replace(/\/+$/,"")}function pi(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Rt(e,t="value"){let r=pi(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function Ur(e){if(Array.isArray(e))return e.map(Ur);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=Ur(t[n]);return r}function ro(e){return JSON.stringify(Ur(e))}function Zn(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function eo(e){let t=await e.json().catch(()=>({}));if(!e.ok){let r=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(r)}return t}function no(e){let t=fi(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},u=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:Zn(e),body:JSON.stringify({...r,...a})});return eo(u)},o=async(s,i)=>{let a=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[k,g]of Object.entries(i))g&&a.set(k,g);let u=await fetch(`${t}/api/v1/data${s}?${a.toString()}`,{headers:Zn(e)});return eo(u)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return n("/features",s)},queryValues(s){return n("/values/query",s)},setValues(s){return n("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return n("/options",s)},ensureLlmJobs(s){return n("/llm/ensure",s)},queryLlmJobs(s){return n("/llm/jobs/query",s)}}}function er(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,previewSession:s,userHash:i,userId:a}=he(),u=e||o;return mr.useMemo(()=>{if(!r||!u)return null;let k=s?te():{};return no({apiKey:t,appId:r,baseUrl:n,containerId:u,userId:s?void 0:a,userHash:s?void 0:i,extraHeaders:k})},[t,r,n,u,s,i,a])}function gi(e){let t=er(e.containerId),[r,n]=mr.useState(null),[o,s]=mr.useState([]),[i,a]=mr.useState(false),[u,k]=mr.useState(null),g=ro({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),d=mr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){a(true);try{let f=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(f.feature),s(f.values),k(null);}catch(f){k(f instanceof Error?f:new Error(String(f)));}finally{a(false);}}},[t,g]);mr.useEffect(()=>{d();},[d]),mr.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let f=setInterval(()=>{d();},e.pollMs);return ()=>clearInterval(f)},[e.pollMs,d]);let w=mr.useMemo(()=>new Map(o.map(f=>[Rt(f.entity,f.valueKey),f])),[o]),A=mr.useCallback((f,p="value")=>w.get(Rt(f,p))??null,[w]);return {feature:r,values:o,byKey:w,getValue:A,loading:i,error:u,refresh:d}}function mi(e){let t=er(e),r=mr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=mr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=mr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(s)},[t]);return {client:t,ensureFeature:r,setValues:n,setOptions:o}}function to(e){return e.some(t=>t.status==="queued"||t.status==="running")}function hi(e){let t=er(e.containerId),[r,n]=mr.useState(null),[o,s]=mr.useState([]),[i,a]=mr.useState([]),[u,k]=mr.useState(false),[g,d]=mr.useState(null),w=mr.useRef(""),A=ro({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),f=mr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){k(true);try{let h=await t.ensureLlmJobs(e);w.current=A,n(h.feature),s(h.jobs),a(h.values),d(null);}catch(h){d(h instanceof Error?h:new Error(String(h)));}finally{k(false);}}},[t,A]),p=mr.useCallback(async()=>{if(!t)return;let h=o.map(v=>v.id);try{if(h.length>0){let v=await t.queryLlmJobs({jobIds:h});s(v.jobs);}if(e.featureId||e.featureKey){let v=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(T=>T.entity),valueKeys:Array.from(new Set(e.jobs.map(T=>T.valueKey||"value")))});n(v.feature),a(v.values);}d(null);}catch(v){d(v instanceof Error?v:new Error(String(v)));}},[t,o,A]);mr.useEffect(()=>{w.current!==A&&f();},[f,A]),mr.useEffect(()=>{let h=e.pollMs??3e3;if(h<=0||!to(o))return;let v=setInterval(()=>{p();},h);return ()=>clearInterval(v)},[e.pollMs,o,p]);let I=mr.useMemo(()=>new Map(i.map(h=>[Rt(h.entity,h.valueKey),h])),[i]),M=mr.useCallback((h,v="value")=>I.get(Rt(h,v))??null,[I]);return {feature:r,jobs:o,values:i,byKey:I,getValue:M,loading:u,error:g,ensure:f,refresh:p,running:to(o)}}exports.ForkBoundaryUI=Bs;exports.ForkButton=wr;exports.ForkChatInterface=Ft;exports.ForkPanel=qt;exports.ForkProvider=Uo;exports.ForkSlot=Yo;exports.ForkUI=ci;exports.clearCachedManifest=xo;exports.createForkDataClient=no;exports.forkEntityValueKey=Rt;exports.forkable=ai;exports.loadManifest=Bt;exports.manifestDiffers=Ao;exports.readCachedManifest=So;exports.registerForkShared=sr;exports.useBoundaryFork=xr;exports.useFork=Ar;exports.useForkChatPanel=_r;exports.useForkDataClient=er;exports.useForkDataMutation=mi;exports.useForkFeatureValues=gi;exports.useForkLlmJobs=hi;exports.usePreviewSession=Nt;exports.writeCachedManifest=Fo;
|
|
64
|
+
`,document.head.appendChild(e);}function Xn(e,t,r="top"){ti();let{outline:n,glow:o,tooltip:s}=ei(t),i=Qs(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${Xs}ms ease-in-out infinite`,document.body.append(o,n,s);let a=()=>{let g=e.getBoundingClientRect();if(g.width===0&&g.height===0)return;n.style.top=`${g.top}px`,n.style.left=`${g.left}px`,n.style.width=`${g.width}px`,n.style.height=`${g.height}px`,o.style.top=`${g.top-1}px`,o.style.left=`${g.left-1}px`,o.style.width=`${g.width+2}px`,o.style.height=`${g.height+2}px`;let x=s.getBoundingClientRect(),H=x.width||s.offsetWidth||80,y=x.height||s.offsetHeight||26,v=Zs(r,g,H,y);s.style.top=`${v.top}px`,s.style.left=`${v.left}px`;};a(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(a);});let u=false,b=new ResizeObserver(a);b.observe(e);let m=()=>a(),d=()=>a();window.addEventListener("scroll",m,true),window.addEventListener("resize",d);let w=()=>{u||(u=true,clearTimeout(f),b.disconnect(),window.removeEventListener("scroll",m,true),window.removeEventListener("resize",d),window.removeEventListener("click",I,true),n.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{n.remove(),o.remove(),s.remove();},Ys));},I=()=>w();setTimeout(()=>{u||window.addEventListener("click",I,{once:true,capture:true});},250);let f=setTimeout(w,Gs);return w}var ri="fork:highlight:v1:seen";function Gn(e){return `${ri}:${e}`}function Yn(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 ni(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var Qn=new Set;function Zn(e,t,r){return `${r}::${e}:${t}`}function Dr(e,t,r){let n=Zn(e,t,r);return Qn.has(n)?true:Yn(Gn(r)).has(`${e}:${t}`)}function eo(e,t,r){let n=Zn(e,t,r);Qn.add(n);let o=Gn(r),s=`${e}:${t}`,i=Yn(o);i.has(s)||(i.add(s),ni(o,i));}var _t=new Map,Rt=new Map,jr=new Map;function si(e){for(let t of e)Rt.set(t,(Rt.get(t)??0)+1);}function ii(e){if(!(typeof document>"u"))for(let t of e){let r=(Rt.get(t)??0)-1;if(r>0){Rt.set(t,r);continue}Rt.delete(t),_t.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function ai(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function ro(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let r=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<n&&t.left<r}function no(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function li(e){if(!e||typeof document>"u")return Promise.resolve();let t=_t.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((s,i)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",u),s();},u=()=>{r.removeEventListener("load",a),r.removeEventListener("error",u),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",u,{once:true});});return _t.set(e,o),o}let n=new Promise((o,s)=>{let i=document.createElement("link");i.rel="stylesheet",i.href=e,i.setAttribute("data-fork-override-href",e),i.onload=()=>o(),i.onerror=()=>{i.remove(),s(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(i);}).catch(o=>{throw _t.delete(e),o});return _t.set(e,n),n}var It=null;function ci(){if(It)return It;try{It=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{It=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return It}function ui(e){let t=jr.get(e);if(t)return t;let r=ci()(e).catch(n=>{throw jr.delete(e),n});return jr.set(e,r),r}async function di(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>li(s)));let o=await ui(e.moduleUrl);return no(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return no(n,r)}function fi(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:a,getBoundaryOverride:u,consumeBoundaryAnimation:b,highlightScope:m}=ye(),[d,w]=wr.useState(null),[I,f]=wr.useState(null),g=wr.useRef(null),x=wr.useRef(null),H=wr.useRef(null),y=wr.useRef(false),v=wr.useRef(null),M=wr.useRef(null),U=wr.useRef(null),N=wr.useRef(false),D=wr.useRef(false),R=u(e.id),T=R?`override:${R.id}`:"original",O=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(wr.useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),v.current&&(v.current.remove(),v.current=null),U.current&&(U.current(),U.current=null);},[]),wr.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,O]),wr.useEffect(()=>{let S=R?.cssUrls??[];if(S.length!==0)return si(S),()=>ii(S)},[R?.cssUrls.join("|")]),wr.useEffect(()=>{if(o&&!s&&!d||x.current===T&&d)return;let S=false;return f(null),di(R,e.original,e.exportName).then(c=>{if(S)return;let F=R?.id?b(e.id,R.id):false;if(N.current=F,F&&g.current){let C=Lr(g.current);if(C){let $=Hr(C);$.length>0&&(H.current=$,y.current=true,M.current&&(clearTimeout(M.current),M.current=null),v.current&&v.current.remove(),v.current=Dn(C));}}x.current=T,wr.startTransition(()=>{w(()=>c);});}).catch(c=>{S||f(ai(c));}),()=>{S=true;}},[b,T,o,s,i,R?.id,R?.moduleUrl,R?.integrity,R?.cssUrls.join("|"),e.exportName,e.original,d]),wr.useEffect(()=>{if(!d||!g.current)return;let S=false,c=null,F=()=>{if(S||!g.current)return false;let C=R?.highlightHint,$=R?.id,A=R?.createdAt?String(R.createdAt):"";if(!C||!$||Dr($,A,m))return false;let k=Array.from(g.current.querySelectorAll("[data-fork-new]"));k.length,k.map(G=>G.getAttribute("data-fork-new")),C.label,C.textHint,C.selector;let E=qn(g.current,C);return E?.tagName,E?.getAttribute("data-fork-new"),E?.getAttribute("aria-label"),E?.textContent?.trim().slice(0,60),!E||!ro(E)?(E&&ro(E),E?.getBoundingClientRect(),false):(eo($,A,m),v.current&&(v.current.remove(),v.current=null),U.current&&U.current(),U.current=Xn(E,C.label,C.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(S||!g.current)return;let C=N.current,$=!D.current;D.current=true;let A=C||$,k=A?F():false;if(A&&!k&&R?.highlightHint&&R?.id&&!Dr(R.id,String(R.createdAt??""),m)){let _e=[150,400,800],z=0,ee=()=>{if(S||z>=_e.length)return;let ve=_e[z];z+=1,c=setTimeout(()=>{if(F()){k=true;return}ee();},ve);};ee();}let E=y.current,G=!!R?.highlightHint,V=H.current;if(H.current=null,y.current=false,k||G||!E){v.current&&(v.current.remove(),v.current=null);return}let q=Lr(g.current);if(!V||!q){v.current&&(v.current.remove(),v.current=null);return}let te=Hr(q),X=jn(V,te),j=Kn(V,te),ne=v.current;if(j.length>0&&ne){let _e=Wn(j);M.current=setTimeout(()=>{M.current=null;let z=400;ne.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),_e.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{ne.remove(),_e.remove(),v.current===ne&&(v.current=null),X.length>0&&Or(X);},z);},3500);}else ne&&(ne.remove(),v.current===ne&&(v.current=null)),X.length>0&&Or(X);});}),()=>{S=true,c!==null&&(clearTimeout(c),c=null);}},[d,R?.id,R?.createdAt,R?.highlightHint,m]),I)throw I;return d?bo.jsx("div",{ref:g,"data-fork-boundary":e.id,style:{display:"contents"},children:bo.jsx(d,{...r})}):bo.jsx(bo.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function gi({slotId:e,title:t,slotLabel:r}){return bo.jsx(xt,{slotId:e,title:t,slotLabel:r})}function yi(e){return e.replace(/\/+$/,"")}function ki(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Et(e,t="value"){let r=ki(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function zr(e){if(Array.isArray(e))return e.map(zr);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=zr(t[n]);return r}function ao(e){return JSON.stringify(zr(e))}function oo(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function so(e){let t=await e.json().catch(()=>({}));if(!e.ok){let r=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(r)}return t}function lo(e){let t=yi(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},u=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:oo(e),body:JSON.stringify({...r,...a})});return so(u)},o=async(s,i)=>{let a=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[b,m]of Object.entries(i))m&&a.set(b,m);let u=await fetch(`${t}/api/v1/data${s}?${a.toString()}`,{headers:oo(e)});return so(u)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return n("/features",s)},queryValues(s){return n("/values/query",s)},setValues(s){return n("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return n("/options",s)},ensureLlmJobs(s){return n("/llm/ensure",s)},queryLlmJobs(s){return n("/llm/jobs/query",s)}}}function nr(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,previewSession:s,userHash:i,userId:a}=ye(),u=e||o;return wr.useMemo(()=>{if(!r||!u)return null;let b=s?oe():{};return lo({apiKey:t,appId:r,baseUrl:n,containerId:u,userId:s?void 0:a,userHash:s?void 0:i,extraHeaders:b})},[t,r,n,u,s,i,a])}function bi(e){let t=nr(e.containerId),[r,n]=wr.useState(null),[o,s]=wr.useState([]),[i,a]=wr.useState(false),[u,b]=wr.useState(null),m=ao({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),d=wr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){a(true);try{let f=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(f.feature),s(f.values),b(null);}catch(f){b(f instanceof Error?f:new Error(String(f)));}finally{a(false);}}},[t,m]);wr.useEffect(()=>{d();},[d]),wr.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let f=setInterval(()=>{d();},e.pollMs);return ()=>clearInterval(f)},[e.pollMs,d]);let w=wr.useMemo(()=>new Map(o.map(f=>[Et(f.entity,f.valueKey),f])),[o]),I=wr.useCallback((f,g="value")=>w.get(Et(f,g))??null,[w]);return {feature:r,values:o,byKey:w,getValue:I,loading:i,error:u,refresh:d}}function wi(e){let t=nr(e),r=wr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=wr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=wr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(s)},[t]);return {client:t,ensureFeature:r,setValues:n,setOptions:o}}function io(e){return e.some(t=>t.status==="queued"||t.status==="running")}function vi(e){let t=nr(e.containerId),[r,n]=wr.useState(null),[o,s]=wr.useState([]),[i,a]=wr.useState([]),[u,b]=wr.useState(false),[m,d]=wr.useState(null),w=wr.useRef(""),I=ao({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),f=wr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){b(true);try{let y=await t.ensureLlmJobs(e);w.current=I,n(y.feature),s(y.jobs),a(y.values),d(null);}catch(y){d(y instanceof Error?y:new Error(String(y)));}finally{b(false);}}},[t,I]),g=wr.useCallback(async()=>{if(!t)return;let y=o.map(v=>v.id);try{if(y.length>0){let v=await t.queryLlmJobs({jobIds:y});s(v.jobs);}if(e.featureId||e.featureKey){let v=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(M=>M.entity),valueKeys:Array.from(new Set(e.jobs.map(M=>M.valueKey||"value")))});n(v.feature),a(v.values);}d(null);}catch(v){d(v instanceof Error?v:new Error(String(v)));}},[t,o,I]);wr.useEffect(()=>{w.current!==I&&f();},[f,I]),wr.useEffect(()=>{let y=e.pollMs??3e3;if(y<=0||!io(o))return;let v=setInterval(()=>{g();},y);return ()=>clearInterval(v)},[e.pollMs,o,g]);let x=wr.useMemo(()=>new Map(i.map(y=>[Et(y.entity,y.valueKey),y])),[i]),H=wr.useCallback((y,v="value")=>x.get(Et(y,v))??null,[x]);return {feature:r,jobs:o,values:i,byKey:x,getValue:H,loading:u,error:m,ensure:f,refresh:g,running:io(o)}}exports.ForkBoundaryUI=Ws;exports.ForkButton=Ar;exports.ForkChatInterface=xt;exports.ForkPanel=Yt;exports.ForkProvider=Ko;exports.ForkSlot=rs;exports.ForkUI=gi;exports.clearCachedManifest=Eo;exports.createForkDataClient=lo;exports.forkEntityValueKey=Et;exports.forkable=fi;exports.loadManifest=Kt;exports.manifestDiffers=Co;exports.readCachedManifest=_o;exports.registerForkShared=ur;exports.useBoundaryFork=Cr;exports.useFork=$r;exports.useForkChatPanel=Tr;exports.useForkDataClient=nr;exports.useForkDataMutation=wi;exports.useForkFeatureValues=bi;exports.useForkLlmJobs=vi;exports.usePreviewSession=jt;exports.writeCachedManifest=Ro;
|