@fork-api/chat-sdk 0.1.147 → 0.1.151
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/README.md +1 -1
- package/dist/index.cjs +7 -6
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +7 -6
- package/package.json +1 -1
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
'use strict';var Bt=require('react'),gn=require('react-dom'),mn=require('react/jsx-runtime'),hn=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 Bt__namespace=/*#__PURE__*/_interopNamespace(Bt);var gn__namespace=/*#__PURE__*/_interopNamespace(gn);var mn__namespace=/*#__PURE__*/_interopNamespace(mn);var hn__namespace=/*#__PURE__*/_interopNamespace(hn);var be="__FORK_SHARED__";function Ct(){var t,r,n,o;let e=globalThis;return e[be]||(e[be]={}),(t=e[be]).react||(t.react=Bt__namespace),(r=e[be])["react-dom"]||(r["react-dom"]=gn__namespace),(n=e[be])["react/jsx-runtime"]||(n["react/jsx-runtime"]=mn__namespace),(o=e[be])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=hn__namespace),e[be]}function Et(e){return Object.assign(Ct(),e)}var yn="__fork_preview_session__";function nt(e){return `${yn}${e}`}var H={apiKey:null,session:null},At=new Set;function ot(){for(let e of At)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function pr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function kn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(nt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:pr(r)?(window.sessionStorage.removeItem(nt(e)),null):r}catch{return null}}function $t(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(nt(e),JSON.stringify(t)):window.sessionStorage.removeItem(nt(e));}catch{}}function Ne(e){H.apiKey!==e&&(H.apiKey=e,H.session=kn(e),ot());}function we(){return H.session?pr(H.session)?(Pt(null),null):H.session:null}function Pt(e){H.session=e,H.apiKey&&$t(H.apiKey,e),ot();}function Be(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&$t(H.apiKey,H.session),ot());}function ve(e,t){H.session&&(H.session.container_id===e&&H.session.container_name===t||(H.session={...H.session,container_id:e,container_name:t??H.session.container_name??"Fork",fork_id:null},H.apiKey&&$t(H.apiKey,H.session),ot()));}function Mt(e){return At.add(e),()=>{At.delete(e);}}var gr="__fork_preview";function mr(){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(gr);return typeof r=="string"&&r.length>0?r:null}function Tt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return yr()!==null}function hr(){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(gr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Se=null;function yr(){if(Se)return Se;let e=mr();return e?(Se=e,hr(),Se):null}async function It(e,t){Ne(e);let r=we();if(r)return Se=null,r;let n=Se??mr();if(Se=null,!n)return null;hr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Pt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function wn(){return we()}function vn(){return null}function st(){return Bt.useSyncExternalStore(Mt,wn,vn)}function G(){let e=we();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 it(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[c,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:f,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Sn="fork:manifest:v1";function Lt(e,t,r){return `${Sn}:${e}:${t}:${r}`}function xn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Lt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Fn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Lt(e,t,r),JSON.stringify(n));}catch{}}function Rn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Lt(e,t,r));}catch{}}function _n(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var wr=Bt.createContext(null);function Ue(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function An(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Ue(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Ue(e,i)):[]};return r}function kr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Ue(e,c),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function br(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:Ue(e,i),cssUrls:(o.cssUrls??[]).map(s=>Ue(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function $n(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=Bt.useState(()=>(Ne(t),Tt(t))),[g,f]=Bt.useState({}),[x,T]=Bt.useState(s?{userId:s,userHash:void 0}:null),[_,R]=Bt.useState(!!s||p),[k,m]=Bt.useState({}),[I,C]=Bt.useState(!o),[N,$]=Bt.useState(0),[L,S]=Bt.useState(null),h=Bt.useRef(new Map),d=Bt.useRef(new Map),[w,E]=Bt.useState(0),A=Bt.useRef(new Set),u=Bt.useRef(new Map),l=Bt.useRef(void 0);Ct(),Bt.useEffect(()=>{return It(t,r).then(()=>{}),()=>{}},[]);let y=st();i&&l.current!==i&&(Et(i),l.current=i),Bt.useEffect(()=>{c&&(p||(R(false),fetch(c,{credentials:"include"}).then(P=>{if(!P.ok)throw new Error(`Auth endpoint returned ${P.status}`);return P.json()}).then(P=>{if(!P.userId||typeof P.userId!="string")throw new Error("authUrl response must include userId");T({userId:P.userId,userHash:P.userHash});}).catch(P=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",P.message);}).finally(()=>{R(true);})));},[c,p]),Bt.useEffect(()=>{!c&&s&&(T({userId:s,userHash:void 0}),R(true));},[s,c]);let j=x?.userId??"",q=x?.userHash,D=y?"":j,W=y?void 0:q,Q=!!o,z=Bt.useCallback(async()=>{if(!Q){S(null),m({}),C(true),$(F=>F+1);return}if(!_){C(false);return}if(!y&&!D||!o){S(null),m({}),C(true),$(F=>F+1);return}if(C(false),!y){try{let F=await it({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});F&&(S(F.containerId),f(kr(r,F,D,o)),m(br(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),S(null),f({}),m({});}finally{$(F=>F+1),C(true);}return}if(S(y.container_id??null),y.container_id){try{let F=await it({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:y.container_id,extraHeaders:G()});F&&(f(kr(r,F,D,o)),m(br(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch preview container manifest:",F.message),f({}),m({});}finally{$(F=>F+1),C(true);}return}let P=new URLSearchParams({appId:o,userId:D});W&&P.set("userHash",W);try{let F=await fetch(`${r}/api/v1/boundaries/manifest?${P.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}});if(!F.ok)throw new Error(`${F.status}`);let O=await F.json();m(An(r,O));}catch(F){console.error("[ForkProvider] Failed to fetch module override manifest:",F.message),m({});}finally{$(F=>F+1),C(true);}},[t,o,r,_,Q,W,D,y?.preview_session_id,y?.fork_id,y?.container_id]);Bt.useEffect(()=>{if(!D||o&&(!y||y.container_id))return;let P=new URLSearchParams({userId:D});W&&P.set("userHash",W),fetch(`${r}/api/v1/forks/active?${P.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&f(F);}).catch(()=>{});},[t,o,D,W,r,y?.preview_session_id,y?.fork_id]),Bt.useEffect(()=>{z();},[z]);let se=Bt.useCallback((P,F)=>{f(O=>({...O,[P]:F}));},[]),ie=Bt.useCallback(P=>{f(F=>{let O={...F};return delete O[P],O});},[]),pe=Bt.useCallback(P=>{A.current.add(P);},[]),ee=Bt.useCallback(P=>A.current.has(P)?(A.current.delete(P),true):false,[]),kt=Bt.useCallback((P,F)=>{u.current.set(P,F);},[]),Je=Bt.useCallback((P,F)=>u.current.get(P)!==F?false:(u.current.delete(P),true),[]),Ee=Bt.useCallback(P=>{if(!o)return;let F=JSON.stringify(P);h.current.get(P.id)===F||d.current.get(P.id)?.signature===F||(d.current.set(P.id,{boundary:P,signature:F}),E(re=>re+1));},[o]);Bt.useEffect(()=>{if(!o||d.current.size===0)return;let P=setTimeout(()=>{let F=Array.from(d.current.values());F.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of F)d.current.get(O.boundary.id)?.signature===O.signature&&(d.current.delete(O.boundary.id),h.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout(P);}},[t,o,r,w]);let de=Bt.useCallback(P=>k[P],[k]),te=Bt.useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let P=new URLSearchParams({userId:D});W&&P.set("userHash",W);let F={Authorization:`Bearer ${t}`,...G()};o&&(F["X-Fork-App-Id"]=o);let O=await fetch(`${r}/api/v1/forks/all?${P.toString()}`,{method:"DELETE",headers:F});if(!O.ok){let ne=await O.json().catch(()=>({}));throw new Error(ne.error||`API error: ${O.status}`)}let re=await O.json().catch(()=>({}));f({}),m({}),C(true),$(ne=>ne+1),A.current.clear(),u.current.clear();try{for(let ne=sessionStorage.length-1;ne>=0;ne-=1){let Ae=sessionStorage.key(ne);Ae&&Ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(Ae);}}catch{}return re},[t,o,r,W,D]);return mn.jsx(wr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Q,moduleManifestReady:I,moduleManifestVersion:N,currentContainerId:L,previewSession:y,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:pe,shouldSkipAnimation:ee,queueBoundaryAnimation:kt,consumeBoundaryAnimation:Je,registerBoundary:Ee,getBoundaryOverride:de,refreshModuleManifest:z,resetAllForks:te},children:n})}function Z(){let e=Bt.useContext(wr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function at(e){return Z().forks[e]}var He=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function Ot(e,t){let r;try{r=Bt.Children.only(e);}catch{let o=Bt.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 Sr=new Set;function xr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Ln(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Nn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Rr(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 Fr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f++){let{rect:x,borderRadius:T}=e[f],_=x.left-.5,R=x.top-.5,k=x.width+1,m=x.height+1,I=Math.min(T+.5,k/2,m/2),C=Rr(_,R,k,m,I),N=`__fork-glow-${f}`,$=document.createElementNS(t,"filter");$.setAttribute("id",N),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),$.appendChild(L),o.appendChild($);let S=`__fork-mask-${f}`,h=document.createElementNS(t,"mask");h.setAttribute("id",S),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(_-200)),h.setAttribute("y",String(R-200)),h.setAttribute("width",String(k+400)),h.setAttribute("height",String(m+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(k+400)),d.setAttribute("height",String(m+400)),d.setAttribute("fill","white"),h.appendChild(d);let w=document.createElementNS(t,"path");w.setAttribute("d",C),w.setAttribute("fill","black"),h.appendChild(w),o.appendChild(h);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${S})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let x=i[f],T=i[f+1],_=x.__group,R=T.getTotalLength(),k=x.getTotalLength();if(R<=0)continue;let m=R*.35;T.setAttribute("stroke-dasharray",`${m} ${R-m}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=k*.35;x.setAttribute("stroke-dasharray",`${I} ${k-I}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*k,offset:.06},{strokeDashoffset:-2*k,offset:.92},{strokeDashoffset:-2.25*k,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function 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"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let g=c.left,f=c.top,x=c.width,T=c.height,_=Math.min(p,x/2,T/2),R=Rr(g,f,x,T,_),k=document.createElementNS(t,"path");k.setAttribute("d",R),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 On(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 Un=Bt__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return mn.jsx("div",{ref:r,style:n,children:mn.jsx(t,{...o})})},(e,t)=>e.component===t.component&&On(e.hostProps,t.hostProps)),Nt=class extends Bt__namespace.default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function _r({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Ot(t,e);let i=at(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:g}=Z(),[f,x]=Bt.useState(null),T=Bt.useRef(null),_=Bt.useRef(null),R=Bt.useRef(null),k=Bt.useRef(false),m=Bt.useRef(null),I=Bt.useRef(null),C=!!(n||o),N=Bt.useRef(null);C&&!N.current&&(N.current=new He(e));let $=Bt.useRef(o);if($.current=o,Bt.useEffect(()=>{if(C)return ()=>{N.current?.destroy(),N.current=null;}},[C,e]),C&&N.current&&n)for(let[w,E]of Object.entries(n))N.current.set(w,E);Bt.useEffect(()=>{if(!C)return;N.current||(N.current=new He(e));let w=N.current,E=Object.keys($.current||{}).map(A=>w.on(A,(...u)=>$.current?.[A]?.(...u)));return ()=>E.forEach(A=>A())},[C,e]),Bt.useEffect(()=>{if(Sr.has(e))return;Sr.add(e);let w={id:e,appId:p,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify(w)}).catch(()=>{});},[e,s,c,r,p]);let L=i?.id||null;Bt.useEffect(()=>{if(i?.bundleUrl,T.current,_.current,!i?.bundleUrl||!L){return}let w=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,A=sessionStorage.getItem(E),u=g(e),l=!u&&A!==L;if(u&&L&&sessionStorage.setItem(E,L),l&&_.current){let W=xr(_.current);R.current=W,k.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Bt__namespace.default,window.__FORK_REACT_DOM__=gn__namespace,window.__FORK_REACT_JSX__=mn__namespace;let y=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${y}`,q=document.createElement("link");q.rel="stylesheet",q.href=j,q.dataset.forkSlot=e,document.head.appendChild(q);let D=document.createElement("script");return D.src=w+"?t="+y,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(_.current&&R.current&&k.current){let Q=_.current.getBoundingClientRect(),z=_.current.cloneNode(true);z.style.position="fixed",z.style.top=`${Q.top}px`,z.style.left=`${Q.left}px`,z.style.width=`${Q.width}px`,z.style.height=`${Q.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(_.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=_.current.querySelectorAll("*"),pe=z.querySelectorAll("*");for(let ee=0;ee<ie.length;ee++)ie[ee].scrollTop!==0&&(pe[ee].scrollTop=ie[ee].scrollTop),ie[ee].scrollLeft!==0&&(pe[ee].scrollLeft=ie[ee].scrollLeft);m.current=z;}x(()=>W.default),T.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),q.remove(),I.current&&(clearTimeout(I.current),I.current=null),m.current&&(m.current.remove(),m.current=null);}},[L,s,e]),Bt.useEffect(()=>{if(!k.current||!f||!_.current){`${e}${k.current}`,_.current;return}let w=R.current;if(!w){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let E=xr(_.current),A=Ln(w,E),u=Nn(w,E),l=m.current;if(`${e}${A.length}${u.length}`,u.length>0&&l){let y=Bn(u);I.current=setTimeout(()=>{I.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),m.current=null,A.length>0&&(Fr(A));},j);},3500);}else l&&(l.remove(),m.current=null),A.length>0&&(Fr(A));R.current=null,k.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[f]);let S={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return mn.jsx("div",{ref:_,style:S,children:t});if(!f)return mn.jsx("div",{ref:_,style:S,children:t});let d=t?.props??{};return mn.jsx(Nt,{slotId:e,resetKey:L,fallback:mn.jsx("div",{ref:_,style:S,children:t}),children:mn.jsx(Un,{component:f,containerRef:_,wrapperStyle:S,hostProps:d})})}var Er=new Set;function Dn(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 Ar(e,t=new Set){return Bt.Children.forEach(e,r=>{if(!Bt.isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&Ar(n.children,t);}),t}function zn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(Ot(r,e),s==="direct")return mn.jsx(_r,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let g=at(e),{baseUrl:f,apiKey:x,appId:T}=Z(),_=Bt.useRef(null),R=Bt.useRef(false),k=Bt.useRef(null),m=Bt.useRef(i);m.current=i;let I=Bt.useRef(t);I.current=t;let C=Bt.useRef(n);C.current=n,Bt.useEffect(()=>{if(typeof process<"u")return;let S=Ar(r),h=new Set(i?Object.keys(i):[]),d=[...S].filter(w=>!h.has(w));d.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
2
|
-
`+d.map(w=>` - ${w}`).join(`
|
|
3
|
-
|
|
1
|
+
'use strict';var Bt=require('react'),bn=require('react-dom'),wn=require('react/jsx-runtime'),vn=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 Bt__namespace=/*#__PURE__*/_interopNamespace(Bt);var bn__namespace=/*#__PURE__*/_interopNamespace(bn);var wn__namespace=/*#__PURE__*/_interopNamespace(wn);var vn__namespace=/*#__PURE__*/_interopNamespace(vn);var ve="__FORK_SHARED__";function Ct(){var t,r,n,o;let e=globalThis;return e[ve]||(e[ve]={}),(t=e[ve]).react||(t.react=Bt__namespace),(r=e[ve])["react-dom"]||(r["react-dom"]=bn__namespace),(n=e[ve])["react/jsx-runtime"]||(n["react/jsx-runtime"]=wn__namespace),(o=e[ve])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=vn__namespace),e[ve]}function $t(e){return Object.assign(Ct(),e)}var Sn="__fork_preview_session__";function at(e){return `${Sn}${e}`}var B={apiKey:null,session:null},Pt=new Set;function lt(){for(let e of Pt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function yr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function xn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(at(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:yr(r)?(window.sessionStorage.removeItem(at(e)),null):r}catch{return null}}function It(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(at(e),JSON.stringify(t)):window.sessionStorage.removeItem(at(e));}catch{}}function Pe(e){B.apiKey!==e&&(B.apiKey=e,B.session=xn(e),lt());}function me(){return B.session?yr(B.session)?(ct(null),null):B.session:null}function ct(e){B.session=e,B.apiKey&&It(B.apiKey,e),lt();}function Ue(e){B.session&&B.session.fork_id!==e&&(B.session={...B.session,fork_id:e},B.apiKey&&It(B.apiKey,B.session),lt());}function Se(e,t){B.session&&(B.session.container_id===e&&B.session.container_name===t||(B.session={...B.session,container_id:e,container_name:t??B.session.container_name??"Fork",fork_id:null},B.apiKey&&It(B.apiKey,B.session),lt()));}function Tt(e){return Pt.add(e),()=>{Pt.delete(e);}}var kr="__fork_preview";function br(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(kr);return typeof r=="string"&&r.length>0?r:null}function Ot(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 vr()!==null}function wr(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(kr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var xe=null,Mt=null,Be=null;function vr(){if(xe)return xe;let e=br();return e?(xe=e,wr(),xe):null}async function Ht(e,t){Pe(e);let r=me();if(r)return xe=null,r;let n=xe??br();if(xe=null,!n)return null;wr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return ct(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function Nt(e,t,r){Pe(e);let n=me();if(n)return n;if(!r.appId||!r.userId||!r.userHash||!Number.isInteger(r.forkUserId)||r.forkUserId<=0||!Number.isInteger(r.forkOperatorExpiresAt)||r.forkOperatorExpiresAt<=0||!r.forkOperatorHash)return null;let o=[e,t,r.appId,r.userId,r.forkUserId,r.forkOperatorExpiresAt].join(`
|
|
2
|
+
`);return Be&&Mt===o||(Mt=o,Be=(async()=>{try{let i=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({appId:r.appId,userId:r.userId,userHash:r.userHash,forkUserId:r.forkUserId,forkOperatorExpiresAt:r.forkOperatorExpiresAt,forkOperatorHash:r.forkOperatorHash})});if(i.status===204)return null;if(!i.ok){let p=await i.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${i.status}): ${p.error??"unknown"}`),null}let s=await i.json(),c={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return ct(c),c}catch(i){return console.warn("[fork-preview] auto admin activate threw",i),null}finally{Mt=null,Be=null;}})()),Be}function _n(){return me()}function Rn(){return null}function dt(){return Bt.useSyncExternalStore(Tt,_n,Rn)}function K(){let e=me();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function ut(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[c,p]of Object.entries(i.modules)){let m=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:m,legacyModuleUrl:f,bundleUrl:p.bundleUrl??m,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var En="fork:manifest:v1";function Lt(e,t,r){return `${En}:${e}:${t}:${r}`}function An(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Lt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Cn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Lt(e,t,r),JSON.stringify(n));}catch{}}function $n(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Lt(e,t,r));}catch{}}function Pn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var Fr=Bt.createContext(null);function De(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Mn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:De(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>De(e,i)):[]};return r}function Sr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:De(e,c),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function xr(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:De(e,i),cssUrls:(o.cssUrls??[]).map(s=>De(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function On(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=Bt.useState(()=>(Pe(t),Ot(t))),[m,f]=Bt.useState({}),[g,I]=Bt.useState(s?{userId:s,userHash:void 0}:null),[E,R]=Bt.useState(!!s||p),[y,b]=Bt.useState({}),[M,A]=Bt.useState(!o),[H,T]=Bt.useState(0),[O,_]=Bt.useState(null),w=Bt.useRef(new Map),d=Bt.useRef(new Map),[S,C]=Bt.useState(0),$=Bt.useRef(new Set),u=Bt.useRef(new Map),l=Bt.useRef(void 0);Ct(),Bt.useEffect(()=>{return Ht(t,r).then(()=>{}),()=>{}},[]);let k=dt();Bt.useEffect(()=>{p||k||!o||!g?.userHash||!g.forkUserId||!g.forkOperatorExpiresAt||!g.forkOperatorHash||Nt(t,r,{appId:o,userId:g.userId,userHash:g.userHash,forkUserId:g.forkUserId,forkOperatorExpiresAt:g.forkOperatorExpiresAt,forkOperatorHash:g.forkOperatorHash});},[t,o,g?.forkOperatorExpiresAt,g?.forkOperatorHash,g?.forkUserId,g?.userHash,g?.userId,r,p,k?.preview_session_id]),i&&l.current!==i&&($t(i),l.current=i),Bt.useEffect(()=>{c&&(p||(R(false),fetch(c,{credentials:"include"}).then(F=>{if(!F.ok)throw new Error(`Auth endpoint returned ${F.status}`);return F.json()}).then(F=>{if(!F.userId||typeof F.userId!="string")throw new Error("authUrl response must include userId");let x=F.forkUserId??F.fork_user_id,N=typeof x=="number"?x:typeof x=="string"&&x.length>0?Number(x):void 0,ee=typeof F.forkOperatorHash=="string"?F.forkOperatorHash:typeof F.operatorHash=="string"?F.operatorHash:void 0,G=F.forkOperatorExpiresAt??F.fork_operator_expires_at??F.operatorExpiresAt,ae=typeof G=="number"?G:typeof G=="string"&&G.length>0?Number(G):void 0;I({userId:F.userId,userHash:typeof F.userHash=="string"?F.userHash:void 0,forkUserId:N&&Number.isInteger(N)&&N>0?N:void 0,forkOperatorExpiresAt:ae&&Number.isInteger(ae)&&ae>0?ae:void 0,forkOperatorHash:ee});}).catch(F=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",F.message);}).finally(()=>{R(true);})));},[c,p]),Bt.useEffect(()=>{!c&&s&&(I({userId:s,userHash:void 0}),R(true));},[s,c]);let j=g?.userId??"",Z=g?.userHash,D=k?"":j,W=k?void 0:Z,re=!!o,z=Bt.useCallback(async()=>{if(!re){_(null),b({}),A(true),T(x=>x+1);return}if(!E){A(false);return}if(!k&&!D||!o){_(null),b({}),A(true),T(x=>x+1);return}if(A(false),!k){try{let x=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});x&&(_(x.containerId),f(Sr(r,x,D,o)),b(xr(r,x)));}catch(x){console.error("[ForkProvider] Failed to fetch fork manifest:",x.message),_(null),f({}),b({});}finally{T(x=>x+1),A(true);}return}if(_(k.container_id??null),k.container_id){try{let x=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:k.container_id,extraHeaders:K()});x&&(f(Sr(r,x,D,o)),b(xr(r,x)));}catch(x){console.error("[ForkProvider] Failed to fetch preview container manifest:",x.message),f({}),b({});}finally{T(x=>x+1),A(true);}return}let F=new URLSearchParams({appId:o,userId:D});W&&F.set("userHash",W);try{let x=await fetch(`${r}/api/v1/boundaries/manifest?${F.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}});if(!x.ok)throw new Error(`${x.status}`);let N=await x.json();b(Mn(r,N));}catch(x){console.error("[ForkProvider] Failed to fetch module override manifest:",x.message),b({});}finally{T(x=>x+1),A(true);}},[t,o,r,E,re,W,D,k?.preview_session_id,k?.fork_id,k?.container_id]);Bt.useEffect(()=>{if(!D||o&&(!k||k.container_id))return;let F=new URLSearchParams({userId:D});W&&F.set("userHash",W),fetch(`${r}/api/v1/forks/active?${F.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}}).then(x=>{if(!x.ok)throw new Error(`${x.status}`);return x.json()}).then(x=>{x&&typeof x=="object"&&f(x);}).catch(()=>{});},[t,o,D,W,r,k?.preview_session_id,k?.fork_id]),Bt.useEffect(()=>{z();},[z]);let se=Bt.useCallback((F,x)=>{f(N=>({...N,[F]:x}));},[]),ie=Bt.useCallback(F=>{f(x=>{let N={...x};return delete N[F],N});},[]),pe=Bt.useCallback(F=>{$.current.add(F);},[]),ne=Bt.useCallback(F=>$.current.has(F)?($.current.delete(F),true):false,[]),xt=Bt.useCallback((F,x)=>{u.current.set(F,x);},[]),Xe=Bt.useCallback((F,x)=>u.current.get(F)!==x?false:(u.current.delete(F),true),[]),Me=Bt.useCallback(F=>{if(!o)return;let x=JSON.stringify(F);w.current.get(F.id)===x||d.current.get(F.id)?.signature===x||(d.current.set(F.id,{boundary:F,signature:x}),C(ee=>ee+1));},[o]);Bt.useEffect(()=>{if(!o||d.current.size===0)return;let F=setTimeout(()=>{let x=Array.from(d.current.values());x.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:x.map(N=>N.boundary)})}).then(N=>{if(!N.ok)throw new Error(`${N.status}`)}).then(()=>{for(let N of x)d.current.get(N.boundary.id)?.signature===N.signature&&(d.current.delete(N.boundary.id),w.current.set(N.boundary.id,N.signature));}).catch(N=>{console.error("[ForkProvider] Failed to register module boundaries:",N.message);});},50);return ()=>{clearTimeout(F);}},[t,o,r,S]);let de=Bt.useCallback(F=>y[F],[y]),Q=Bt.useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let F=new URLSearchParams({userId:D});W&&F.set("userHash",W);let x={Authorization:`Bearer ${t}`,...K()};o&&(x["X-Fork-App-Id"]=o);let N=await fetch(`${r}/api/v1/forks/all?${F.toString()}`,{method:"DELETE",headers:x});if(!N.ok){let G=await N.json().catch(()=>({}));throw new Error(G.error||`API error: ${N.status}`)}let ee=await N.json().catch(()=>({}));f({}),b({}),A(true),T(G=>G+1),$.current.clear(),u.current.clear();try{for(let G=sessionStorage.length-1;G>=0;G-=1){let ae=sessionStorage.key(G);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return ee},[t,o,r,W,D]);return wn.jsx(Fr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:m,moduleOverridesEnabled:re,moduleManifestReady:M,moduleManifestVersion:H,currentContainerId:O,previewSession:k,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:pe,shouldSkipAnimation:ne,queueBoundaryAnimation:xt,consumeBoundaryAnimation:Xe,registerBoundary:Me,getBoundaryOverride:de,refreshModuleManifest:z,resetAllForks:Q},children:n})}function te(){let e=Bt.useContext(Fr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ft(e){return te().forks[e]}var ze=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function jt(e,t){let r;try{r=Bt.Children.only(e);}catch{let o=Bt.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var Rr=new Set;function Er(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Bn(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Cr(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 Ar(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f++){let{rect:g,borderRadius:I}=e[f],E=g.left-.5,R=g.top-.5,y=g.width+1,b=g.height+1,M=Math.min(I+.5,y/2,b/2),A=Cr(E,R,y,b,M),H=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",H),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let O=document.createElementNS(t,"feGaussianBlur");O.setAttribute("in","SourceGraphic"),O.setAttribute("stdDeviation","8"),T.appendChild(O),o.appendChild(T);let _=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",_),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(E-200)),w.setAttribute("y",String(R-200)),w.setAttribute("width",String(y+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(E-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(y+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",A),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let C=document.createElementNS(t,"g");C.setAttribute("mask",`url(#${_})`),C.setAttribute("opacity","0");let $=document.createElementNS(t,"g");$.setAttribute("filter",`url(#${H})`);let u=document.createElementNS(t,"path");u.setAttribute("d",A),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),$.appendChild(u),C.appendChild($),n.appendChild(C);let l=document.createElementNS(t,"path");l.setAttribute("d",A),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=C;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let g=i[f],I=i[f+1],E=g.__group,R=I.getTotalLength(),y=g.getTotalLength();if(R<=0)continue;let b=R*.35;I.setAttribute("stroke-dasharray",`${b} ${R-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=y*.35;g.setAttribute("stroke-dasharray",`${M} ${y-M}`),g.setAttribute("stroke-dashoffset","0"),s.push(g.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(E.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(m);for(let g of s)try{g.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},m=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let m=c.left,f=c.top,g=c.width,I=c.height,E=Math.min(p,g/2,I/2),R=Cr(m,f,g,I,E),y=document.createElementNS(t,"path");y.setAttribute("d",R),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zn(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var Wn=Bt__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return wn.jsx("div",{ref:r,style:n,children:wn.jsx(t,{...o})})},(e,t)=>e.component===t.component&&zn(e.hostProps,t.hostProps)),Ut=class extends Bt__namespace.default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function $r({slotId:e,children:t,githubRepo:r,shared:n,events:o}){jt(t,e);let i=ft(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:m}=te(),[f,g]=Bt.useState(null),I=Bt.useRef(null),E=Bt.useRef(null),R=Bt.useRef(null),y=Bt.useRef(false),b=Bt.useRef(null),M=Bt.useRef(null),A=!!(n||o),H=Bt.useRef(null);A&&!H.current&&(H.current=new ze(e));let T=Bt.useRef(o);if(T.current=o,Bt.useEffect(()=>{if(A)return ()=>{H.current?.destroy(),H.current=null;}},[A,e]),A&&H.current&&n)for(let[S,C]of Object.entries(n))H.current.set(S,C);Bt.useEffect(()=>{if(!A)return;H.current||(H.current=new ze(e));let S=H.current,C=Object.keys(T.current||{}).map($=>S.on($,(...u)=>T.current?.[$]?.(...u)));return ()=>C.forEach($=>$())},[A,e]),Bt.useEffect(()=>{if(Rr.has(e))return;Rr.add(e);let S={id:e,appId:p,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify(S)}).catch(()=>{});},[e,s,c,r,p]);let O=i?.id||null;Bt.useEffect(()=>{if(i?.bundleUrl,I.current,E.current,!i?.bundleUrl||!O){return}let S=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,C=`__fork_animated_${e}`,$=sessionStorage.getItem(C),u=m(e),l=!u&&$!==O;if(u&&O&&sessionStorage.setItem(C,O),l&&E.current){let W=Er(E.current);R.current=W,y.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Bt__namespace.default,window.__FORK_REACT_DOM__=bn__namespace,window.__FORK_REACT_JSX__=wn__namespace;let k=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${k}`,Z=document.createElement("link");Z.rel="stylesheet",Z.href=j,Z.dataset.forkSlot=e,document.head.appendChild(Z);let D=document.createElement("script");return D.src=S+"?t="+k,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(E.current&&R.current&&y.current){let re=E.current.getBoundingClientRect(),z=E.current.cloneNode(true);z.style.position="fixed",z.style.top=`${re.top}px`,z.style.left=`${re.left}px`,z.style.width=`${re.width}px`,z.style.height=`${re.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(E.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=E.current.querySelectorAll("*"),pe=z.querySelectorAll("*");for(let ne=0;ne<ie.length;ne++)ie[ne].scrollTop!==0&&(pe[ne].scrollTop=ie[ne].scrollTop),ie[ne].scrollLeft!==0&&(pe[ne].scrollLeft=ie[ne].scrollLeft);b.current=z;}g(()=>W.default),I.current=O;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),Z.remove(),M.current&&(clearTimeout(M.current),M.current=null),b.current&&(b.current.remove(),b.current=null);}},[O,s,e]),Bt.useEffect(()=>{if(!y.current||!f||!E.current){`${e}${y.current}`,E.current;return}let S=R.current;if(!S){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!E.current)return;let C=Er(E.current),$=Bn(S,C),u=jn(S,C),l=b.current;if(`${e}${$.length}${u.length}`,u.length>0&&l){let k=Dn(u);M.current=setTimeout(()=>{M.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),k.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),k.remove(),b.current=null,$.length>0&&(Ar($));},j);},3500);}else l&&(l.remove(),b.current=null),$.length>0&&(Ar($));R.current=null,y.current=false,O&&(sessionStorage.setItem(`__fork_animated_${e}`,O),`${e}`);});});},[f]);let _={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return wn.jsx("div",{ref:E,style:_,children:t});if(!f)return wn.jsx("div",{ref:E,style:_,children:t});let d=t?.props??{};return wn.jsx(Ut,{slotId:e,resetKey:O,fallback:wn.jsx("div",{ref:E,style:_,children:t}),children:wn.jsx(Wn,{component:f,containerRef:E,wrapperStyle:_,hostProps:d})})}var Ir=new Set;function Jn(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function Tr(e,t=new Set){return Bt.Children.forEach(e,r=>{if(!Bt.isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&Tr(n.children,t);}),t}function qn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(jt(r,e),s==="direct")return wn.jsx($r,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let m=ft(e),{baseUrl:f,apiKey:g,appId:I}=te(),E=Bt.useRef(null),R=Bt.useRef(false),y=Bt.useRef(null),b=Bt.useRef(i);b.current=i;let M=Bt.useRef(t);M.current=t;let A=Bt.useRef(n);A.current=n,Bt.useEffect(()=>{if(typeof process<"u")return;let _=Tr(r),w=new Set(i?Object.keys(i):[]),d=[..._].filter(S=>!w.has(S));d.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
3
|
+
`+d.map(S=>` - ${S}`).join(`
|
|
4
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),Bt.useEffect(()=>{Ir.has(e)||(Ir.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?Jn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,f,g,o,I]);let H=Bt.useCallback(_=>{let w=E.current;if(w?.contentWindow&&R.current){let d=b.current?Object.keys(b.current):[];w.contentWindow.postMessage({type:"slot:props",props:_,callbackNames:d},"*"),y.current=null;}else y.current=_;},[]),T=Bt.useCallback((_,w)=>{let d=A.current;return !d||d.length===0?false:d.some(S=>{let[C,$]=S.split(" "),u=w.split("?")[0];return _.toUpperCase()===C.toUpperCase()&&u.startsWith($)})},[]);if(Bt.useEffect(()=>{if(!m?.bundleUrl)return;let _=async w=>{if(w.source===E.current?.contentWindow){if(w.data?.type==="slot:ready")R.current=true,E.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,y.current?H(y.current):H(M.current||{});else if(w.data?.type==="slot:event"){let d=w.data.event;d?.navigate&&(window.location.hash=d.navigate);}else if(w.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(w.data.text).catch(d=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,d.message);});else if(w.data?.type==="slot:callback"){let{name:d,args:S}=w.data,C=b.current?.[d];C?(C(...S||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${d}`);}else if(w.data?.type==="slot:fetch"){let{id:d,method:S,url:C,body:$}=w.data,u=E.current?.contentWindow;if(!u)return;let l=S||"GET";if(!T(l,C)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${d}: ${l} ${C} \u2014 not in allowedFetches`),u.postMessage({type:"slot:fetch-response",id:d,error:`Fetch not allowed: ${l} ${C}`},"*");return}try{let k={method:l};$&&l!=="GET"&&(k.headers={"Content-Type":"application/json"},k.body=JSON.stringify($));let j=await fetch(C,k),Z=await j.json();`${e}${d}${j.status}`,u.postMessage({type:"slot:fetch-response",id:d,data:Z,status:j.status},"*");}catch(k){console.error(`[ForkSlot:${e}] fetch #${d} failed:`,k.message),u.postMessage({type:"slot:fetch-response",id:d,error:k.message},"*");}}}};return window.addEventListener("message",_),()=>{window.removeEventListener("message",_),R.current=false;}},[m?.bundleUrl,e,H,T]),Bt.useEffect(()=>{m?.bundleUrl&&R.current&&H(t||{});},[t,m?.bundleUrl,H]),!m||m.status!=="complete"||!m.bundleUrl)return `${e}${m?.status||"none"}${m?.bundleUrl||"none"}`,wn.jsx(wn.Fragment,{children:r});`${e}${m.bundleUrl}`;let O=`${f}${m.bundleUrl.replace("/bundle.js","/host")}`;return wn.jsx("iframe",{ref:E,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 gt({style:e={width:20,height:20},...t}){return wn.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[wn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),wn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),wn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),wn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),wn.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}function zt({onClick:e}){let[t,r]=Bt.useState(false),[n,o]=Bt.useState(false),i=t?48:40;return wn.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:wn.jsx(gt,{style:{width:24,height:24}})})}var oo={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},so={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},io={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},ao={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Kt(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 jr({events:e}){let t=Bt.useRef(null);return Bt.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),wn.jsxs(wn.Fragment,{children:[wn.jsx("style",{children:`
|
|
4
5
|
@keyframes __fork-spin {
|
|
5
6
|
from { transform: rotate(0deg); }
|
|
6
7
|
to { transform: rotate(360deg); }
|
|
@@ -18,7 +19,7 @@
|
|
|
18
19
|
.__fork-stream::-webkit-scrollbar-thumb:hover {
|
|
19
20
|
background: rgba(255, 255, 255, 0.3);
|
|
20
21
|
}
|
|
21
|
-
`}),mn.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&&mn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[mn.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),c=Qn[r.type]||lucideReact.Code,p=eo[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");c=to[g]||lucideReact.Wrench,p=ro[g]||"#fbbf24";}return s?c=lucideReact.Loader2:!o&&r.type==="status"&&(c=lucideReact.Check,p="#4ade80"),mn.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[mn.jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),mn.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Dt(r)})]},n)})]})]})}var Hr=35,uo="Working on Feature",fo="Built Custom Feature",jr=360,ft=350;function po(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 go(e){return e.length<=Hr?e:e.slice(0,Hr-3).trimEnd()+"..."}function mo({events:e}){let[t,r]=Bt.useState("Setting up environment..."),[n,o]=Bt.useState(true),i=Bt.useRef(t),s=Bt.useRef(false);return Bt.useEffect(()=>{if(!s.current){for(let p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let g=e[p];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){c=go(Dt(g));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[e]),mn.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 ho({children:e}){let[t,r]=Bt.useState(null);return Bt.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?gn.createPortal(e,t):null}function pt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:g,onClose:f,baseUrl:x,apiKey:T,userId:_,userHash:R,appId:k,embedded:m=false}){let[I,C]=Bt.useState(""),[N,$]=Bt.useState([]),[L,S]=Bt.useState(false),[h,d]=Bt.useState(false),[w,E]=Bt.useState(false),[A,u]=Bt.useState(false),[l,y]=Bt.useState(false),[j,q]=Bt.useState(false),[D,W]=Bt.useState(false),[Q,z]=Bt.useState(false),[se,ie]=Bt.useState(false),[pe,ee]=Bt.useState(null),[kt,Je]=Bt.useState(false),[Ee,de]=Bt.useState([]),[te,P]=Bt.useState(null),[F,O]=Bt.useState(false),[re,ne]=Bt.useState(false),[Ae,Qt]=Bt.useState(false),[tn,er]=Bt.useState(null),[J,Ve]=Bt.useState(null),[rn,tr]=Bt.useState(false),[bt,qe]=Bt.useState(false),[me,$e]=Bt.useState(""),wt=Bt.useRef(null),[rr,he]=Bt.useState(null),[nn,Pe]=Bt.useState(false),[Fe,nr]=Bt.useState(null),[vt,St]=Bt.useState([]),[Y,Me]=Bt.useState(null),[ae,Te]=Bt.useState(false),Ie=Bt.useRef(false),xt=Bt.useRef(null),Xe=Bt.useRef(null),{resetAllForks:on,previewSession:K,currentContainerId:sn}=Z(),ye=K?.container_id??sn,Ye=!!(K&&nn),ue=Fe!==null,or=Bt.useRef(f);Bt.useEffect(()=>{or.current=f;});let Ft=Bt.useRef(null),Ze=Bt.useRef(false),sr=typeof window<"u"&&"documentPictureInPicture"in window,an=async()=>{if(!(!sr||ue))try{let a=await window.documentPictureInPicture.requestWindow({width:jr,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let v=document.adoptedStyleSheets??[];v.length>0&&(a.document.adoptedStyleSheets=[...v]);}catch{}a.addEventListener("pagehide",()=>{Ft.current=null,nr(null),Ze.current||or.current(),Ze.current=!1;},{once:!0}),Ft.current=a,nr(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},ln=()=>{Fe&&(Ze.current=true,Fe.close());};Bt.useEffect(()=>()=>{Ze.current=true,Ft.current?.close();},[]);let le=i??o??"",ir=(s||le).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),Qe=Bt.useRef(""),ar=()=>{let a={Authorization:`Bearer ${T}`,...G()};return k&&(a["X-Fork-App-Id"]=k),!K&&_&&(a["X-Fork-User-Id"]=_),!K&&R&&(a["X-Fork-User-Hash"]=R),a},et=m?true:h&&!w,cn=r.find(a=>{let v=a.data;return a.type==="status"&&v.summary})?.data?.summary||t?.summary||uo,ke=r.find(a=>{let v=a.data;return (a.type==="status"||a.type==="complete")&&typeof v?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;Bt.useEffect(()=>{if(c==="none"){S(true);return}if(!x||!T)return;if(!Y){$([]),S(true);return}let a=new AbortController;return fetch(`${x}/api/v1/forks/${encodeURIComponent(Y)}/messages`,{headers:ar(),signal:a.signal}).then(v=>v.ok?v.json():[]).then(v=>{if(a.signal.aborted)return;let M=[];for(let X of v){let _t=X.forkId??Y;X.role==="user"?M.push({type:"user",text:X.content,forkId:_t}):M.push({type:"applied",text:X.content,forkId:_t});}$(M),S(true);}).catch(()=>{a.signal.aborted||S(true);}),()=>{a.abort();}},[T,k,x,c,Y,K?.fork_id,K?.preview_session_id,R,_,t?.id,t?.completedAt]),Bt.useEffect(()=>{if(c==="none"||!x||!T||!F)return;if(!te){St([]);return}let a=new AbortController,v=new URLSearchParams({container_id:te});return fetch(`${x}/api/v1/forks?${v.toString()}`,{headers:ar(),signal:a.signal}).then(M=>M.ok?M.json():{forks:[]}).then(M=>{a.signal.aborted||St(M.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[T,k,x,c,te,F,t?.id,t?.completedAt,K?.fork_id,K?.preview_session_id,R,_]),Bt.useEffect(()=>{e==="complete"&&z(false);},[e]),Bt.useEffect(()=>{if(m&&c==="none"){de([]),P(null),O(true),Pe(false);return}if(K){let a=false;return O(false),Pe(false),he(null),fetch(`${x}/api/v1/preview/${encodeURIComponent(K.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${T}`,...G()}}).then(v=>{if(!v.ok)throw new Error(`${v.status}`);return v.json()}).then(v=>{a||(de(v.containers),P(v.currentContainerId??K.container_id??null),Pe(true));}).catch(v=>{a||(Pe(false),he(v instanceof Error?v.message:String(v)),ye?(de([{id:ye,name:K.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),P(ye)):(de([]),P(null)));}).finally(()=>{a||O(true);}),()=>{a=true;}}ye?(de([{id:ye,name:"Primary container",createdAt:""}]),P(ye)):(de([]),P(null)),O(true),Pe(false);},[T,ye,x,m,c,K?.container_id,K?.container_name,K?.preview_session_id]);let tt=Bt.useRef(void 0);Bt.useEffect(()=>{if(F){if(tt.current===void 0){tt.current=te;return}tt.current!==te&&(tt.current=te,$([]),S(false));}},[te,F]);let rt=Bt.useRef(null);Bt.useEffect(()=>{if(!re)return;let a=M=>{if(!rt.current)return;let X=typeof M.composedPath=="function"?M.composedPath():[];rt.current.contains(M.target)||X.includes(rt.current)||ne(false);},v=M=>{M.key==="Escape"&&ne(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",v,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",v,true);}},[re]),Bt.useEffect(()=>{re||(qe(false),$e(""));},[re]),Bt.useEffect(()=>{bt&&(wt.current?.focus(),wt.current?.select());},[bt]),Bt.useEffect(()=>{if(m)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[m]),Bt.useEffect(()=>{let a=m||ue;if((a||et)&&(e==="prompting"||e==="complete")){let v=setTimeout(()=>xt.current?.focus(),a?100:ft+100);return ()=>clearTimeout(v)}},[et,m,ue,e]),Bt.useEffect(()=>{if(e==="complete"&&Qe.current){let v=r.find(M=>M.type==="complete")?.data?.summary||t?.summary||fo;$(M=>M[M.length-1]?.type==="applied"?M:[...M,{type:"applied",text:v}]),C(""),setTimeout(()=>xt.current?.focus(),200);}},[e,ir,r,t?.summary]),Bt.useEffect(()=>{Xe.current&&(Xe.current.scrollTop=Xe.current.scrollHeight);},[N,e]);let lr=()=>{if(I.trim()){Qe.current=I.trim();let a={};ae?(a.forceNew=true,Ie.current=true):Y&&(a.forkId=Y),ae||$(v=>[...v,{type:"user",text:I.trim(),forkId:Y}]),p(I.trim(),le,te,a),C("");}};Bt.useEffect(()=>{if(Ie.current){if(e==="error"){Ie.current=false;return}t?.id&&(Me(t.id),Te(false),Ie.current=false);}},[t?.id,e]);let cr=a=>{ve(a.session.containerId,a.session.containerName),P(a.session.containerId),de(v=>{let M=v.filter(X=>X.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...M.map(X=>({...X,isPrimary:false}))]}),$([]),S(false),Qe.current="";},dn=async a=>{if(!(!K||!Ye||J)){Ve(a),he(null);try{let v=await fetch(`${x}/api/v1/preview/${encodeURIComponent(K.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${T}`,...G()}});if(!v.ok){let M=await v.json().catch(()=>({}));throw new Error(M.error||`API error: ${v.status}`)}cr(await v.json()),ne(!1);}catch(v){he(v instanceof Error?v.message:String(v));}finally{Ve(null);}}},dr=async a=>{if(!K||!Ye||J)return;let v=a.trim();if(v){Ve("__new__"),he(null);try{let M=await fetch(`${x}/api/v1/preview/${encodeURIComponent(K.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${T}`,...G()},body:JSON.stringify({name:v})});if(!M.ok){let X=await M.json().catch(()=>({}));throw new Error(X.error||`API error: ${M.status}`)}cr(await M.json()),qe(!1),$e(""),ne(!1);}catch(M){he(M instanceof Error?M.message:String(M));}finally{Ve(null);}}},un=async()=>{if(!(!g||se||!le)){ie(true);try{let a=await g(le);$(v=>{let M=[...v];return M.length>=2&&M[M.length-1]?.type==="applied"?M.splice(-2,2):M.length>=1&&M[M.length-1]?.type==="applied"&&M.splice(-1,1),M}),a?.removed&&$([]);}catch{}finally{ie(false);}}},ur=()=>{if(m){f();return}if(ue){Fe?.close();return}E(true),d(false),setTimeout(()=>f(),ft);},fn=m||ue?{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:jr,maxWidth:"100vw",background:"#ffffff",boxShadow:et?"-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:et?"translateX(0)":"translateX(100%)",transition:`transform ${ft}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${ft}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},fr=Ee.find(a=>a.id===te)?.name??(F?"Fork":"Loading..."),Le=ae?[]:Y?N.filter(a=>a.forkId===Y||a.forkId==null):N,Rt=mn.jsxs(mn.Fragment,{children:[mn.jsx("style",{children:`
|
|
22
|
+
`}),wn.jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[wn.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),c=oo[r.type]||lucideReact.Code,p=so[r.type]||"#9ca3af";if(r.type==="tool_use"){let m=String(r.data.category||"");c=io[m]||lucideReact.Wrench,p=ao[m]||"#fbbf24";}return s?c=lucideReact.Loader2:!o&&r.type==="status"&&(c=lucideReact.Check,p="#4ade80"),wn.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[wn.jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),wn.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Kt(r)})]},n)})]})]})}var Wr=35,ho="Working on Feature",yo="Built Custom Feature",Kr=360,yt=350;function ko(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function bo(e){return e.length<=Wr?e:e.slice(0,Wr-3).trimEnd()+"..."}function wo({events:e}){let[t,r]=Bt.useState("Setting up environment..."),[n,o]=Bt.useState(true),i=Bt.useRef(t),s=Bt.useRef(false);return Bt.useEffect(()=>{if(!s.current){for(let p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let m=e[p];if(m.type==="tool_use"||m.type==="build_start"||m.type==="build_complete"){c=bo(Kt(m));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[e]),wn.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function vo({children:e}){let[t,r]=Bt.useState(null);return Bt.useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?bn.createPortal(e,t):null}function kt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:m,onClose:f,baseUrl:g,apiKey:I,userId:E,userHash:R,appId:y,embedded:b=false}){let[M,A]=Bt.useState(""),[H,T]=Bt.useState([]),[O,_]=Bt.useState(false),[w,d]=Bt.useState(false),[S,C]=Bt.useState(false),[$,u]=Bt.useState(false),[l,k]=Bt.useState(false),[j,Z]=Bt.useState(false),[D,W]=Bt.useState(false),[re,z]=Bt.useState(false),[se,ie]=Bt.useState(false),[pe,ne]=Bt.useState(null),[xt,Xe]=Bt.useState(false),[Me,de]=Bt.useState([]),[Q,F]=Bt.useState(null),[x,N]=Bt.useState(false),[ee,G]=Bt.useState(false),[ae,rr]=Bt.useState(false),[sn,nr]=Bt.useState(null),[X,Ye]=Bt.useState(null),[an,or]=Bt.useState(false),[Ft,Ze]=Bt.useState(false),[ye,Oe]=Bt.useState(""),_t=Bt.useRef(null),[sr,ke]=Bt.useState(null),[ln,He]=Bt.useState(false),[Re,ir]=Bt.useState(null),[Ne,Qe]=Bt.useState([]),[Y,Ee]=Bt.useState(null),[le,Ae]=Bt.useState(false),Ce=Bt.useRef(false),Rt=Bt.useRef(null),et=Bt.useRef(null),{resetAllForks:cn,previewSession:J,currentContainerId:dn}=te(),be=J?.container_id??dn,tt=!!(J&&ln),ue=Re!==null,ar=Bt.useRef(f);Bt.useEffect(()=>{ar.current=f;});let Et=Bt.useRef(null),rt=Bt.useRef(false),lr=typeof window<"u"&&"documentPictureInPicture"in window,un=async()=>{if(!(!lr||ue))try{let a=await window.documentPictureInPicture.requestWindow({width:Kr,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let h=document.adoptedStyleSheets??[];h.length>0&&(a.document.adoptedStyleSheets=[...h]);}catch{}a.addEventListener("pagehide",()=>{Et.current=null,ir(null),rt.current||ar.current(),rt.current=!1;},{once:!0}),Et.current=a,ir(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},fn=()=>{Re&&(rt.current=true,Re.close());};Bt.useEffect(()=>()=>{rt.current=true,Et.current?.close();},[]);let ge=i??o??"",cr=(s||ge).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),nt=Bt.useRef(""),dr=()=>{let a={Authorization:`Bearer ${I}`,...K()};return y&&(a["X-Fork-App-Id"]=y),!J&&E&&(a["X-Fork-User-Id"]=E),!J&&R&&(a["X-Fork-User-Hash"]=R),a},ot=b?true:w&&!S,pn=r.find(a=>{let h=a.data;return a.type==="status"&&h.summary})?.data?.summary||t?.summary||ho,we=r.find(a=>{let h=a.data;return (a.type==="status"||a.type==="complete")&&typeof h?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;Bt.useEffect(()=>{if(c==="none"){_(true);return}if(!g||!I)return;if(!Y){T([]),_(true);return}let a=new AbortController;return fetch(`${g}/api/v1/forks/${encodeURIComponent(Y)}/messages`,{headers:dr(),signal:a.signal}).then(h=>h.ok?h.json():[]).then(h=>{if(a.signal.aborted)return;let P=[];for(let q of h){let $e=q.forkId??Y;q.role==="user"?P.push({type:"user",text:q.content,forkId:$e}):P.push({type:"applied",text:q.content,forkId:$e});}T(P),_(true);}).catch(()=>{a.signal.aborted||_(true);}),()=>{a.abort();}},[I,y,g,c,Y,J?.fork_id,J?.preview_session_id,R,E,t?.id,t?.completedAt]),Bt.useEffect(()=>{if(c==="none"||!g||!I||!x)return;if(!Q){Qe([]);return}let a=new AbortController,h=new URLSearchParams({container_id:Q});return fetch(`${g}/api/v1/forks?${h.toString()}`,{headers:dr(),signal:a.signal}).then(P=>P.ok?P.json():{forks:[]}).then(P=>{a.signal.aborted||Qe(P.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[I,y,g,c,Q,x,t?.id,t?.completedAt,J?.fork_id,J?.preview_session_id,R,E]),Bt.useEffect(()=>{e==="complete"&&z(false);},[e]);let ur=Ne.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");Bt.useEffect(()=>{if(!ur||!g||!I||!Q)return;let a=new URLSearchParams({container_id:Q}),h={Authorization:`Bearer ${I}`,...K()};y&&(h["X-Fork-App-Id"]=y);let q=setInterval(async()=>{try{let $e=await fetch(`${g}/api/v1/forks?${a.toString()}`,{headers:h});if(!$e.ok)return;let yn=await $e.json();Qe(yn.forks??[]);}catch{}},3e3);return ()=>clearInterval(q)},[ur,g,I,y,Q]),Bt.useEffect(()=>{if(b&&c==="none"){de([]),F(null),N(true),He(false);return}if(J){let a=false;return N(false),He(false),ke(null),fetch(`${g}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${I}`,...K()}}).then(h=>{if(!h.ok)throw new Error(`${h.status}`);return h.json()}).then(h=>{a||(de(h.containers),F(h.currentContainerId??J.container_id??null),He(true));}).catch(h=>{a||(He(false),ke(h instanceof Error?h.message:String(h)),be?(de([{id:be,name:J.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),F(be)):(de([]),F(null)));}).finally(()=>{a||N(true);}),()=>{a=true;}}be?(de([{id:be,name:"Primary container",createdAt:""}]),F(be)):(de([]),F(null)),N(true),He(false);},[I,be,g,b,c,J?.container_id,J?.container_name,J?.preview_session_id]);let st=Bt.useRef(void 0);Bt.useEffect(()=>{if(x){if(st.current===void 0){st.current=Q;return}st.current!==Q&&(st.current=Q,T([]),_(false));}},[Q,x]);let it=Bt.useRef(null);Bt.useEffect(()=>{if(!ee)return;let a=P=>{if(!it.current)return;let q=typeof P.composedPath=="function"?P.composedPath():[];it.current.contains(P.target)||q.includes(it.current)||G(false);},h=P=>{P.key==="Escape"&&G(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",h,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",h,true);}},[ee]),Bt.useEffect(()=>{ee||(Ze(false),Oe(""));},[ee]),Bt.useEffect(()=>{Ft&&(_t.current?.focus(),_t.current?.select());},[Ft]),Bt.useEffect(()=>{if(b)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[b]),Bt.useEffect(()=>{let a=b||ue;if((a||ot)&&(e==="prompting"||e==="complete")){let h=setTimeout(()=>Rt.current?.focus(),a?100:yt+100);return ()=>clearTimeout(h)}},[ot,b,ue,e]),Bt.useEffect(()=>{if(e==="complete"&&nt.current){let h=r.find(P=>P.type==="complete")?.data?.summary||t?.summary||yo;T(P=>P[P.length-1]?.type==="applied"?P:[...P,{type:"applied",text:h}]),A(""),setTimeout(()=>Rt.current?.focus(),200);}},[e,cr,r,t?.summary]),Bt.useEffect(()=>{et.current&&(et.current.scrollTop=et.current.scrollHeight);},[H,e]);let fr=()=>{if(M.trim()){nt.current=M.trim();let a={};le?(a.forceNew=true,Ce.current=true):Y&&(a.forkId=Y),le||T(h=>[...h,{type:"user",text:M.trim(),forkId:Y}]),p(M.trim(),ge,Q,a),A("");}};Bt.useEffect(()=>{if(Ce.current){if(e==="error"){Ce.current=false;return}t?.id&&(Ee(t.id),Ae(false),Ce.current=false);}},[t?.id,e]);let pr=a=>{Se(a.session.containerId,a.session.containerName),F(a.session.containerId),de(h=>{let P=h.filter(q=>q.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...P.map(q=>({...q,isPrimary:false}))]}),Ee(null),Ae(false),Ce.current=false,T([]),_(false),nt.current="";},gn=async a=>{if(!(!J||!tt||X)){Ye(a),ke(null);try{let h=await fetch(`${g}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${I}`,...K()}});if(!h.ok){let P=await h.json().catch(()=>({}));throw new Error(P.error||`API error: ${h.status}`)}pr(await h.json()),G(!1);}catch(h){ke(h instanceof Error?h.message:String(h));}finally{Ye(null);}}},gr=async a=>{if(!J||!tt||X)return;let h=a.trim();if(h){Ye("__new__"),ke(null);try{let P=await fetch(`${g}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I}`,...K()},body:JSON.stringify({name:h})});if(!P.ok){let q=await P.json().catch(()=>({}));throw new Error(q.error||`API error: ${P.status}`)}pr(await P.json()),Ze(!1),Oe(""),G(!1);}catch(P){ke(P instanceof Error?P.message:String(P));}finally{Ye(null);}}},mn=async()=>{if(!(!m||se||!ge)){ie(true);try{let a=await m(ge);T(h=>{let P=[...h];return P.length>=2&&P[P.length-1]?.type==="applied"?P.splice(-2,2):P.length>=1&&P[P.length-1]?.type==="applied"&&P.splice(-1,1),P}),a?.removed&&T([]);}catch{}finally{ie(false);}}},mr=()=>{if(b){f();return}if(ue){Re?.close();return}C(true),d(false),setTimeout(()=>f(),yt);},hn=b||ue?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:Kr,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:ot?"translateX(0)":"translateX(100%)",transition:`transform ${yt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${yt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},hr=Me.find(a=>a.id===Q)?.name??(x?"Fork":"Loading..."),Le=le?[]:Y?H.filter(a=>a.forkId===Y||a.forkId==null):H,At=wn.jsxs(wn.Fragment,{children:[wn.jsx("style",{children:`
|
|
22
23
|
@keyframes __fork-pulse {
|
|
23
24
|
0%, 100% { opacity: 1; }
|
|
24
25
|
50% { opacity: 0.5; }
|
|
@@ -40,5 +41,5 @@
|
|
|
40
41
|
scrollbar-width: thin;
|
|
41
42
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
42
43
|
}
|
|
43
|
-
`}),mn.jsxs("div",{className:"__fork-panel",style:fn,children:[mn.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:[mn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[mn.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!kt&&confirm("Kill all forks in this container?")){Je(true);try{let v=await on();`${v?.deleted??0}`,St([]),Me(null),Te(!1),C("");}catch(v){console.error("[Fork] Reset failed:",v);}finally{Je(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:mn.jsx(ct,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?mn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:cn}):Ee.length===0&&!Ye?mn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ye?mn.jsxs("div",{ref:rt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[mn.jsxs("button",{type:"button",onClick:()=>{ne(a=>!a);},onMouseEnter:()=>Qt(true),onMouseLeave:()=>Qt(false),"aria-haspopup":"menu","aria-expanded":re,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Ae||re?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[mn.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:fr}),mn.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:re?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),re&&mn.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(a=>{let v=a.id===te,M=tn===a.id,X=J===a.id;return mn.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>er(a.id),onMouseLeave:()=>er(null),onClick:()=>{a.id!==te&&dn(a.id);},disabled:!!J,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:M?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:J?"default":"pointer",textAlign:"left",fontWeight:v?600:400,opacity:J&&!X?.55:1},children:[mn.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:v&&mn.jsx(lucideReact.Check,{style:{width:12,height:12}})}),mn.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:X?"Switching...":a.name})]},a.id)}),mn.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),bt?mn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[mn.jsx("input",{ref:wt,type:"text",value:me,placeholder:"Container name",disabled:J==="__new__",onChange:a=>$e(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),dr(me)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),qe(false),$e(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),mn.jsx("button",{type:"button",onClick:()=>{dr(me);},disabled:!me.trim()||J==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!me.trim()||J==="__new__"?"#e5e7eb":"#1c4587",color:!me.trim()||J==="__new__"?"#9ca3af":"#ffffff",cursor:!me.trim()||J==="__new__"?"default":"pointer",flexShrink:0},children:J==="__new__"?mn.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):mn.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):mn.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>tr(true),onMouseLeave:()=>tr(false),onClick:()=>{J||(he(null),$e(""),qe(true));},disabled:!!J,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:rn?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:J?"default":"pointer",textAlign:"left",opacity:J&&J!=="__new__"?.55:1},children:"+ New container"}),rr&&mn.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:rr})]})]}):mn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:fr}),e==="running"&&mn.jsx("span",{title:ke?`Estimated ~${ke} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ke?"#1c4587":"#9ca3af",backgroundColor:ke?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ke?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ke?`~${ke}m`:"~ m"}),e==="complete"&&mn.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!m&&mn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[sr&&mn.jsx("button",{onClick:ue?ln:an,onMouseEnter:()=>y(true),onMouseLeave:()=>y(false),title:ue?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ue?mn.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):mn.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),mn.jsx("button",{onClick:ur,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:A?"#4b5563":"#9ca3af",backgroundColor:A?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:mn.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),mn.jsxs("div",{ref:Xe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(Y||ae)&&mn.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[mn.jsx("button",{onClick:()=>{Me(null),Te(false),Ie.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"}),le&&mn.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 ${le}`,children:["Forking ",mn.jsx("span",{style:{color:"#6b7280"},children:le})]})]}),!Y&&!ae&&mn.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[mn.jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[mn.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),le&&mn.jsx("button",{onClick:()=>{Me(null),Te(true);},title:`Start a new fork on ${le}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),vt.length===0&&mn.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),vt.length>0&&mn.jsx("div",{style:{display:"flex",flexDirection:"column"},children:vt.map(a=>{let v=a.summary||"Untitled fork";return mn.jsxs("button",{onClick:()=>{Te(false),Me(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:M=>M.currentTarget.style.background="#fafafa",onMouseLeave:M=>M.currentTarget.style.background="#ffffff",children:[mn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[mn.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:v}),mn.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:po(a.updatedAt)})]}),mn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[mn.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),mn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),mn.jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?mn.jsxs(mn.Fragment,{children:[mn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),mn.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),ae&&mn.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:mn.jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),Y&&Le.length>0&&mn.jsx("div",{style:{padding:"16px 16px 0 16px"},children:Le.map((a,v)=>mn.jsx("div",{style:{marginBottom:v<Le.length-1?10:0},children:a.type==="user"?mn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[mn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:mn.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),mn.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):mn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[mn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:mn.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),mn.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:[mn.jsx("span",{style:{flex:1},children:a.text}),g&&v===Le.length-1&&e!=="running"&&mn.jsxs("button",{onClick:M=>{M.stopPropagation(),un();},onMouseEnter:()=>ee(v),onMouseLeave:()=>ee(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:pe===v?"rgba(0,0,0,0.06)":"transparent",color:pe===v?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[mn.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),pe===v&&mn.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"})]})]})]})},v))}),e==="running"&&(Y||ae)&&mn.jsx("div",{style:{padding:16},children:mn.jsxs("div",{onClick:()=>z(!Q),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[mn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[mn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[mn.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:mn.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),mn.jsx(mo,{events:r})]}),mn.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:Q?"rotate(180deg)":"rotate(0deg)"},children:mn.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),mn.jsx("div",{style:{maxHeight:Q?320:0,opacity:Q?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:mn.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:mn.jsx(Br,{events:r})})})]})}),e==="error"&&(Y||ae)&&mn.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[mn.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:mn.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),mn.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),mn.jsxs("button",{onClick:()=>{let a=t?.prompt||Qe.current;a&&p(a,le);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[mn.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&(Y||ae)&&mn.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:mn.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[mn.jsx("textarea",{ref:xt,value:I,onChange:a=>{C(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),lr()),a.key==="Escape"&&!m&&ur();},placeholder:Le.length>0&&!ae?"Ask for another change...":`Describe your ideal ${ir.toLowerCase()}...`,rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),mn.jsx("button",{onClick:lr,disabled:!I.trim(),onMouseEnter:()=>q(true),onMouseLeave:()=>q(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:I.trim()?1:.25,transform:j&&I.trim()?"scale(1.1)":"scale(1)",background:I.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:I.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:mn.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return m?Rt:ue&&Fe?gn.createPortal(Rt,Fe.document.body):mn.jsx(ho,{children:Rt})}function Wr(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 Wt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=Z(),[g,f]=Bt.useState("idle"),[x,T]=Bt.useState(null),[_,R]=Bt.useState([]),[k,m]=Bt.useState(null),I=Bt.useRef(null),C=Bt.useCallback(()=>{f("prompting"),R([]),m(null),T(null);},[]),N=Bt.useCallback(()=>{f("idle"),I.current&&(I.current.close(),I.current=null);},[]);Bt.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(S=>S==="idle"?"prompting":S);},[s?.preview_session_id,s?.target.id,e]);let $=Bt.useCallback(async(S,h,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),R([]),m(null);let w;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...G()},body:JSON.stringify({prompt:S,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let q=await l.json().catch(()=>({}));throw new Error(q.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),w=await(await fetch(`${o}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...G()}})).json();}else if(d?.forkId){let u={prompt:S};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}else {let u={userId:r,prompt:S,boundaryId:e,appId:i};h&&(u.containerId=h),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}T(w);let E=new URLSearchParams({key:t});s?(E.set("previewSessionId",s.preview_session_id),E.set("previewForkId",w.id)):r&&E.set("userId",r),n&&E.set("userHash",n);let A=new EventSource(`${o}/api/v1/forks/${w.id}/events?${E.toString()}`);I.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(y=>[...y,l]),l.type==="complete"){let y=l.data;p(e,w.id),c().catch(()=>{}).finally(()=>{let j={...w,status:"complete",moduleUrl:y.moduleUrl,cssUrls:y.cssUrls,summary:y.summary,completedAt:new Date().toISOString()};T(j),f("complete"),A.close();});}else if(l.type==="error"){let y=l.data;m(y.error||"Unknown error"),f("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${t}`,...G()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${w.id}`,{headers:u}).then(l=>l.json()).then(l=>{T(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(m(l.error||"Fork generation failed"),f("error"));}).catch(()=>{m("Connection lost"),f("error");}),A.close();};}catch(w){m(w.message),f("error");}},[t,i,o,e,s,p,c,n,r]),L=Bt.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let S={userId:r,boundaryId:e,appId:i};n&&(S.userHash=n);let h=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(S)});if(!h.ok){let w=await h.json().catch(()=>({}));throw new Error(w.error||`API error: ${h.status}`)}let d=await h.json();return await c().catch(()=>{}),d.removed?(T(null),f("prompting")):d.fork&&(T(d.fork),f("complete")),d}catch(S){throw m(S.message),S}},[t,i,o,e,c,n,r]);return {state:g,fork:x,events:_,error:k,open:C,close:N,startFork:$,undoFork:L}}function Kr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Wt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function Kt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=Z(),[p,g]=Bt.useState("idle"),[f,x]=Bt.useState(null),[T,_]=Bt.useState([]),[R,k]=Bt.useState(null),m=Bt.useRef(null),I=Bt.useCallback(()=>{g("prompting"),_([]),k(null),x(null);},[]),C=Bt.useCallback(()=>{g("idle"),m.current&&(m.current.close(),m.current=null);},[]);Bt.useEffect(()=>{o&&o.target.kind==="slot"&&g(L=>L==="idle"?"prompting":L);},[o?.preview_session_id,o?.target.kind]);let N=Bt.useCallback(async(L,S,h,d)=>{try{g("running"),_([]),k(null);let w;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...G()},body:JSON.stringify({prompt:L,...S?{slot_id:S}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let q=await l.json().catch(()=>({}));throw new Error(q.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),w=await(await fetch(`${n}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...G()}})).json();}else if(d?.forkId){let u={prompt:L};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}else {let u={userId:t,prompt:L};S&&(u.slotId=S),h&&(u.containerId=h),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}x(w);let E=new URLSearchParams({key:e});o?(E.set("previewSessionId",o.preview_session_id),E.set("previewForkId",w.id)):t&&E.set("userId",t),r&&E.set("userHash",r);let A=new EventSource(`${n}/api/v1/forks/${w.id}/events?${E.toString()}`);m.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(_(y=>[...y,l]),l.type==="complete"){let y=l.data,j={...w,status:"complete",bundleUrl:y.bundleUrl,summary:y.summary,completedAt:new Date().toISOString()};x(j),g("complete"),S&&y.bundleUrl&&i(S,j),A.close();}else if(l.type==="error"){let y=l.data;k(y.error||"Unknown error"),g("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...G()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${w.id}`,{headers:u}).then(l=>l.json()).then(l=>{x(l),l.status==="complete"?(g("complete"),S&&l.bundleUrl&&i(S,l)):l.status==="error"&&(k(l.error||"Fork generation failed"),g("error"));}).catch(()=>{k("Connection lost"),g("error");}),A.close();};}catch(w){k(w.message),g("error");}},[e,t,r,n,o,i]),$=Bt.useCallback(async L=>{try{let S={userId:t,slotId:L};r&&(S.userHash=r);let h=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(S)});if(!h.ok){let w=await h.json().catch(()=>({}));throw new Error(w.error||`API error: ${h.status}`)}let d=await h.json();return c(L),d.removed?(s(L),x(null),g("prompting")):d.fork&&(i(L,d.fork),x(d.fork)),d}catch(S){throw k(S.message),S}},[e,t,r,n,s,i]);return {state:p,fork:f,events:T,error:R,open:I,close:C,startFork:N,undoFork:$}}function Gr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=Kt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Gt(e){let t=Wr(e),r=Gr(),n=Kr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=Z(),g=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",x=t.id,T=t.title,_=Bt.useCallback((k,m,I,C)=>t.type==="slot"?r.submit(k,m??t.id,I,C):n.submit(k,I,C),[n,r,t]),R=Bt.useCallback(k=>t.type==="slot"?r.undo(k??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:x,targetLabel:T,historyMode:f,submit:_,undo:R,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:x,targetLabel:T,historyMode:f}:{targetId:x,targetLabel:T,historyMode:f},onSubmit:_,onUndo:R,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function ze(e){let{embedded:t}=e,r=Gt(e);return t?mn.jsx(pt,{...r.panelProps,embedded:true}):r.isOpen?mn.jsx(pt,{...r.panelProps}):mn.jsx(Ht,{...r.buttonProps})}function vo({boundaryId:e,title:t}){return mn.jsx(ze,{boundaryId:e,title:t})}function Vt(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 Vr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function qt(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function qr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Xr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yr(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Xt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f+=1){let{rect:x,borderRadius:T}=e[f],_=x.left-.5,R=x.top-.5,k=x.width+1,m=x.height+1,I=Math.min(T+.5,k/2,m/2),C=Yr(_,R,k,m,I),N=`__fork-glow-${f}`,$=document.createElementNS(t,"filter");$.setAttribute("id",N),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),$.appendChild(L),o.appendChild($);let S=`__fork-mask-${f}`,h=document.createElementNS(t,"mask");h.setAttribute("id",S),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(_-200)),h.setAttribute("y",String(R-200)),h.setAttribute("width",String(k+400)),h.setAttribute("height",String(m+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(k+400)),d.setAttribute("height",String(m+400)),d.setAttribute("fill","white"),h.appendChild(d);let w=document.createElementNS(t,"path");w.setAttribute("d",C),w.setAttribute("fill","black"),h.appendChild(w),o.appendChild(h);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${S})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let x=i[f],T=i[f+1],_=x.__group;if(!_)continue;let R=T.getTotalLength(),k=x.getTotalLength();if(R<=0)continue;let m=R*.35;T.setAttribute("stroke-dasharray",`${m} ${R-m}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=k*.35;x.setAttribute("stroke-dasharray",`${I} ${k-I}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*k,offset:.06},{strokeDashoffset:-2*k,offset:.92},{strokeDashoffset:-2.25*k,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Zr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Yr(c.left,c.top,c.width,c.height,p)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var Ke=new Map,Ge=new Map,Yt=new Map;function Fo(e){for(let t of e)Ge.set(t,(Ge.get(t)??0)+1);}function Ro(e){if(!(typeof document>"u"))for(let t of e){let r=(Ge.get(t)??0)-1;if(r>0){Ge.set(t,r);continue}Ge.delete(t),Ke.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function _o(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function en(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 Co(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ke.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return Ke.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw Ke.delete(e),o});return Ke.set(e,n),n}function Eo(e){let t=Yt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Yt.delete(e),n});return Yt.set(e,r),r}async function Ao(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Co(i)));let o=await Eo(e.moduleUrl);return en(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 en(n,r)}function $o(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:g}=Z(),[f,x]=Bt.useState(null),[T,_]=Bt.useState(null),R=Bt.useRef(null),k=Bt.useRef(null),m=Bt.useRef(null),I=Bt.useRef(false),C=Bt.useRef(null),N=Bt.useRef(null),$=p(e.id),L=$?`override:${$.id}`:"original",S=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Bt.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),C.current&&(C.current.remove(),C.current=null);},[]),Bt.useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,S]),Bt.useEffect(()=>{let h=$?.cssUrls??[];if(h.length!==0)return Fo(h),()=>Ro(h)},[$?.cssUrls.join("|")]),Bt.useEffect(()=>{if(o&&!i&&!f||k.current===L&&f)return;let h=false;return _(null),Ao($,e.original,e.exportName).then(d=>{if(!h){if($?.id&&g(e.id,$.id)&&R.current){let w=Vt(R.current);if(w){let E=qt(w);E.length>0&&(m.current=E,I.current=true,N.current&&(clearTimeout(N.current),N.current=null),C.current&&C.current.remove(),C.current=Vr(w));}}k.current=L,Bt.startTransition(()=>{x(()=>d);});}}).catch(d=>{h||_(_o(d));}),()=>{h=true;}},[g,L,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,f]),Bt.useEffect(()=>{if(!I.current||!f||!R.current)return;let h=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(h||!R.current)return;let d=m.current,w=Vt(R.current);if(m.current=null,I.current=false,!d||!w){C.current&&(C.current.remove(),C.current=null);return}let E=qt(w),A=qr(d,E),u=Xr(d,E),l=C.current;if(u.length>0&&l){let y=Zr(u);N.current=setTimeout(()=>{N.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),C.current===l&&(C.current=null),A.length>0&&Xt(A);},j);},3500);}else l&&(l.remove(),C.current===l&&(C.current=null)),A.length>0&&Xt(A);});}),()=>{h=true;}},[f]),T)throw T;return f?mn.jsx("div",{ref:R,style:{display:"contents"},children:mn.jsx(f,{...r})}):mn.jsx(mn.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Mo({slotId:e,title:t,slotLabel:r}){return mn.jsx(ze,{slotId:e,title:t,slotLabel:r})}
|
|
44
|
-
exports.ForkBoundaryUI=
|
|
44
|
+
`}),wn.jsxs("div",{className:"__fork-panel",style:hn,children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[wn.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!xt&&confirm("Kill all forks in this container?")){Xe(true);try{let h=await cn();`${h?.deleted??0}`,Qe([]),Ee(null),Ae(!1),A("");}catch(h){console.error("[Fork] Reset failed:",h);}finally{Xe(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:wn.jsx(gt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:pn}):Me.length===0&&!tt?wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):tt?wn.jsxs("div",{ref:it,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[wn.jsxs("button",{type:"button",onClick:()=>{G(a=>!a);},onMouseEnter:()=>rr(true),onMouseLeave:()=>rr(false),"aria-haspopup":"menu","aria-expanded":ee,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:ae||ee?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[wn.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),wn.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:ee?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),ee&&wn.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Me.map(a=>{let h=a.id===Q,P=sn===a.id,q=X===a.id;return wn.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>nr(a.id),onMouseLeave:()=>nr(null),onClick:()=>{a.id!==Q&&gn(a.id);},disabled:!!X,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:P?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:X?"default":"pointer",textAlign:"left",fontWeight:h?600:400,opacity:X&&!q?.55:1},children:[wn.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:h&&wn.jsx(lucideReact.Check,{style:{width:12,height:12}})}),wn.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:q?"Switching...":a.name})]},a.id)}),wn.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Ft?wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[wn.jsx("input",{ref:_t,type:"text",value:ye,placeholder:"Container name",disabled:X==="__new__",onChange:a=>Oe(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),gr(ye)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Ze(false),Oe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),wn.jsx("button",{type:"button",onClick:()=>{gr(ye);},disabled:!ye.trim()||X==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!ye.trim()||X==="__new__"?"#e5e7eb":"#1c4587",color:!ye.trim()||X==="__new__"?"#9ca3af":"#ffffff",cursor:!ye.trim()||X==="__new__"?"default":"pointer",flexShrink:0},children:X==="__new__"?wn.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):wn.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):wn.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>or(true),onMouseLeave:()=>or(false),onClick:()=>{X||(ke(null),Oe(""),Ze(true));},disabled:!!X,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:an?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:X?"default":"pointer",textAlign:"left",opacity:X&&X!=="__new__"?.55:1},children:"+ New container"}),sr&&wn.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:sr})]})]}):wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),e==="running"&&wn.jsx("span",{title:we?`Estimated ~${we} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:we?"#1c4587":"#9ca3af",backgroundColor:we?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:we?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:we?`~${we}m`:"~ m"}),e==="complete"&&wn.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!b&&wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[lr&&wn.jsx("button",{onClick:ue?fn:un,onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),title:ue?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ue?wn.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):wn.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),wn.jsx("button",{onClick:mr,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:$?"#4b5563":"#9ca3af",backgroundColor:$?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:wn.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),wn.jsxs("div",{ref:et,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(Y||le)&&wn.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[wn.jsx("button",{onClick:()=>{Ee(null),Ae(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 h=(Y?Ne.find(P=>P.id===Y)?.targetId:null)??ge;return h?wn.jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${h}`,children:["Forking ",wn.jsx("span",{style:{color:"#6b7280"},children:h})]}):null})()]}),!Y&&!le&&wn.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[wn.jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[wn.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),ge&&wn.jsx("button",{onClick:()=>{Ee(null),Ae(true);},title:`Start a new fork on ${ge}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),Ne.length===0&&wn.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),Ne.length>0&&wn.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ne.map(a=>{let h=a.summary||"Untitled fork";return wn.jsxs("button",{onClick:()=>{Ae(false),Ee(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:P=>P.currentTarget.style.background="#fafafa",onMouseLeave:P=>P.currentTarget.style.background="#ffffff",children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[wn.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:h}),wn.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:ko(a.updatedAt)})]}),wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[wn.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),wn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),wn.jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?wn.jsxs(wn.Fragment,{children:[wn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),wn.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),le&&wn.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:wn.jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),Y&&Le.length>0&&wn.jsx("div",{style:{padding:"16px 16px 0 16px"},children:Le.map((a,h)=>wn.jsx("div",{style:{marginBottom:h<Le.length-1?10:0},children:a.type==="user"?wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[wn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:wn.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),wn.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[wn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:wn.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),wn.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[wn.jsx("span",{style:{flex:1},children:a.text}),m&&h===Le.length-1&&e!=="running"&&wn.jsxs("button",{onClick:P=>{P.stopPropagation(),mn();},onMouseEnter:()=>ne(h),onMouseLeave:()=>ne(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:pe===h?"rgba(0,0,0,0.06)":"transparent",color:pe===h?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[wn.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),pe===h&&wn.jsx("span",{style:{position:"absolute",bottom:"calc(100% + 4px)",right:0,fontSize:10,fontWeight:500,color:"#fff",background:"#374151",borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",pointerEvents:"none",lineHeight:"16px"},children:"Undo"})]})]})]})},h))}),e==="running"&&(Y||le)&&wn.jsx("div",{style:{padding:16},children:wn.jsxs("div",{onClick:()=>z(!re),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[wn.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:wn.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),wn.jsx(wo,{events:r})]}),wn.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:re?"rotate(180deg)":"rotate(0deg)"},children:wn.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),wn.jsx("div",{style:{maxHeight:re?320:0,opacity:re?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:wn.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:wn.jsx(jr,{events:r})})})]})}),e==="error"&&(Y||le)&&wn.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[wn.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:wn.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),wn.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),wn.jsxs("button",{onClick:()=>{let a=t?.prompt||nt.current;a&&p(a,ge);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[wn.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&(Y||le)&&wn.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:wn.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[wn.jsx("textarea",{ref:Rt,value:M,onChange:a=>{A(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),fr()),a.key==="Escape"&&!b&&mr();},placeholder:Le.length>0&&!le?"Ask for another change...":`Describe your ideal ${cr.toLowerCase()}...`,rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),wn.jsx("button",{onClick:fr,disabled:!M.trim(),onMouseEnter:()=>Z(true),onMouseLeave:()=>Z(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:M.trim()?1:.25,transform:j&&M.trim()?"scale(1.1)":"scale(1)",background:M.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:M.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:wn.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return b?At:ue&&Re?bn.createPortal(At,Re.document.body):wn.jsx(vo,{children:At})}function qr(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function Jt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=te(),[m,f]=Bt.useState("idle"),[g,I]=Bt.useState(null),[E,R]=Bt.useState([]),[y,b]=Bt.useState(null),M=Bt.useRef(null),A=Bt.useCallback(()=>{f("prompting"),R([]),b(null),I(null);},[]),H=Bt.useCallback(()=>{f("idle"),M.current&&(M.current.close(),M.current=null);},[]);Bt.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(_=>_==="idle"?"prompting":_);},[s?.preview_session_id,s?.target.id,e]);let T=Bt.useCallback(async(_,w,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),R([]),b(null);let S;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...K()},body:JSON.stringify({prompt:_,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Z=await l.json().catch(()=>({}));throw new Error(Z.error||`API error: ${l.status}`)}let k=await l.json();k.container_id&&Se(k.container_id,k.container_name),Ue(k.fork_id),S=await(await fetch(`${o}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...K()}})).json();}else if(d?.forkId){let u={prompt:_};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:r,prompt:_,boundaryId:e,appId:i};w&&(u.containerId=w),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}I(S);let C=new URLSearchParams({key:t});s?(C.set("previewSessionId",s.preview_session_id),C.set("previewForkId",S.id)):r&&C.set("userId",r),n&&C.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${S.id}/events?${C.toString()}`);M.current=$,$.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(k=>[...k,l]),l.type==="complete"){let k=l.data;p(e,S.id),c().catch(()=>{}).finally(()=>{let j={...S,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};I(j),f("complete"),$.close();});}else if(l.type==="error"){let k=l.data;b(k.error||"Unknown error"),f("error"),$.close();}}catch{}},$.onerror=()=>{let u={Authorization:`Bearer ${t}`,...K()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{I(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(b(l.error||"Fork generation failed"),f("error"));}).catch(()=>{b("Connection lost"),f("error");}),$.close();};}catch(S){b(S.message),f("error");}},[t,i,o,e,s,p,c,n,r]),O=Bt.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let _={userId:r,boundaryId:e,appId:i};n&&(_.userHash=n);let w=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(_)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return await c().catch(()=>{}),d.removed?(I(null),f("prompting")):d.fork&&(I(d.fork),f("complete")),d}catch(_){throw b(_.message),_}},[t,i,o,e,c,n,r]);return {state:m,fork:g,events:E,error:y,open:A,close:H,startFork:T,undoFork:O}}function Vr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Jt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function qt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=te(),[p,m]=Bt.useState("idle"),[f,g]=Bt.useState(null),[I,E]=Bt.useState([]),[R,y]=Bt.useState(null),b=Bt.useRef(null),M=Bt.useCallback(()=>{m("prompting"),E([]),y(null),g(null);},[]),A=Bt.useCallback(()=>{m("idle"),b.current&&(b.current.close(),b.current=null);},[]);Bt.useEffect(()=>{o&&o.target.kind==="slot"&&m(O=>O==="idle"?"prompting":O);},[o?.preview_session_id,o?.target.kind]);let H=Bt.useCallback(async(O,_,w,d)=>{try{m("running"),E([]),y(null);let S;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...K()},body:JSON.stringify({prompt:O,..._?{slot_id:_}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Z=await l.json().catch(()=>({}));throw new Error(Z.error||`API error: ${l.status}`)}let k=await l.json();k.container_id&&Se(k.container_id,k.container_name),Ue(k.fork_id),S=await(await fetch(`${n}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...K()}})).json();}else if(d?.forkId){let u={prompt:O};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:t,prompt:O};_&&(u.slotId=_),w&&(u.containerId=w),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}g(S);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 $=new EventSource(`${n}/api/v1/forks/${S.id}/events?${C.toString()}`);b.current=$,$.onmessage=u=>{try{let l=JSON.parse(u.data);if(E(k=>[...k,l]),l.type==="complete"){let k=l.data,j={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};g(j),m("complete"),_&&k.bundleUrl&&i(_,j),$.close();}else if(l.type==="error"){let k=l.data;y(k.error||"Unknown error"),m("error"),$.close();}}catch{}},$.onerror=()=>{let u={Authorization:`Bearer ${e}`,...K()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{g(l),l.status==="complete"?(m("complete"),_&&l.bundleUrl&&i(_,l)):l.status==="error"&&(y(l.error||"Fork generation failed"),m("error"));}).catch(()=>{y("Connection lost"),m("error");}),$.close();};}catch(S){y(S.message),m("error");}},[e,t,r,n,o,i]),T=Bt.useCallback(async O=>{try{let _={userId:t,slotId:O};r&&(_.userHash=r);let w=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(_)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return c(O),d.removed?(s(O),g(null),m("prompting")):d.fork&&(i(O,d.fork),g(d.fork)),d}catch(_){throw y(_.message),_}},[e,t,r,n,s,i]);return {state:p,fork:f,events:I,error:R,open:M,close:A,startFork:H,undoFork:T}}function Xr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=qt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Vt(e){let t=qr(e),r=Xr(),n=Vr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=te(),m=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",g=t.id,I=t.title,E=Bt.useCallback((y,b,M,A)=>t.type==="slot"?r.submit(y,b??t.id,M,A):n.submit(y,M,A),[n,r,t]),R=Bt.useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...m,target:t,targetId:g,targetLabel:I,historyMode:f,submit:E,undo:R,buttonProps:{onClick:m.open},panelProps:{state:m.state,fork:m.fork,events:m.events,error:m.error,...t.type==="slot"?{slotId:g,targetLabel:I,historyMode:f}:{targetId:g,targetLabel:I,historyMode:f},onSubmit:E,onUndo:R,onClose:m.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function Ge(e){let{embedded:t}=e,r=Vt(e);return t?wn.jsx(kt,{...r.panelProps,embedded:true}):r.isOpen?wn.jsx(kt,{...r.panelProps}):wn.jsx(zt,{...r.buttonProps})}function Ro({boundaryId:e,title:t}){return wn.jsx(Ge,{boundaryId:e,title:t})}function Yt(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Zr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function Zt(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Qr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function en(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function tn(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Qt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f+=1){let{rect:g,borderRadius:I}=e[f],E=g.left-.5,R=g.top-.5,y=g.width+1,b=g.height+1,M=Math.min(I+.5,y/2,b/2),A=tn(E,R,y,b,M),H=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",H),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let O=document.createElementNS(t,"feGaussianBlur");O.setAttribute("in","SourceGraphic"),O.setAttribute("stdDeviation","8"),T.appendChild(O),o.appendChild(T);let _=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",_),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(E-200)),w.setAttribute("y",String(R-200)),w.setAttribute("width",String(y+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(E-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(y+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",A),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let C=document.createElementNS(t,"g");C.setAttribute("mask",`url(#${_})`),C.setAttribute("opacity","0");let $=document.createElementNS(t,"g");$.setAttribute("filter",`url(#${H})`);let u=document.createElementNS(t,"path");u.setAttribute("d",A),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),$.appendChild(u),C.appendChild($),n.appendChild(C);let l=document.createElementNS(t,"path");l.setAttribute("d",A),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=C;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let g=i[f],I=i[f+1],E=g.__group;if(!E)continue;let R=I.getTotalLength(),y=g.getTotalLength();if(R<=0)continue;let b=R*.35;I.setAttribute("stroke-dasharray",`${b} ${R-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=y*.35;g.setAttribute("stroke-dasharray",`${M} ${y-M}`),g.setAttribute("stroke-dashoffset","0"),s.push(g.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(E.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(m);for(let g of s)try{g.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},m=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function rn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let m=document.createElementNS(t,"path");m.setAttribute("d",tn(c.left,c.top,c.width,c.height,p)),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),m.setAttribute("stroke-width","1.5"),m.setAttribute("stroke-dasharray","8 4"),m.setAttribute("stroke-linecap","round"),m.setAttribute("filter","url(#__fork-removed-shadow)"),m.setAttribute("opacity","0"),n.appendChild(m),m.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var qe=new Map,Ve=new Map,er=new Map;function Co(e){for(let t of e)Ve.set(t,(Ve.get(t)??0)+1);}function $o(e){if(!(typeof document>"u"))for(let t of e){let r=(Ve.get(t)??0)-1;if(r>0){Ve.set(t,r);continue}Ve.delete(t),qe.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Po(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function on(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function Io(e){if(!e||typeof document>"u")return Promise.resolve();let t=qe.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return qe.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw qe.delete(e),o});return qe.set(e,n),n}function To(e){let t=er.get(e);if(t)return t;let r=import(e).catch(n=>{throw er.delete(e),n});return er.set(e,r),r}async function Mo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Io(i)));let o=await To(e.moduleUrl);return on(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return on(n,r)}function Oo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:m}=te(),[f,g]=Bt.useState(null),[I,E]=Bt.useState(null),R=Bt.useRef(null),y=Bt.useRef(null),b=Bt.useRef(null),M=Bt.useRef(false),A=Bt.useRef(null),H=Bt.useRef(null),T=p(e.id),O=T?`override:${T.id}`:"original",_=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Bt.useEffect(()=>()=>{H.current&&(clearTimeout(H.current),H.current=null),A.current&&(A.current.remove(),A.current=null);},[]),Bt.useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,_]),Bt.useEffect(()=>{let w=T?.cssUrls??[];if(w.length!==0)return Co(w),()=>$o(w)},[T?.cssUrls.join("|")]),Bt.useEffect(()=>{if(o&&!i&&!f||y.current===O&&f)return;let w=false;return E(null),Mo(T,e.original,e.exportName).then(d=>{if(!w){if(T?.id&&m(e.id,T.id)&&R.current){let S=Yt(R.current);if(S){let C=Zt(S);C.length>0&&(b.current=C,M.current=true,H.current&&(clearTimeout(H.current),H.current=null),A.current&&A.current.remove(),A.current=Zr(S));}}y.current=O,Bt.startTransition(()=>{g(()=>d);});}}).catch(d=>{w||E(Po(d));}),()=>{w=true;}},[m,O,o,i,s,T?.id,T?.moduleUrl,T?.integrity,T?.cssUrls.join("|"),e.exportName,e.original,f]),Bt.useEffect(()=>{if(!M.current||!f||!R.current)return;let w=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(w||!R.current)return;let d=b.current,S=Yt(R.current);if(b.current=null,M.current=false,!d||!S){A.current&&(A.current.remove(),A.current=null);return}let C=Zt(S),$=Qr(d,C),u=en(d,C),l=A.current;if(u.length>0&&l){let k=rn(u);H.current=setTimeout(()=>{H.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),k.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),k.remove(),A.current===l&&(A.current=null),$.length>0&&Qt($);},j);},3500);}else l&&(l.remove(),A.current===l&&(A.current=null)),$.length>0&&Qt($);});}),()=>{w=true;}},[f]),I)throw I;return f?wn.jsx("div",{ref:R,style:{display:"contents"},children:wn.jsx(f,{...r})}):wn.jsx(wn.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function No({slotId:e,title:t,slotLabel:r}){return wn.jsx(Ge,{slotId:e,title:t,slotLabel:r})}
|
|
45
|
+
exports.ForkBoundaryUI=Ro;exports.ForkButton=zt;exports.ForkChatInterface=Ge;exports.ForkPanel=kt;exports.ForkProvider=On;exports.ForkSlot=qn;exports.ForkUI=No;exports.clearCachedManifest=$n;exports.forkable=Oo;exports.loadManifest=ut;exports.manifestDiffers=Pn;exports.readCachedManifest=An;exports.registerForkShared=$t;exports.useBoundaryFork=Jt;exports.useFork=qt;exports.useForkChatPanel=Vt;exports.usePreviewSession=dt;exports.writeCachedManifest=Cn;
|
package/dist/index.d.cts
CHANGED
|
@@ -39,6 +39,11 @@ interface ForkProviderBase {
|
|
|
39
39
|
* The SDK calls this on mount (same-origin, cookies sent automatically).
|
|
40
40
|
* Your backend computes: userHash = HMAC-SHA256(sk_fork_key, userId).
|
|
41
41
|
* This provides verified per-user fork isolation.
|
|
42
|
+
* To auto-enter admin mode for tenant operators, authUrl may also return
|
|
43
|
+
* `{ forkUserId, forkOperatorExpiresAt, forkOperatorHash }`, where
|
|
44
|
+
* forkOperatorExpiresAt is a unix-seconds timestamp no more than 10 minutes
|
|
45
|
+
* in the future and forkOperatorHash is HMAC-SHA256(sk_fork_key,
|
|
46
|
+
* `fork-operator:v1:${appId}:${userId}:${forkUserId}:${forkOperatorExpiresAt}`).
|
|
42
47
|
*/
|
|
43
48
|
type ForkProviderProps = ForkProviderBase & ({
|
|
44
49
|
userId: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -39,6 +39,11 @@ interface ForkProviderBase {
|
|
|
39
39
|
* The SDK calls this on mount (same-origin, cookies sent automatically).
|
|
40
40
|
* Your backend computes: userHash = HMAC-SHA256(sk_fork_key, userId).
|
|
41
41
|
* This provides verified per-user fork isolation.
|
|
42
|
+
* To auto-enter admin mode for tenant operators, authUrl may also return
|
|
43
|
+
* `{ forkUserId, forkOperatorExpiresAt, forkOperatorHash }`, where
|
|
44
|
+
* forkOperatorExpiresAt is a unix-seconds timestamp no more than 10 minutes
|
|
45
|
+
* in the future and forkOperatorHash is HMAC-SHA256(sk_fork_key,
|
|
46
|
+
* `fork-operator:v1:${appId}:${userId}:${forkUserId}:${forkOperatorExpiresAt}`).
|
|
42
47
|
*/
|
|
43
48
|
type ForkProviderProps = ForkProviderBase & ({
|
|
44
49
|
userId: string;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as gn from'react-dom';import {createPortal}from'react-dom';import*as mn from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as hn from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var be="__FORK_SHARED__";function Ct(){var t,r,n,o;let e=globalThis;return e[be]||(e[be]={}),(t=e[be]).react||(t.react=Bt),(r=e[be])["react-dom"]||(r["react-dom"]=gn),(n=e[be])["react/jsx-runtime"]||(n["react/jsx-runtime"]=mn),(o=e[be])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=hn),e[be]}function Et(e){return Object.assign(Ct(),e)}var yn="__fork_preview_session__";function nt(e){return `${yn}${e}`}var H={apiKey:null,session:null},At=new Set;function ot(){for(let e of At)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function pr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function kn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(nt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:pr(r)?(window.sessionStorage.removeItem(nt(e)),null):r}catch{return null}}function $t(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(nt(e),JSON.stringify(t)):window.sessionStorage.removeItem(nt(e));}catch{}}function Ne(e){H.apiKey!==e&&(H.apiKey=e,H.session=kn(e),ot());}function we(){return H.session?pr(H.session)?(Pt(null),null):H.session:null}function Pt(e){H.session=e,H.apiKey&&$t(H.apiKey,e),ot();}function Be(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&$t(H.apiKey,H.session),ot());}function ve(e,t){H.session&&(H.session.container_id===e&&H.session.container_name===t||(H.session={...H.session,container_id:e,container_name:t??H.session.container_name??"Fork",fork_id:null},H.apiKey&&$t(H.apiKey,H.session),ot()));}function Mt(e){return At.add(e),()=>{At.delete(e);}}var gr="__fork_preview";function mr(){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(gr);return typeof r=="string"&&r.length>0?r:null}function Tt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return yr()!==null}function hr(){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(gr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Se=null;function yr(){if(Se)return Se;let e=mr();return e?(Se=e,hr(),Se):null}async function It(e,t){Ne(e);let r=we();if(r)return Se=null,r;let n=Se??mr();if(Se=null,!n)return null;hr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Pt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function wn(){return we()}function vn(){return null}function st(){return useSyncExternalStore(Mt,wn,vn)}function G(){let e=we();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 it(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[c,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:f,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Sn="fork:manifest:v1";function Lt(e,t,r){return `${Sn}:${e}:${t}:${r}`}function xn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Lt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Fn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Lt(e,t,r),JSON.stringify(n));}catch{}}function Rn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Lt(e,t,r));}catch{}}function _n(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var wr=createContext(null);function Ue(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function An(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Ue(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Ue(e,i)):[]};return r}function kr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Ue(e,c),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function br(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:Ue(e,i),cssUrls:(o.cssUrls??[]).map(s=>Ue(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function $n(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=useState(()=>(Ne(t),Tt(t))),[g,f]=useState({}),[x,T]=useState(s?{userId:s,userHash:void 0}:null),[_,R]=useState(!!s||p),[k,m]=useState({}),[I,C]=useState(!o),[N,$]=useState(0),[L,S]=useState(null),h=useRef(new Map),d=useRef(new Map),[w,E]=useState(0),A=useRef(new Set),u=useRef(new Map),l=useRef(void 0);Ct(),useEffect(()=>{return It(t,r).then(()=>{}),()=>{}},[]);let y=st();i&&l.current!==i&&(Et(i),l.current=i),useEffect(()=>{c&&(p||(R(false),fetch(c,{credentials:"include"}).then(P=>{if(!P.ok)throw new Error(`Auth endpoint returned ${P.status}`);return P.json()}).then(P=>{if(!P.userId||typeof P.userId!="string")throw new Error("authUrl response must include userId");T({userId:P.userId,userHash:P.userHash});}).catch(P=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",P.message);}).finally(()=>{R(true);})));},[c,p]),useEffect(()=>{!c&&s&&(T({userId:s,userHash:void 0}),R(true));},[s,c]);let j=x?.userId??"",q=x?.userHash,D=y?"":j,W=y?void 0:q,Q=!!o,z=useCallback(async()=>{if(!Q){S(null),m({}),C(true),$(F=>F+1);return}if(!_){C(false);return}if(!y&&!D||!o){S(null),m({}),C(true),$(F=>F+1);return}if(C(false),!y){try{let F=await it({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});F&&(S(F.containerId),f(kr(r,F,D,o)),m(br(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),S(null),f({}),m({});}finally{$(F=>F+1),C(true);}return}if(S(y.container_id??null),y.container_id){try{let F=await it({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:y.container_id,extraHeaders:G()});F&&(f(kr(r,F,D,o)),m(br(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch preview container manifest:",F.message),f({}),m({});}finally{$(F=>F+1),C(true);}return}let P=new URLSearchParams({appId:o,userId:D});W&&P.set("userHash",W);try{let F=await fetch(`${r}/api/v1/boundaries/manifest?${P.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}});if(!F.ok)throw new Error(`${F.status}`);let O=await F.json();m(An(r,O));}catch(F){console.error("[ForkProvider] Failed to fetch module override manifest:",F.message),m({});}finally{$(F=>F+1),C(true);}},[t,o,r,_,Q,W,D,y?.preview_session_id,y?.fork_id,y?.container_id]);useEffect(()=>{if(!D||o&&(!y||y.container_id))return;let P=new URLSearchParams({userId:D});W&&P.set("userHash",W),fetch(`${r}/api/v1/forks/active?${P.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&f(F);}).catch(()=>{});},[t,o,D,W,r,y?.preview_session_id,y?.fork_id]),useEffect(()=>{z();},[z]);let se=useCallback((P,F)=>{f(O=>({...O,[P]:F}));},[]),ie=useCallback(P=>{f(F=>{let O={...F};return delete O[P],O});},[]),pe=useCallback(P=>{A.current.add(P);},[]),ee=useCallback(P=>A.current.has(P)?(A.current.delete(P),true):false,[]),kt=useCallback((P,F)=>{u.current.set(P,F);},[]),Je=useCallback((P,F)=>u.current.get(P)!==F?false:(u.current.delete(P),true),[]),Ee=useCallback(P=>{if(!o)return;let F=JSON.stringify(P);h.current.get(P.id)===F||d.current.get(P.id)?.signature===F||(d.current.set(P.id,{boundary:P,signature:F}),E(re=>re+1));},[o]);useEffect(()=>{if(!o||d.current.size===0)return;let P=setTimeout(()=>{let F=Array.from(d.current.values());F.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of F)d.current.get(O.boundary.id)?.signature===O.signature&&(d.current.delete(O.boundary.id),h.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout(P);}},[t,o,r,w]);let de=useCallback(P=>k[P],[k]),te=useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let P=new URLSearchParams({userId:D});W&&P.set("userHash",W);let F={Authorization:`Bearer ${t}`,...G()};o&&(F["X-Fork-App-Id"]=o);let O=await fetch(`${r}/api/v1/forks/all?${P.toString()}`,{method:"DELETE",headers:F});if(!O.ok){let ne=await O.json().catch(()=>({}));throw new Error(ne.error||`API error: ${O.status}`)}let re=await O.json().catch(()=>({}));f({}),m({}),C(true),$(ne=>ne+1),A.current.clear(),u.current.clear();try{for(let ne=sessionStorage.length-1;ne>=0;ne-=1){let Ae=sessionStorage.key(ne);Ae&&Ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(Ae);}}catch{}return re},[t,o,r,W,D]);return jsx(wr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Q,moduleManifestReady:I,moduleManifestVersion:N,currentContainerId:L,previewSession:y,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:pe,shouldSkipAnimation:ee,queueBoundaryAnimation:kt,consumeBoundaryAnimation:Je,registerBoundary:Ee,getBoundaryOverride:de,refreshModuleManifest:z,resetAllForks:te},children:n})}function Z(){let e=useContext(wr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function at(e){return Z().forks[e]}var He=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function Ot(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var Sr=new Set;function xr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Ln(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Nn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Rr(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 Fr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f++){let{rect:x,borderRadius:T}=e[f],_=x.left-.5,R=x.top-.5,k=x.width+1,m=x.height+1,I=Math.min(T+.5,k/2,m/2),C=Rr(_,R,k,m,I),N=`__fork-glow-${f}`,$=document.createElementNS(t,"filter");$.setAttribute("id",N),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),$.appendChild(L),o.appendChild($);let S=`__fork-mask-${f}`,h=document.createElementNS(t,"mask");h.setAttribute("id",S),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(_-200)),h.setAttribute("y",String(R-200)),h.setAttribute("width",String(k+400)),h.setAttribute("height",String(m+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(k+400)),d.setAttribute("height",String(m+400)),d.setAttribute("fill","white"),h.appendChild(d);let w=document.createElementNS(t,"path");w.setAttribute("d",C),w.setAttribute("fill","black"),h.appendChild(w),o.appendChild(h);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${S})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let x=i[f],T=i[f+1],_=x.__group,R=T.getTotalLength(),k=x.getTotalLength();if(R<=0)continue;let m=R*.35;T.setAttribute("stroke-dasharray",`${m} ${R-m}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=k*.35;x.setAttribute("stroke-dasharray",`${I} ${k-I}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*k,offset:.06},{strokeDashoffset:-2*k,offset:.92},{strokeDashoffset:-2.25*k,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function 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"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let g=c.left,f=c.top,x=c.width,T=c.height,_=Math.min(p,x/2,T/2),R=Rr(g,f,x,T,_),k=document.createElementNS(t,"path");k.setAttribute("d",R),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 On(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 Un=Bt__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&On(e.hostProps,t.hostProps)),Nt=class extends Bt__default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function _r({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Ot(t,e);let i=at(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:g}=Z(),[f,x]=useState(null),T=useRef(null),_=useRef(null),R=useRef(null),k=useRef(false),m=useRef(null),I=useRef(null),C=!!(n||o),N=useRef(null);C&&!N.current&&(N.current=new He(e));let $=useRef(o);if($.current=o,useEffect(()=>{if(C)return ()=>{N.current?.destroy(),N.current=null;}},[C,e]),C&&N.current&&n)for(let[w,E]of Object.entries(n))N.current.set(w,E);useEffect(()=>{if(!C)return;N.current||(N.current=new He(e));let w=N.current,E=Object.keys($.current||{}).map(A=>w.on(A,(...u)=>$.current?.[A]?.(...u)));return ()=>E.forEach(A=>A())},[C,e]),useEffect(()=>{if(Sr.has(e))return;Sr.add(e);let w={id:e,appId:p,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify(w)}).catch(()=>{});},[e,s,c,r,p]);let L=i?.id||null;useEffect(()=>{if(i?.bundleUrl,T.current,_.current,!i?.bundleUrl||!L){return}let w=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,A=sessionStorage.getItem(E),u=g(e),l=!u&&A!==L;if(u&&L&&sessionStorage.setItem(E,L),l&&_.current){let W=xr(_.current);R.current=W,k.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Bt__default,window.__FORK_REACT_DOM__=gn,window.__FORK_REACT_JSX__=mn;let y=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${y}`,q=document.createElement("link");q.rel="stylesheet",q.href=j,q.dataset.forkSlot=e,document.head.appendChild(q);let D=document.createElement("script");return D.src=w+"?t="+y,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(_.current&&R.current&&k.current){let Q=_.current.getBoundingClientRect(),z=_.current.cloneNode(true);z.style.position="fixed",z.style.top=`${Q.top}px`,z.style.left=`${Q.left}px`,z.style.width=`${Q.width}px`,z.style.height=`${Q.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(_.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=_.current.querySelectorAll("*"),pe=z.querySelectorAll("*");for(let ee=0;ee<ie.length;ee++)ie[ee].scrollTop!==0&&(pe[ee].scrollTop=ie[ee].scrollTop),ie[ee].scrollLeft!==0&&(pe[ee].scrollLeft=ie[ee].scrollLeft);m.current=z;}x(()=>W.default),T.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),q.remove(),I.current&&(clearTimeout(I.current),I.current=null),m.current&&(m.current.remove(),m.current=null);}},[L,s,e]),useEffect(()=>{if(!k.current||!f||!_.current){`${e}${k.current}`,_.current;return}let w=R.current;if(!w){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let E=xr(_.current),A=Ln(w,E),u=Nn(w,E),l=m.current;if(`${e}${A.length}${u.length}`,u.length>0&&l){let y=Bn(u);I.current=setTimeout(()=>{I.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),m.current=null,A.length>0&&(Fr(A));},j);},3500);}else l&&(l.remove(),m.current=null),A.length>0&&(Fr(A));R.current=null,k.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[f]);let S={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:_,style:S,children:t});if(!f)return jsx("div",{ref:_,style:S,children:t});let d=t?.props??{};return jsx(Nt,{slotId:e,resetKey:L,fallback:jsx("div",{ref:_,style:S,children:t}),children:jsx(Un,{component:f,containerRef:_,wrapperStyle:S,hostProps:d})})}var Er=new Set;function Dn(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 Ar(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&Ar(n.children,t);}),t}function zn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(Ot(r,e),s==="direct")return jsx(_r,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let g=at(e),{baseUrl:f,apiKey:x,appId:T}=Z(),_=useRef(null),R=useRef(false),k=useRef(null),m=useRef(i);m.current=i;let I=useRef(t);I.current=t;let C=useRef(n);C.current=n,useEffect(()=>{if(typeof process<"u")return;let S=Ar(r),h=new Set(i?Object.keys(i):[]),d=[...S].filter(w=>!h.has(w));d.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
2
|
-
`+d.map(w=>` - ${w}`).join(`
|
|
3
|
-
|
|
1
|
+
import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as bn from'react-dom';import {createPortal}from'react-dom';import*as wn from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as vn from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var ve="__FORK_SHARED__";function Ct(){var t,r,n,o;let e=globalThis;return e[ve]||(e[ve]={}),(t=e[ve]).react||(t.react=Bt),(r=e[ve])["react-dom"]||(r["react-dom"]=bn),(n=e[ve])["react/jsx-runtime"]||(n["react/jsx-runtime"]=wn),(o=e[ve])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=vn),e[ve]}function $t(e){return Object.assign(Ct(),e)}var Sn="__fork_preview_session__";function at(e){return `${Sn}${e}`}var B={apiKey:null,session:null},Pt=new Set;function lt(){for(let e of Pt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function yr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function xn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(at(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:yr(r)?(window.sessionStorage.removeItem(at(e)),null):r}catch{return null}}function It(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(at(e),JSON.stringify(t)):window.sessionStorage.removeItem(at(e));}catch{}}function Pe(e){B.apiKey!==e&&(B.apiKey=e,B.session=xn(e),lt());}function me(){return B.session?yr(B.session)?(ct(null),null):B.session:null}function ct(e){B.session=e,B.apiKey&&It(B.apiKey,e),lt();}function Ue(e){B.session&&B.session.fork_id!==e&&(B.session={...B.session,fork_id:e},B.apiKey&&It(B.apiKey,B.session),lt());}function Se(e,t){B.session&&(B.session.container_id===e&&B.session.container_name===t||(B.session={...B.session,container_id:e,container_name:t??B.session.container_name??"Fork",fork_id:null},B.apiKey&&It(B.apiKey,B.session),lt()));}function Tt(e){return Pt.add(e),()=>{Pt.delete(e);}}var kr="__fork_preview";function br(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(kr);return typeof r=="string"&&r.length>0?r:null}function Ot(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 vr()!==null}function wr(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(kr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var xe=null,Mt=null,Be=null;function vr(){if(xe)return xe;let e=br();return e?(xe=e,wr(),xe):null}async function Ht(e,t){Pe(e);let r=me();if(r)return xe=null,r;let n=xe??br();if(xe=null,!n)return null;wr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return ct(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function Nt(e,t,r){Pe(e);let n=me();if(n)return n;if(!r.appId||!r.userId||!r.userHash||!Number.isInteger(r.forkUserId)||r.forkUserId<=0||!Number.isInteger(r.forkOperatorExpiresAt)||r.forkOperatorExpiresAt<=0||!r.forkOperatorHash)return null;let o=[e,t,r.appId,r.userId,r.forkUserId,r.forkOperatorExpiresAt].join(`
|
|
2
|
+
`);return Be&&Mt===o||(Mt=o,Be=(async()=>{try{let i=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({appId:r.appId,userId:r.userId,userHash:r.userHash,forkUserId:r.forkUserId,forkOperatorExpiresAt:r.forkOperatorExpiresAt,forkOperatorHash:r.forkOperatorHash})});if(i.status===204)return null;if(!i.ok){let p=await i.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${i.status}): ${p.error??"unknown"}`),null}let s=await i.json(),c={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return ct(c),c}catch(i){return console.warn("[fork-preview] auto admin activate threw",i),null}finally{Mt=null,Be=null;}})()),Be}function _n(){return me()}function Rn(){return null}function dt(){return useSyncExternalStore(Tt,_n,Rn)}function K(){let e=me();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function ut(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[c,p]of Object.entries(i.modules)){let m=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:m,legacyModuleUrl:f,bundleUrl:p.bundleUrl??m,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var En="fork:manifest:v1";function Lt(e,t,r){return `${En}:${e}:${t}:${r}`}function An(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Lt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Cn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Lt(e,t,r),JSON.stringify(n));}catch{}}function $n(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Lt(e,t,r));}catch{}}function Pn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var Fr=createContext(null);function De(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Mn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:De(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>De(e,i)):[]};return r}function Sr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:De(e,c),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function xr(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:De(e,i),cssUrls:(o.cssUrls??[]).map(s=>De(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function On(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=useState(()=>(Pe(t),Ot(t))),[m,f]=useState({}),[g,I]=useState(s?{userId:s,userHash:void 0}:null),[E,R]=useState(!!s||p),[y,b]=useState({}),[M,A]=useState(!o),[H,T]=useState(0),[O,_]=useState(null),w=useRef(new Map),d=useRef(new Map),[S,C]=useState(0),$=useRef(new Set),u=useRef(new Map),l=useRef(void 0);Ct(),useEffect(()=>{return Ht(t,r).then(()=>{}),()=>{}},[]);let k=dt();useEffect(()=>{p||k||!o||!g?.userHash||!g.forkUserId||!g.forkOperatorExpiresAt||!g.forkOperatorHash||Nt(t,r,{appId:o,userId:g.userId,userHash:g.userHash,forkUserId:g.forkUserId,forkOperatorExpiresAt:g.forkOperatorExpiresAt,forkOperatorHash:g.forkOperatorHash});},[t,o,g?.forkOperatorExpiresAt,g?.forkOperatorHash,g?.forkUserId,g?.userHash,g?.userId,r,p,k?.preview_session_id]),i&&l.current!==i&&($t(i),l.current=i),useEffect(()=>{c&&(p||(R(false),fetch(c,{credentials:"include"}).then(F=>{if(!F.ok)throw new Error(`Auth endpoint returned ${F.status}`);return F.json()}).then(F=>{if(!F.userId||typeof F.userId!="string")throw new Error("authUrl response must include userId");let x=F.forkUserId??F.fork_user_id,N=typeof x=="number"?x:typeof x=="string"&&x.length>0?Number(x):void 0,ee=typeof F.forkOperatorHash=="string"?F.forkOperatorHash:typeof F.operatorHash=="string"?F.operatorHash:void 0,G=F.forkOperatorExpiresAt??F.fork_operator_expires_at??F.operatorExpiresAt,ae=typeof G=="number"?G:typeof G=="string"&&G.length>0?Number(G):void 0;I({userId:F.userId,userHash:typeof F.userHash=="string"?F.userHash:void 0,forkUserId:N&&Number.isInteger(N)&&N>0?N:void 0,forkOperatorExpiresAt:ae&&Number.isInteger(ae)&&ae>0?ae:void 0,forkOperatorHash:ee});}).catch(F=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",F.message);}).finally(()=>{R(true);})));},[c,p]),useEffect(()=>{!c&&s&&(I({userId:s,userHash:void 0}),R(true));},[s,c]);let j=g?.userId??"",Z=g?.userHash,D=k?"":j,W=k?void 0:Z,re=!!o,z=useCallback(async()=>{if(!re){_(null),b({}),A(true),T(x=>x+1);return}if(!E){A(false);return}if(!k&&!D||!o){_(null),b({}),A(true),T(x=>x+1);return}if(A(false),!k){try{let x=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});x&&(_(x.containerId),f(Sr(r,x,D,o)),b(xr(r,x)));}catch(x){console.error("[ForkProvider] Failed to fetch fork manifest:",x.message),_(null),f({}),b({});}finally{T(x=>x+1),A(true);}return}if(_(k.container_id??null),k.container_id){try{let x=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:k.container_id,extraHeaders:K()});x&&(f(Sr(r,x,D,o)),b(xr(r,x)));}catch(x){console.error("[ForkProvider] Failed to fetch preview container manifest:",x.message),f({}),b({});}finally{T(x=>x+1),A(true);}return}let F=new URLSearchParams({appId:o,userId:D});W&&F.set("userHash",W);try{let x=await fetch(`${r}/api/v1/boundaries/manifest?${F.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}});if(!x.ok)throw new Error(`${x.status}`);let N=await x.json();b(Mn(r,N));}catch(x){console.error("[ForkProvider] Failed to fetch module override manifest:",x.message),b({});}finally{T(x=>x+1),A(true);}},[t,o,r,E,re,W,D,k?.preview_session_id,k?.fork_id,k?.container_id]);useEffect(()=>{if(!D||o&&(!k||k.container_id))return;let F=new URLSearchParams({userId:D});W&&F.set("userHash",W),fetch(`${r}/api/v1/forks/active?${F.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}}).then(x=>{if(!x.ok)throw new Error(`${x.status}`);return x.json()}).then(x=>{x&&typeof x=="object"&&f(x);}).catch(()=>{});},[t,o,D,W,r,k?.preview_session_id,k?.fork_id]),useEffect(()=>{z();},[z]);let se=useCallback((F,x)=>{f(N=>({...N,[F]:x}));},[]),ie=useCallback(F=>{f(x=>{let N={...x};return delete N[F],N});},[]),pe=useCallback(F=>{$.current.add(F);},[]),ne=useCallback(F=>$.current.has(F)?($.current.delete(F),true):false,[]),xt=useCallback((F,x)=>{u.current.set(F,x);},[]),Xe=useCallback((F,x)=>u.current.get(F)!==x?false:(u.current.delete(F),true),[]),Me=useCallback(F=>{if(!o)return;let x=JSON.stringify(F);w.current.get(F.id)===x||d.current.get(F.id)?.signature===x||(d.current.set(F.id,{boundary:F,signature:x}),C(ee=>ee+1));},[o]);useEffect(()=>{if(!o||d.current.size===0)return;let F=setTimeout(()=>{let x=Array.from(d.current.values());x.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:x.map(N=>N.boundary)})}).then(N=>{if(!N.ok)throw new Error(`${N.status}`)}).then(()=>{for(let N of x)d.current.get(N.boundary.id)?.signature===N.signature&&(d.current.delete(N.boundary.id),w.current.set(N.boundary.id,N.signature));}).catch(N=>{console.error("[ForkProvider] Failed to register module boundaries:",N.message);});},50);return ()=>{clearTimeout(F);}},[t,o,r,S]);let de=useCallback(F=>y[F],[y]),Q=useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let F=new URLSearchParams({userId:D});W&&F.set("userHash",W);let x={Authorization:`Bearer ${t}`,...K()};o&&(x["X-Fork-App-Id"]=o);let N=await fetch(`${r}/api/v1/forks/all?${F.toString()}`,{method:"DELETE",headers:x});if(!N.ok){let G=await N.json().catch(()=>({}));throw new Error(G.error||`API error: ${N.status}`)}let ee=await N.json().catch(()=>({}));f({}),b({}),A(true),T(G=>G+1),$.current.clear(),u.current.clear();try{for(let G=sessionStorage.length-1;G>=0;G-=1){let ae=sessionStorage.key(G);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return ee},[t,o,r,W,D]);return jsx(Fr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:m,moduleOverridesEnabled:re,moduleManifestReady:M,moduleManifestVersion:H,currentContainerId:O,previewSession:k,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:pe,shouldSkipAnimation:ne,queueBoundaryAnimation:xt,consumeBoundaryAnimation:Xe,registerBoundary:Me,getBoundaryOverride:de,refreshModuleManifest:z,resetAllForks:Q},children:n})}function te(){let e=useContext(Fr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ft(e){return te().forks[e]}var ze=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function jt(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var Rr=new Set;function Er(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Bn(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Cr(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 Ar(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f++){let{rect:g,borderRadius:I}=e[f],E=g.left-.5,R=g.top-.5,y=g.width+1,b=g.height+1,M=Math.min(I+.5,y/2,b/2),A=Cr(E,R,y,b,M),H=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",H),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let O=document.createElementNS(t,"feGaussianBlur");O.setAttribute("in","SourceGraphic"),O.setAttribute("stdDeviation","8"),T.appendChild(O),o.appendChild(T);let _=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",_),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(E-200)),w.setAttribute("y",String(R-200)),w.setAttribute("width",String(y+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(E-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(y+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",A),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let C=document.createElementNS(t,"g");C.setAttribute("mask",`url(#${_})`),C.setAttribute("opacity","0");let $=document.createElementNS(t,"g");$.setAttribute("filter",`url(#${H})`);let u=document.createElementNS(t,"path");u.setAttribute("d",A),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),$.appendChild(u),C.appendChild($),n.appendChild(C);let l=document.createElementNS(t,"path");l.setAttribute("d",A),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=C;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let g=i[f],I=i[f+1],E=g.__group,R=I.getTotalLength(),y=g.getTotalLength();if(R<=0)continue;let b=R*.35;I.setAttribute("stroke-dasharray",`${b} ${R-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=y*.35;g.setAttribute("stroke-dasharray",`${M} ${y-M}`),g.setAttribute("stroke-dashoffset","0"),s.push(g.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(E.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(m);for(let g of s)try{g.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},m=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let m=c.left,f=c.top,g=c.width,I=c.height,E=Math.min(p,g/2,I/2),R=Cr(m,f,g,I,E),y=document.createElementNS(t,"path");y.setAttribute("d",R),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zn(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var Wn=Bt__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&zn(e.hostProps,t.hostProps)),Ut=class extends Bt__default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function $r({slotId:e,children:t,githubRepo:r,shared:n,events:o}){jt(t,e);let i=ft(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:m}=te(),[f,g]=useState(null),I=useRef(null),E=useRef(null),R=useRef(null),y=useRef(false),b=useRef(null),M=useRef(null),A=!!(n||o),H=useRef(null);A&&!H.current&&(H.current=new ze(e));let T=useRef(o);if(T.current=o,useEffect(()=>{if(A)return ()=>{H.current?.destroy(),H.current=null;}},[A,e]),A&&H.current&&n)for(let[S,C]of Object.entries(n))H.current.set(S,C);useEffect(()=>{if(!A)return;H.current||(H.current=new ze(e));let S=H.current,C=Object.keys(T.current||{}).map($=>S.on($,(...u)=>T.current?.[$]?.(...u)));return ()=>C.forEach($=>$())},[A,e]),useEffect(()=>{if(Rr.has(e))return;Rr.add(e);let S={id:e,appId:p,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify(S)}).catch(()=>{});},[e,s,c,r,p]);let O=i?.id||null;useEffect(()=>{if(i?.bundleUrl,I.current,E.current,!i?.bundleUrl||!O){return}let S=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,C=`__fork_animated_${e}`,$=sessionStorage.getItem(C),u=m(e),l=!u&&$!==O;if(u&&O&&sessionStorage.setItem(C,O),l&&E.current){let W=Er(E.current);R.current=W,y.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Bt__default,window.__FORK_REACT_DOM__=bn,window.__FORK_REACT_JSX__=wn;let k=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${k}`,Z=document.createElement("link");Z.rel="stylesheet",Z.href=j,Z.dataset.forkSlot=e,document.head.appendChild(Z);let D=document.createElement("script");return D.src=S+"?t="+k,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(E.current&&R.current&&y.current){let re=E.current.getBoundingClientRect(),z=E.current.cloneNode(true);z.style.position="fixed",z.style.top=`${re.top}px`,z.style.left=`${re.left}px`,z.style.width=`${re.width}px`,z.style.height=`${re.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(E.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=E.current.querySelectorAll("*"),pe=z.querySelectorAll("*");for(let ne=0;ne<ie.length;ne++)ie[ne].scrollTop!==0&&(pe[ne].scrollTop=ie[ne].scrollTop),ie[ne].scrollLeft!==0&&(pe[ne].scrollLeft=ie[ne].scrollLeft);b.current=z;}g(()=>W.default),I.current=O;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),Z.remove(),M.current&&(clearTimeout(M.current),M.current=null),b.current&&(b.current.remove(),b.current=null);}},[O,s,e]),useEffect(()=>{if(!y.current||!f||!E.current){`${e}${y.current}`,E.current;return}let S=R.current;if(!S){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!E.current)return;let C=Er(E.current),$=Bn(S,C),u=jn(S,C),l=b.current;if(`${e}${$.length}${u.length}`,u.length>0&&l){let k=Dn(u);M.current=setTimeout(()=>{M.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),k.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),k.remove(),b.current=null,$.length>0&&(Ar($));},j);},3500);}else l&&(l.remove(),b.current=null),$.length>0&&(Ar($));R.current=null,y.current=false,O&&(sessionStorage.setItem(`__fork_animated_${e}`,O),`${e}`);});});},[f]);let _={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:E,style:_,children:t});if(!f)return jsx("div",{ref:E,style:_,children:t});let d=t?.props??{};return jsx(Ut,{slotId:e,resetKey:O,fallback:jsx("div",{ref:E,style:_,children:t}),children:jsx(Wn,{component:f,containerRef:E,wrapperStyle:_,hostProps:d})})}var Ir=new Set;function Jn(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function Tr(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&Tr(n.children,t);}),t}function qn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(jt(r,e),s==="direct")return jsx($r,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let m=ft(e),{baseUrl:f,apiKey:g,appId:I}=te(),E=useRef(null),R=useRef(false),y=useRef(null),b=useRef(i);b.current=i;let M=useRef(t);M.current=t;let A=useRef(n);A.current=n,useEffect(()=>{if(typeof process<"u")return;let _=Tr(r),w=new Set(i?Object.keys(i):[]),d=[..._].filter(S=>!w.has(S));d.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
3
|
+
`+d.map(S=>` - ${S}`).join(`
|
|
4
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{Ir.has(e)||(Ir.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?Jn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,f,g,o,I]);let H=useCallback(_=>{let w=E.current;if(w?.contentWindow&&R.current){let d=b.current?Object.keys(b.current):[];w.contentWindow.postMessage({type:"slot:props",props:_,callbackNames:d},"*"),y.current=null;}else y.current=_;},[]),T=useCallback((_,w)=>{let d=A.current;return !d||d.length===0?false:d.some(S=>{let[C,$]=S.split(" "),u=w.split("?")[0];return _.toUpperCase()===C.toUpperCase()&&u.startsWith($)})},[]);if(useEffect(()=>{if(!m?.bundleUrl)return;let _=async w=>{if(w.source===E.current?.contentWindow){if(w.data?.type==="slot:ready")R.current=true,E.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,y.current?H(y.current):H(M.current||{});else if(w.data?.type==="slot:event"){let d=w.data.event;d?.navigate&&(window.location.hash=d.navigate);}else if(w.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(w.data.text).catch(d=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,d.message);});else if(w.data?.type==="slot:callback"){let{name:d,args:S}=w.data,C=b.current?.[d];C?(C(...S||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${d}`);}else if(w.data?.type==="slot:fetch"){let{id:d,method:S,url:C,body:$}=w.data,u=E.current?.contentWindow;if(!u)return;let l=S||"GET";if(!T(l,C)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${d}: ${l} ${C} \u2014 not in allowedFetches`),u.postMessage({type:"slot:fetch-response",id:d,error:`Fetch not allowed: ${l} ${C}`},"*");return}try{let k={method:l};$&&l!=="GET"&&(k.headers={"Content-Type":"application/json"},k.body=JSON.stringify($));let j=await fetch(C,k),Z=await j.json();`${e}${d}${j.status}`,u.postMessage({type:"slot:fetch-response",id:d,data:Z,status:j.status},"*");}catch(k){console.error(`[ForkSlot:${e}] fetch #${d} failed:`,k.message),u.postMessage({type:"slot:fetch-response",id:d,error:k.message},"*");}}}};return window.addEventListener("message",_),()=>{window.removeEventListener("message",_),R.current=false;}},[m?.bundleUrl,e,H,T]),useEffect(()=>{m?.bundleUrl&&R.current&&H(t||{});},[t,m?.bundleUrl,H]),!m||m.status!=="complete"||!m.bundleUrl)return `${e}${m?.status||"none"}${m?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${m.bundleUrl}`;let O=`${f}${m.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:E,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 gt({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}function zt({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(gt,{style:{width:24,height:24}})})}var oo={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},so={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},io={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},ao={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Kt(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 jr({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
|
|
4
5
|
@keyframes __fork-spin {
|
|
5
6
|
from { transform: rotate(0deg); }
|
|
6
7
|
to { transform: rotate(360deg); }
|
|
@@ -18,7 +19,7 @@ import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,
|
|
|
18
19
|
.__fork-stream::-webkit-scrollbar-thumb:hover {
|
|
19
20
|
background: rgba(255, 255, 255, 0.3);
|
|
20
21
|
}
|
|
21
|
-
`}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),c=Qn[r.type]||Code,p=eo[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");c=to[g]||Wrench,p=ro[g]||"#fbbf24";}return s?c=Loader2:!o&&r.type==="status"&&(c=Check,p="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Dt(r)})]},n)})]})]})}var Hr=35,uo="Working on Feature",fo="Built Custom Feature",jr=360,ft=350;function po(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 go(e){return e.length<=Hr?e:e.slice(0,Hr-3).trimEnd()+"..."}function mo({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let g=e[p];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){c=go(Dt(g));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function ho({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function pt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:g,onClose:f,baseUrl:x,apiKey:T,userId:_,userHash:R,appId:k,embedded:m=false}){let[I,C]=useState(""),[N,$]=useState([]),[L,S]=useState(false),[h,d]=useState(false),[w,E]=useState(false),[A,u]=useState(false),[l,y]=useState(false),[j,q]=useState(false),[D,W]=useState(false),[Q,z]=useState(false),[se,ie]=useState(false),[pe,ee]=useState(null),[kt,Je]=useState(false),[Ee,de]=useState([]),[te,P]=useState(null),[F,O]=useState(false),[re,ne]=useState(false),[Ae,Qt]=useState(false),[tn,er]=useState(null),[J,Ve]=useState(null),[rn,tr]=useState(false),[bt,qe]=useState(false),[me,$e]=useState(""),wt=useRef(null),[rr,he]=useState(null),[nn,Pe]=useState(false),[Fe,nr]=useState(null),[vt,St]=useState([]),[Y,Me]=useState(null),[ae,Te]=useState(false),Ie=useRef(false),xt=useRef(null),Xe=useRef(null),{resetAllForks:on,previewSession:K,currentContainerId:sn}=Z(),ye=K?.container_id??sn,Ye=!!(K&&nn),ue=Fe!==null,or=useRef(f);useEffect(()=>{or.current=f;});let Ft=useRef(null),Ze=useRef(false),sr=typeof window<"u"&&"documentPictureInPicture"in window,an=async()=>{if(!(!sr||ue))try{let a=await window.documentPictureInPicture.requestWindow({width:jr,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let v=document.adoptedStyleSheets??[];v.length>0&&(a.document.adoptedStyleSheets=[...v]);}catch{}a.addEventListener("pagehide",()=>{Ft.current=null,nr(null),Ze.current||or.current(),Ze.current=!1;},{once:!0}),Ft.current=a,nr(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},ln=()=>{Fe&&(Ze.current=true,Fe.close());};useEffect(()=>()=>{Ze.current=true,Ft.current?.close();},[]);let le=i??o??"",ir=(s||le).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),Qe=useRef(""),ar=()=>{let a={Authorization:`Bearer ${T}`,...G()};return k&&(a["X-Fork-App-Id"]=k),!K&&_&&(a["X-Fork-User-Id"]=_),!K&&R&&(a["X-Fork-User-Hash"]=R),a},et=m?true:h&&!w,cn=r.find(a=>{let v=a.data;return a.type==="status"&&v.summary})?.data?.summary||t?.summary||uo,ke=r.find(a=>{let v=a.data;return (a.type==="status"||a.type==="complete")&&typeof v?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(c==="none"){S(true);return}if(!x||!T)return;if(!Y){$([]),S(true);return}let a=new AbortController;return fetch(`${x}/api/v1/forks/${encodeURIComponent(Y)}/messages`,{headers:ar(),signal:a.signal}).then(v=>v.ok?v.json():[]).then(v=>{if(a.signal.aborted)return;let M=[];for(let X of v){let _t=X.forkId??Y;X.role==="user"?M.push({type:"user",text:X.content,forkId:_t}):M.push({type:"applied",text:X.content,forkId:_t});}$(M),S(true);}).catch(()=>{a.signal.aborted||S(true);}),()=>{a.abort();}},[T,k,x,c,Y,K?.fork_id,K?.preview_session_id,R,_,t?.id,t?.completedAt]),useEffect(()=>{if(c==="none"||!x||!T||!F)return;if(!te){St([]);return}let a=new AbortController,v=new URLSearchParams({container_id:te});return fetch(`${x}/api/v1/forks?${v.toString()}`,{headers:ar(),signal:a.signal}).then(M=>M.ok?M.json():{forks:[]}).then(M=>{a.signal.aborted||St(M.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[T,k,x,c,te,F,t?.id,t?.completedAt,K?.fork_id,K?.preview_session_id,R,_]),useEffect(()=>{e==="complete"&&z(false);},[e]),useEffect(()=>{if(m&&c==="none"){de([]),P(null),O(true),Pe(false);return}if(K){let a=false;return O(false),Pe(false),he(null),fetch(`${x}/api/v1/preview/${encodeURIComponent(K.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${T}`,...G()}}).then(v=>{if(!v.ok)throw new Error(`${v.status}`);return v.json()}).then(v=>{a||(de(v.containers),P(v.currentContainerId??K.container_id??null),Pe(true));}).catch(v=>{a||(Pe(false),he(v instanceof Error?v.message:String(v)),ye?(de([{id:ye,name:K.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),P(ye)):(de([]),P(null)));}).finally(()=>{a||O(true);}),()=>{a=true;}}ye?(de([{id:ye,name:"Primary container",createdAt:""}]),P(ye)):(de([]),P(null)),O(true),Pe(false);},[T,ye,x,m,c,K?.container_id,K?.container_name,K?.preview_session_id]);let tt=useRef(void 0);useEffect(()=>{if(F){if(tt.current===void 0){tt.current=te;return}tt.current!==te&&(tt.current=te,$([]),S(false));}},[te,F]);let rt=useRef(null);useEffect(()=>{if(!re)return;let a=M=>{if(!rt.current)return;let X=typeof M.composedPath=="function"?M.composedPath():[];rt.current.contains(M.target)||X.includes(rt.current)||ne(false);},v=M=>{M.key==="Escape"&&ne(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",v,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",v,true);}},[re]),useEffect(()=>{re||(qe(false),$e(""));},[re]),useEffect(()=>{bt&&(wt.current?.focus(),wt.current?.select());},[bt]),useEffect(()=>{if(m)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[m]),useEffect(()=>{let a=m||ue;if((a||et)&&(e==="prompting"||e==="complete")){let v=setTimeout(()=>xt.current?.focus(),a?100:ft+100);return ()=>clearTimeout(v)}},[et,m,ue,e]),useEffect(()=>{if(e==="complete"&&Qe.current){let v=r.find(M=>M.type==="complete")?.data?.summary||t?.summary||fo;$(M=>M[M.length-1]?.type==="applied"?M:[...M,{type:"applied",text:v}]),C(""),setTimeout(()=>xt.current?.focus(),200);}},[e,ir,r,t?.summary]),useEffect(()=>{Xe.current&&(Xe.current.scrollTop=Xe.current.scrollHeight);},[N,e]);let lr=()=>{if(I.trim()){Qe.current=I.trim();let a={};ae?(a.forceNew=true,Ie.current=true):Y&&(a.forkId=Y),ae||$(v=>[...v,{type:"user",text:I.trim(),forkId:Y}]),p(I.trim(),le,te,a),C("");}};useEffect(()=>{if(Ie.current){if(e==="error"){Ie.current=false;return}t?.id&&(Me(t.id),Te(false),Ie.current=false);}},[t?.id,e]);let cr=a=>{ve(a.session.containerId,a.session.containerName),P(a.session.containerId),de(v=>{let M=v.filter(X=>X.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...M.map(X=>({...X,isPrimary:false}))]}),$([]),S(false),Qe.current="";},dn=async a=>{if(!(!K||!Ye||J)){Ve(a),he(null);try{let v=await fetch(`${x}/api/v1/preview/${encodeURIComponent(K.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${T}`,...G()}});if(!v.ok){let M=await v.json().catch(()=>({}));throw new Error(M.error||`API error: ${v.status}`)}cr(await v.json()),ne(!1);}catch(v){he(v instanceof Error?v.message:String(v));}finally{Ve(null);}}},dr=async a=>{if(!K||!Ye||J)return;let v=a.trim();if(v){Ve("__new__"),he(null);try{let M=await fetch(`${x}/api/v1/preview/${encodeURIComponent(K.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${T}`,...G()},body:JSON.stringify({name:v})});if(!M.ok){let X=await M.json().catch(()=>({}));throw new Error(X.error||`API error: ${M.status}`)}cr(await M.json()),qe(!1),$e(""),ne(!1);}catch(M){he(M instanceof Error?M.message:String(M));}finally{Ve(null);}}},un=async()=>{if(!(!g||se||!le)){ie(true);try{let a=await g(le);$(v=>{let M=[...v];return M.length>=2&&M[M.length-1]?.type==="applied"?M.splice(-2,2):M.length>=1&&M[M.length-1]?.type==="applied"&&M.splice(-1,1),M}),a?.removed&&$([]);}catch{}finally{ie(false);}}},ur=()=>{if(m){f();return}if(ue){Fe?.close();return}E(true),d(false),setTimeout(()=>f(),ft);},fn=m||ue?{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:jr,maxWidth:"100vw",background:"#ffffff",boxShadow:et?"-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:et?"translateX(0)":"translateX(100%)",transition:`transform ${ft}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${ft}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},fr=Ee.find(a=>a.id===te)?.name??(F?"Fork":"Loading..."),Le=ae?[]:Y?N.filter(a=>a.forkId===Y||a.forkId==null):N,Rt=jsxs(Fragment,{children:[jsx("style",{children:`
|
|
22
|
+
`}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),c=oo[r.type]||Code,p=so[r.type]||"#9ca3af";if(r.type==="tool_use"){let m=String(r.data.category||"");c=io[m]||Wrench,p=ao[m]||"#fbbf24";}return s?c=Loader2:!o&&r.type==="status"&&(c=Check,p="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Kt(r)})]},n)})]})]})}var Wr=35,ho="Working on Feature",yo="Built Custom Feature",Kr=360,yt=350;function ko(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function bo(e){return e.length<=Wr?e:e.slice(0,Wr-3).trimEnd()+"..."}function wo({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let m=e[p];if(m.type==="tool_use"||m.type==="build_start"||m.type==="build_complete"){c=bo(Kt(m));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function vo({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function kt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:m,onClose:f,baseUrl:g,apiKey:I,userId:E,userHash:R,appId:y,embedded:b=false}){let[M,A]=useState(""),[H,T]=useState([]),[O,_]=useState(false),[w,d]=useState(false),[S,C]=useState(false),[$,u]=useState(false),[l,k]=useState(false),[j,Z]=useState(false),[D,W]=useState(false),[re,z]=useState(false),[se,ie]=useState(false),[pe,ne]=useState(null),[xt,Xe]=useState(false),[Me,de]=useState([]),[Q,F]=useState(null),[x,N]=useState(false),[ee,G]=useState(false),[ae,rr]=useState(false),[sn,nr]=useState(null),[X$1,Ye]=useState(null),[an,or]=useState(false),[Ft,Ze]=useState(false),[ye,Oe]=useState(""),_t=useRef(null),[sr,ke]=useState(null),[ln,He]=useState(false),[Re,ir]=useState(null),[Ne,Qe]=useState([]),[Y,Ee]=useState(null),[le,Ae]=useState(false),Ce=useRef(false),Rt=useRef(null),et=useRef(null),{resetAllForks:cn,previewSession:J,currentContainerId:dn}=te(),be=J?.container_id??dn,tt=!!(J&&ln),ue=Re!==null,ar=useRef(f);useEffect(()=>{ar.current=f;});let Et=useRef(null),rt=useRef(false),lr=typeof window<"u"&&"documentPictureInPicture"in window,un=async()=>{if(!(!lr||ue))try{let a=await window.documentPictureInPicture.requestWindow({width:Kr,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let h=document.adoptedStyleSheets??[];h.length>0&&(a.document.adoptedStyleSheets=[...h]);}catch{}a.addEventListener("pagehide",()=>{Et.current=null,ir(null),rt.current||ar.current(),rt.current=!1;},{once:!0}),Et.current=a,ir(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},fn=()=>{Re&&(rt.current=true,Re.close());};useEffect(()=>()=>{rt.current=true,Et.current?.close();},[]);let ge=i??o??"",cr=(s||ge).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),nt=useRef(""),dr=()=>{let a={Authorization:`Bearer ${I}`,...K()};return y&&(a["X-Fork-App-Id"]=y),!J&&E&&(a["X-Fork-User-Id"]=E),!J&&R&&(a["X-Fork-User-Hash"]=R),a},ot=b?true:w&&!S,pn=r.find(a=>{let h=a.data;return a.type==="status"&&h.summary})?.data?.summary||t?.summary||ho,we=r.find(a=>{let h=a.data;return (a.type==="status"||a.type==="complete")&&typeof h?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(c==="none"){_(true);return}if(!g||!I)return;if(!Y){T([]),_(true);return}let a=new AbortController;return fetch(`${g}/api/v1/forks/${encodeURIComponent(Y)}/messages`,{headers:dr(),signal:a.signal}).then(h=>h.ok?h.json():[]).then(h=>{if(a.signal.aborted)return;let P=[];for(let q of h){let $e=q.forkId??Y;q.role==="user"?P.push({type:"user",text:q.content,forkId:$e}):P.push({type:"applied",text:q.content,forkId:$e});}T(P),_(true);}).catch(()=>{a.signal.aborted||_(true);}),()=>{a.abort();}},[I,y,g,c,Y,J?.fork_id,J?.preview_session_id,R,E,t?.id,t?.completedAt]),useEffect(()=>{if(c==="none"||!g||!I||!x)return;if(!Q){Qe([]);return}let a=new AbortController,h=new URLSearchParams({container_id:Q});return fetch(`${g}/api/v1/forks?${h.toString()}`,{headers:dr(),signal:a.signal}).then(P=>P.ok?P.json():{forks:[]}).then(P=>{a.signal.aborted||Qe(P.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[I,y,g,c,Q,x,t?.id,t?.completedAt,J?.fork_id,J?.preview_session_id,R,E]),useEffect(()=>{e==="complete"&&z(false);},[e]);let ur=Ne.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!ur||!g||!I||!Q)return;let a=new URLSearchParams({container_id:Q}),h={Authorization:`Bearer ${I}`,...K()};y&&(h["X-Fork-App-Id"]=y);let q=setInterval(async()=>{try{let $e=await fetch(`${g}/api/v1/forks?${a.toString()}`,{headers:h});if(!$e.ok)return;let yn=await $e.json();Qe(yn.forks??[]);}catch{}},3e3);return ()=>clearInterval(q)},[ur,g,I,y,Q]),useEffect(()=>{if(b&&c==="none"){de([]),F(null),N(true),He(false);return}if(J){let a=false;return N(false),He(false),ke(null),fetch(`${g}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${I}`,...K()}}).then(h=>{if(!h.ok)throw new Error(`${h.status}`);return h.json()}).then(h=>{a||(de(h.containers),F(h.currentContainerId??J.container_id??null),He(true));}).catch(h=>{a||(He(false),ke(h instanceof Error?h.message:String(h)),be?(de([{id:be,name:J.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),F(be)):(de([]),F(null)));}).finally(()=>{a||N(true);}),()=>{a=true;}}be?(de([{id:be,name:"Primary container",createdAt:""}]),F(be)):(de([]),F(null)),N(true),He(false);},[I,be,g,b,c,J?.container_id,J?.container_name,J?.preview_session_id]);let st=useRef(void 0);useEffect(()=>{if(x){if(st.current===void 0){st.current=Q;return}st.current!==Q&&(st.current=Q,T([]),_(false));}},[Q,x]);let it=useRef(null);useEffect(()=>{if(!ee)return;let a=P=>{if(!it.current)return;let q=typeof P.composedPath=="function"?P.composedPath():[];it.current.contains(P.target)||q.includes(it.current)||G(false);},h=P=>{P.key==="Escape"&&G(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",h,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",h,true);}},[ee]),useEffect(()=>{ee||(Ze(false),Oe(""));},[ee]),useEffect(()=>{Ft&&(_t.current?.focus(),_t.current?.select());},[Ft]),useEffect(()=>{if(b)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[b]),useEffect(()=>{let a=b||ue;if((a||ot)&&(e==="prompting"||e==="complete")){let h=setTimeout(()=>Rt.current?.focus(),a?100:yt+100);return ()=>clearTimeout(h)}},[ot,b,ue,e]),useEffect(()=>{if(e==="complete"&&nt.current){let h=r.find(P=>P.type==="complete")?.data?.summary||t?.summary||yo;T(P=>P[P.length-1]?.type==="applied"?P:[...P,{type:"applied",text:h}]),A(""),setTimeout(()=>Rt.current?.focus(),200);}},[e,cr,r,t?.summary]),useEffect(()=>{et.current&&(et.current.scrollTop=et.current.scrollHeight);},[H,e]);let fr=()=>{if(M.trim()){nt.current=M.trim();let a={};le?(a.forceNew=true,Ce.current=true):Y&&(a.forkId=Y),le||T(h=>[...h,{type:"user",text:M.trim(),forkId:Y}]),p(M.trim(),ge,Q,a),A("");}};useEffect(()=>{if(Ce.current){if(e==="error"){Ce.current=false;return}t?.id&&(Ee(t.id),Ae(false),Ce.current=false);}},[t?.id,e]);let pr=a=>{Se(a.session.containerId,a.session.containerName),F(a.session.containerId),de(h=>{let P=h.filter(q=>q.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...P.map(q=>({...q,isPrimary:false}))]}),Ee(null),Ae(false),Ce.current=false,T([]),_(false),nt.current="";},gn=async a=>{if(!(!J||!tt||X$1)){Ye(a),ke(null);try{let h=await fetch(`${g}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${I}`,...K()}});if(!h.ok){let P=await h.json().catch(()=>({}));throw new Error(P.error||`API error: ${h.status}`)}pr(await h.json()),G(!1);}catch(h){ke(h instanceof Error?h.message:String(h));}finally{Ye(null);}}},gr=async a=>{if(!J||!tt||X$1)return;let h=a.trim();if(h){Ye("__new__"),ke(null);try{let P=await fetch(`${g}/api/v1/preview/${encodeURIComponent(J.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I}`,...K()},body:JSON.stringify({name:h})});if(!P.ok){let q=await P.json().catch(()=>({}));throw new Error(q.error||`API error: ${P.status}`)}pr(await P.json()),Ze(!1),Oe(""),G(!1);}catch(P){ke(P instanceof Error?P.message:String(P));}finally{Ye(null);}}},mn=async()=>{if(!(!m||se||!ge)){ie(true);try{let a=await m(ge);T(h=>{let P=[...h];return P.length>=2&&P[P.length-1]?.type==="applied"?P.splice(-2,2):P.length>=1&&P[P.length-1]?.type==="applied"&&P.splice(-1,1),P}),a?.removed&&T([]);}catch{}finally{ie(false);}}},mr=()=>{if(b){f();return}if(ue){Re?.close();return}C(true),d(false),setTimeout(()=>f(),yt);},hn=b||ue?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:Kr,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:ot?"translateX(0)":"translateX(100%)",transition:`transform ${yt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${yt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},hr=Me.find(a=>a.id===Q)?.name??(x?"Fork":"Loading..."),Le=le?[]:Y?H.filter(a=>a.forkId===Y||a.forkId==null):H,At=jsxs(Fragment,{children:[jsx("style",{children:`
|
|
22
23
|
@keyframes __fork-pulse {
|
|
23
24
|
0%, 100% { opacity: 1; }
|
|
24
25
|
50% { opacity: 0.5; }
|
|
@@ -40,5 +41,5 @@ import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,
|
|
|
40
41
|
scrollbar-width: thin;
|
|
41
42
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
42
43
|
}
|
|
43
|
-
`}),jsxs("div",{className:"__fork-panel",style:fn,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!kt&&confirm("Kill all forks in this container?")){Je(true);try{let v=await on();`${v?.deleted??0}`,St([]),Me(null),Te(!1),C("");}catch(v){console.error("[Fork] Reset failed:",v);}finally{Je(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(ct,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:cn}):Ee.length===0&&!Ye?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Ye?jsxs("div",{ref:rt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ne(a=>!a);},onMouseEnter:()=>Qt(true),onMouseLeave:()=>Qt(false),"aria-haspopup":"menu","aria-expanded":re,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Ae||re?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:fr}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:re?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),re&&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(a=>{let v=a.id===te,M=tn===a.id,X=J===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>er(a.id),onMouseLeave:()=>er(null),onClick:()=>{a.id!==te&&dn(a.id);},disabled:!!J,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:M?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:J?"default":"pointer",textAlign:"left",fontWeight:v?600:400,opacity:J&&!X?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:v&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:X?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),bt?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:wt,type:"text",value:me,placeholder:"Container name",disabled:J==="__new__",onChange:a=>$e(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),dr(me)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),qe(false),$e(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{dr(me);},disabled:!me.trim()||J==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!me.trim()||J==="__new__"?"#e5e7eb":"#1c4587",color:!me.trim()||J==="__new__"?"#9ca3af":"#ffffff",cursor:!me.trim()||J==="__new__"?"default":"pointer",flexShrink:0},children:J==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>tr(true),onMouseLeave:()=>tr(false),onClick:()=>{J||(he(null),$e(""),qe(true));},disabled:!!J,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:rn?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:J?"default":"pointer",textAlign:"left",opacity:J&&J!=="__new__"?.55:1},children:"+ New container"}),rr&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:rr})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:fr}),e==="running"&&jsx("span",{title:ke?`Estimated ~${ke} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ke?"#1c4587":"#9ca3af",backgroundColor:ke?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ke?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ke?`~${ke}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!m&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[sr&&jsx("button",{onClick:ue?ln:an,onMouseEnter:()=>y(true),onMouseLeave:()=>y(false),title:ue?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ue?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:ur,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:A?"#4b5563":"#9ca3af",backgroundColor:A?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:Xe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(Y||ae)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{Me(null),Te(false),Ie.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"}),le&&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 ${le}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:le})]})]}),!Y&&!ae&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),le&&jsx("button",{onClick:()=>{Me(null),Te(true);},title:`Start a new fork on ${le}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),vt.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),vt.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:vt.map(a=>{let v=a.summary||"Untitled fork";return jsxs("button",{onClick:()=>{Te(false),Me(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:M=>M.currentTarget.style.background="#fafafa",onMouseLeave:M=>M.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:v}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:po(a.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),ae&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),Y&&Le.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:Le.map((a,v)=>jsx("div",{style:{marginBottom:v<Le.length-1?10:0},children:a.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:a.text}),g&&v===Le.length-1&&e!=="running"&&jsxs("button",{onClick:M=>{M.stopPropagation(),un();},onMouseEnter:()=>ee(v),onMouseLeave:()=>ee(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:pe===v?"rgba(0,0,0,0.06)":"transparent",color:pe===v?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),pe===v&&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"})]})]})]})},v))}),e==="running"&&(Y||ae)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>z(!Q),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(mo,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:Q?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:Q?320:0,opacity:Q?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(Br,{events:r})})})]})}),e==="error"&&(Y||ae)&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let a=t?.prompt||Qe.current;a&&p(a,le);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&(Y||ae)&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:xt,value:I,onChange:a=>{C(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),lr()),a.key==="Escape"&&!m&&ur();},placeholder:Le.length>0&&!ae?"Ask for another change...":`Describe your ideal ${ir.toLowerCase()}...`,rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:lr,disabled:!I.trim(),onMouseEnter:()=>q(true),onMouseLeave:()=>q(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:I.trim()?1:.25,transform:j&&I.trim()?"scale(1.1)":"scale(1)",background:I.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:I.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return m?Rt:ue&&Fe?createPortal(Rt,Fe.document.body):jsx(ho,{children:Rt})}function Wr(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 Wt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=Z(),[g,f]=useState("idle"),[x,T]=useState(null),[_,R]=useState([]),[k,m]=useState(null),I=useRef(null),C=useCallback(()=>{f("prompting"),R([]),m(null),T(null);},[]),N=useCallback(()=>{f("idle"),I.current&&(I.current.close(),I.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(S=>S==="idle"?"prompting":S);},[s?.preview_session_id,s?.target.id,e]);let $=useCallback(async(S,h,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),R([]),m(null);let w;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...G()},body:JSON.stringify({prompt:S,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let q=await l.json().catch(()=>({}));throw new Error(q.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),w=await(await fetch(`${o}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...G()}})).json();}else if(d?.forkId){let u={prompt:S};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}else {let u={userId:r,prompt:S,boundaryId:e,appId:i};h&&(u.containerId=h),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}T(w);let E=new URLSearchParams({key:t});s?(E.set("previewSessionId",s.preview_session_id),E.set("previewForkId",w.id)):r&&E.set("userId",r),n&&E.set("userHash",n);let A=new EventSource(`${o}/api/v1/forks/${w.id}/events?${E.toString()}`);I.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(y=>[...y,l]),l.type==="complete"){let y=l.data;p(e,w.id),c().catch(()=>{}).finally(()=>{let j={...w,status:"complete",moduleUrl:y.moduleUrl,cssUrls:y.cssUrls,summary:y.summary,completedAt:new Date().toISOString()};T(j),f("complete"),A.close();});}else if(l.type==="error"){let y=l.data;m(y.error||"Unknown error"),f("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${t}`,...G()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${w.id}`,{headers:u}).then(l=>l.json()).then(l=>{T(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(m(l.error||"Fork generation failed"),f("error"));}).catch(()=>{m("Connection lost"),f("error");}),A.close();};}catch(w){m(w.message),f("error");}},[t,i,o,e,s,p,c,n,r]),L=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let S={userId:r,boundaryId:e,appId:i};n&&(S.userHash=n);let h=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(S)});if(!h.ok){let w=await h.json().catch(()=>({}));throw new Error(w.error||`API error: ${h.status}`)}let d=await h.json();return await c().catch(()=>{}),d.removed?(T(null),f("prompting")):d.fork&&(T(d.fork),f("complete")),d}catch(S){throw m(S.message),S}},[t,i,o,e,c,n,r]);return {state:g,fork:x,events:_,error:k,open:C,close:N,startFork:$,undoFork:L}}function Kr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Wt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function Kt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=Z(),[p,g]=useState("idle"),[f,x]=useState(null),[T,_]=useState([]),[R,k]=useState(null),m=useRef(null),I=useCallback(()=>{g("prompting"),_([]),k(null),x(null);},[]),C=useCallback(()=>{g("idle"),m.current&&(m.current.close(),m.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&g(L=>L==="idle"?"prompting":L);},[o?.preview_session_id,o?.target.kind]);let N=useCallback(async(L,S,h,d)=>{try{g("running"),_([]),k(null);let w;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...G()},body:JSON.stringify({prompt:L,...S?{slot_id:S}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let q=await l.json().catch(()=>({}));throw new Error(q.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),w=await(await fetch(`${n}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...G()}})).json();}else if(d?.forkId){let u={prompt:L};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}else {let u={userId:t,prompt:L};S&&(u.slotId=S),h&&(u.containerId=h),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}w=await l.json();}x(w);let E=new URLSearchParams({key:e});o?(E.set("previewSessionId",o.preview_session_id),E.set("previewForkId",w.id)):t&&E.set("userId",t),r&&E.set("userHash",r);let A=new EventSource(`${n}/api/v1/forks/${w.id}/events?${E.toString()}`);m.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(_(y=>[...y,l]),l.type==="complete"){let y=l.data,j={...w,status:"complete",bundleUrl:y.bundleUrl,summary:y.summary,completedAt:new Date().toISOString()};x(j),g("complete"),S&&y.bundleUrl&&i(S,j),A.close();}else if(l.type==="error"){let y=l.data;k(y.error||"Unknown error"),g("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...G()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${w.id}`,{headers:u}).then(l=>l.json()).then(l=>{x(l),l.status==="complete"?(g("complete"),S&&l.bundleUrl&&i(S,l)):l.status==="error"&&(k(l.error||"Fork generation failed"),g("error"));}).catch(()=>{k("Connection lost"),g("error");}),A.close();};}catch(w){k(w.message),g("error");}},[e,t,r,n,o,i]),$=useCallback(async L=>{try{let S={userId:t,slotId:L};r&&(S.userHash=r);let h=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(S)});if(!h.ok){let w=await h.json().catch(()=>({}));throw new Error(w.error||`API error: ${h.status}`)}let d=await h.json();return c(L),d.removed?(s(L),x(null),g("prompting")):d.fork&&(i(L,d.fork),x(d.fork)),d}catch(S){throw k(S.message),S}},[e,t,r,n,s,i]);return {state:p,fork:f,events:T,error:R,open:I,close:C,startFork:N,undoFork:$}}function Gr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=Kt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Gt(e){let t=Wr(e),r=Gr(),n=Kr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=Z(),g=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",x=t.id,T=t.title,_=useCallback((k,m,I,C)=>t.type==="slot"?r.submit(k,m??t.id,I,C):n.submit(k,I,C),[n,r,t]),R=useCallback(k=>t.type==="slot"?r.undo(k??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:x,targetLabel:T,historyMode:f,submit:_,undo:R,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:x,targetLabel:T,historyMode:f}:{targetId:x,targetLabel:T,historyMode:f},onSubmit:_,onUndo:R,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function ze(e){let{embedded:t}=e,r=Gt(e);return t?jsx(pt,{...r.panelProps,embedded:true}):r.isOpen?jsx(pt,{...r.panelProps}):jsx(Ht,{...r.buttonProps})}function vo({boundaryId:e,title:t}){return jsx(ze,{boundaryId:e,title:t})}function Vt(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 Vr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function qt(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function qr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Xr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yr(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Xt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f+=1){let{rect:x,borderRadius:T}=e[f],_=x.left-.5,R=x.top-.5,k=x.width+1,m=x.height+1,I=Math.min(T+.5,k/2,m/2),C=Yr(_,R,k,m,I),N=`__fork-glow-${f}`,$=document.createElementNS(t,"filter");$.setAttribute("id",N),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),$.appendChild(L),o.appendChild($);let S=`__fork-mask-${f}`,h=document.createElementNS(t,"mask");h.setAttribute("id",S),h.setAttribute("maskUnits","userSpaceOnUse"),h.setAttribute("x",String(_-200)),h.setAttribute("y",String(R-200)),h.setAttribute("width",String(k+400)),h.setAttribute("height",String(m+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(k+400)),d.setAttribute("height",String(m+400)),d.setAttribute("fill","white"),h.appendChild(d);let w=document.createElementNS(t,"path");w.setAttribute("d",C),w.setAttribute("fill","black"),h.appendChild(w),o.appendChild(h);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${S})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let x=i[f],T=i[f+1],_=x.__group;if(!_)continue;let R=T.getTotalLength(),k=x.getTotalLength();if(R<=0)continue;let m=R*.35;T.setAttribute("stroke-dasharray",`${m} ${R-m}`),T.setAttribute("stroke-dashoffset","0"),s.push(T.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=k*.35;x.setAttribute("stroke-dasharray",`${I} ${k-I}`),x.setAttribute("stroke-dashoffset","0"),s.push(x.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*k,offset:.06},{strokeDashoffset:-2*k,offset:.92},{strokeDashoffset:-2.25*k,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let x of s)try{x.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Zr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Yr(c.left,c.top,c.width,c.height,p)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var Ke=new Map,Ge=new Map,Yt=new Map;function Fo(e){for(let t of e)Ge.set(t,(Ge.get(t)??0)+1);}function Ro(e){if(!(typeof document>"u"))for(let t of e){let r=(Ge.get(t)??0)-1;if(r>0){Ge.set(t,r);continue}Ge.delete(t),Ke.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function _o(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function en(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 Co(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ke.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return Ke.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw Ke.delete(e),o});return Ke.set(e,n),n}function Eo(e){let t=Yt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Yt.delete(e),n});return Yt.set(e,r),r}async function Ao(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Co(i)));let o=await Eo(e.moduleUrl);return en(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 en(n,r)}function $o(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:g}=Z(),[f,x]=useState(null),[T,_]=useState(null),R=useRef(null),k=useRef(null),m=useRef(null),I=useRef(false),C=useRef(null),N=useRef(null),$=p(e.id),L=$?`override:${$.id}`:"original",S=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),C.current&&(C.current.remove(),C.current=null);},[]),useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,S]),useEffect(()=>{let h=$?.cssUrls??[];if(h.length!==0)return Fo(h),()=>Ro(h)},[$?.cssUrls.join("|")]),useEffect(()=>{if(o&&!i&&!f||k.current===L&&f)return;let h=false;return _(null),Ao($,e.original,e.exportName).then(d=>{if(!h){if($?.id&&g(e.id,$.id)&&R.current){let w=Vt(R.current);if(w){let E=qt(w);E.length>0&&(m.current=E,I.current=true,N.current&&(clearTimeout(N.current),N.current=null),C.current&&C.current.remove(),C.current=Vr(w));}}k.current=L,startTransition(()=>{x(()=>d);});}}).catch(d=>{h||_(_o(d));}),()=>{h=true;}},[g,L,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,f]),useEffect(()=>{if(!I.current||!f||!R.current)return;let h=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(h||!R.current)return;let d=m.current,w=Vt(R.current);if(m.current=null,I.current=false,!d||!w){C.current&&(C.current.remove(),C.current=null);return}let E=qt(w),A=qr(d,E),u=Xr(d,E),l=C.current;if(u.length>0&&l){let y=Zr(u);N.current=setTimeout(()=>{N.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),C.current===l&&(C.current=null),A.length>0&&Xt(A);},j);},3500);}else l&&(l.remove(),C.current===l&&(C.current=null)),A.length>0&&Xt(A);});}),()=>{h=true;}},[f]),T)throw T;return f?jsx("div",{ref:R,style:{display:"contents"},children:jsx(f,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Mo({slotId:e,title:t,slotLabel:r}){return jsx(ze,{slotId:e,title:t,slotLabel:r})}
|
|
44
|
-
export{
|
|
44
|
+
`}),jsxs("div",{className:"__fork-panel",style:hn,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!xt&&confirm("Kill all forks in this container?")){Xe(true);try{let h=await cn();`${h?.deleted??0}`,Qe([]),Ee(null),Ae(!1),A("");}catch(h){console.error("[Fork] Reset failed:",h);}finally{Xe(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(gt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:pn}):Me.length===0&&!tt?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):tt?jsxs("div",{ref:it,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{G(a=>!a);},onMouseEnter:()=>rr(true),onMouseLeave:()=>rr(false),"aria-haspopup":"menu","aria-expanded":ee,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:ae||ee?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:ee?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),ee&&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:[Me.map(a=>{let h=a.id===Q,P=sn===a.id,q=X$1===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>nr(a.id),onMouseLeave:()=>nr(null),onClick:()=>{a.id!==Q&&gn(a.id);},disabled:!!X$1,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:P?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:X$1?"default":"pointer",textAlign:"left",fontWeight:h?600:400,opacity:X$1&&!q?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:h&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:q?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Ft?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:_t,type:"text",value:ye,placeholder:"Container name",disabled:X$1==="__new__",onChange:a=>Oe(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),gr(ye)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Ze(false),Oe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{gr(ye);},disabled:!ye.trim()||X$1==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!ye.trim()||X$1==="__new__"?"#e5e7eb":"#1c4587",color:!ye.trim()||X$1==="__new__"?"#9ca3af":"#ffffff",cursor:!ye.trim()||X$1==="__new__"?"default":"pointer",flexShrink:0},children:X$1==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>or(true),onMouseLeave:()=>or(false),onClick:()=>{X$1||(ke(null),Oe(""),Ze(true));},disabled:!!X$1,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:an?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:X$1?"default":"pointer",textAlign:"left",opacity:X$1&&X$1!=="__new__"?.55:1},children:"+ New container"}),sr&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:sr})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),e==="running"&&jsx("span",{title:we?`Estimated ~${we} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:we?"#1c4587":"#9ca3af",backgroundColor:we?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:we?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:we?`~${we}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!b&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[lr&&jsx("button",{onClick:ue?fn:un,onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),title:ue?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ue?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:mr,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:$?"#4b5563":"#9ca3af",backgroundColor:$?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:et,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(Y||le)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{Ee(null),Ae(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 h=(Y?Ne.find(P=>P.id===Y)?.targetId:null)??ge;return h?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 ${h}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:h})]}):null})()]}),!Y&&!le&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),ge&&jsx("button",{onClick:()=>{Ee(null),Ae(true);},title:`Start a new fork on ${ge}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),Ne.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),Ne.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ne.map(a=>{let h=a.summary||"Untitled fork";return jsxs("button",{onClick:()=>{Ae(false),Ee(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:P=>P.currentTarget.style.background="#fafafa",onMouseLeave:P=>P.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:h}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:ko(a.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),le&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),Y&&Le.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:Le.map((a,h)=>jsx("div",{style:{marginBottom:h<Le.length-1?10:0},children:a.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:a.text}),m&&h===Le.length-1&&e!=="running"&&jsxs("button",{onClick:P=>{P.stopPropagation(),mn();},onMouseEnter:()=>ne(h),onMouseLeave:()=>ne(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:pe===h?"rgba(0,0,0,0.06)":"transparent",color:pe===h?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),pe===h&&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"})]})]})]})},h))}),e==="running"&&(Y||le)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>z(!re),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(wo,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:re?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:re?320:0,opacity:re?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(jr,{events:r})})})]})}),e==="error"&&(Y||le)&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let a=t?.prompt||nt.current;a&&p(a,ge);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&(Y||le)&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:Rt,value:M,onChange:a=>{A(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),fr()),a.key==="Escape"&&!b&&mr();},placeholder:Le.length>0&&!le?"Ask for another change...":`Describe your ideal ${cr.toLowerCase()}...`,rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:fr,disabled:!M.trim(),onMouseEnter:()=>Z(true),onMouseLeave:()=>Z(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:M.trim()?1:.25,transform:j&&M.trim()?"scale(1.1)":"scale(1)",background:M.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:M.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return b?At:ue&&Re?createPortal(At,Re.document.body):jsx(vo,{children:At})}function qr(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function Jt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=te(),[m,f]=useState("idle"),[g,I]=useState(null),[E,R]=useState([]),[y,b]=useState(null),M=useRef(null),A=useCallback(()=>{f("prompting"),R([]),b(null),I(null);},[]),H=useCallback(()=>{f("idle"),M.current&&(M.current.close(),M.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(_=>_==="idle"?"prompting":_);},[s?.preview_session_id,s?.target.id,e]);let T=useCallback(async(_,w,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),R([]),b(null);let S;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...K()},body:JSON.stringify({prompt:_,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Z=await l.json().catch(()=>({}));throw new Error(Z.error||`API error: ${l.status}`)}let k=await l.json();k.container_id&&Se(k.container_id,k.container_name),Ue(k.fork_id),S=await(await fetch(`${o}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...K()}})).json();}else if(d?.forkId){let u={prompt:_};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:r,prompt:_,boundaryId:e,appId:i};w&&(u.containerId=w),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}I(S);let C=new URLSearchParams({key:t});s?(C.set("previewSessionId",s.preview_session_id),C.set("previewForkId",S.id)):r&&C.set("userId",r),n&&C.set("userHash",n);let $=new EventSource(`${o}/api/v1/forks/${S.id}/events?${C.toString()}`);M.current=$,$.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(k=>[...k,l]),l.type==="complete"){let k=l.data;p(e,S.id),c().catch(()=>{}).finally(()=>{let j={...S,status:"complete",moduleUrl:k.moduleUrl,cssUrls:k.cssUrls,summary:k.summary,completedAt:new Date().toISOString()};I(j),f("complete"),$.close();});}else if(l.type==="error"){let k=l.data;b(k.error||"Unknown error"),f("error"),$.close();}}catch{}},$.onerror=()=>{let u={Authorization:`Bearer ${t}`,...K()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{I(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(b(l.error||"Fork generation failed"),f("error"));}).catch(()=>{b("Connection lost"),f("error");}),$.close();};}catch(S){b(S.message),f("error");}},[t,i,o,e,s,p,c,n,r]),O=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let _={userId:r,boundaryId:e,appId:i};n&&(_.userHash=n);let w=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(_)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return await c().catch(()=>{}),d.removed?(I(null),f("prompting")):d.fork&&(I(d.fork),f("complete")),d}catch(_){throw b(_.message),_}},[t,i,o,e,c,n,r]);return {state:m,fork:g,events:E,error:y,open:A,close:H,startFork:T,undoFork:O}}function Vr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Jt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function qt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=te(),[p,m]=useState("idle"),[f,g]=useState(null),[I,E]=useState([]),[R,y]=useState(null),b=useRef(null),M=useCallback(()=>{m("prompting"),E([]),y(null),g(null);},[]),A=useCallback(()=>{m("idle"),b.current&&(b.current.close(),b.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&m(O=>O==="idle"?"prompting":O);},[o?.preview_session_id,o?.target.kind]);let H=useCallback(async(O,_,w,d)=>{try{m("running"),E([]),y(null);let S;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...K()},body:JSON.stringify({prompt:O,..._?{slot_id:_}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Z=await l.json().catch(()=>({}));throw new Error(Z.error||`API error: ${l.status}`)}let k=await l.json();k.container_id&&Se(k.container_id,k.container_name),Ue(k.fork_id),S=await(await fetch(`${n}/api/v1/forks/${k.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...K()}})).json();}else if(d?.forkId){let u={prompt:O};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:t,prompt:O};_&&(u.slotId=_),w&&(u.containerId=w),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let k=await l.json().catch(()=>({}));throw new Error(k.error||`API error: ${l.status}`)}S=await l.json();}g(S);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 $=new EventSource(`${n}/api/v1/forks/${S.id}/events?${C.toString()}`);b.current=$,$.onmessage=u=>{try{let l=JSON.parse(u.data);if(E(k=>[...k,l]),l.type==="complete"){let k=l.data,j={...S,status:"complete",bundleUrl:k.bundleUrl,summary:k.summary,completedAt:new Date().toISOString()};g(j),m("complete"),_&&k.bundleUrl&&i(_,j),$.close();}else if(l.type==="error"){let k=l.data;y(k.error||"Unknown error"),m("error"),$.close();}}catch{}},$.onerror=()=>{let u={Authorization:`Bearer ${e}`,...K()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{g(l),l.status==="complete"?(m("complete"),_&&l.bundleUrl&&i(_,l)):l.status==="error"&&(y(l.error||"Fork generation failed"),m("error"));}).catch(()=>{y("Connection lost"),m("error");}),$.close();};}catch(S){y(S.message),m("error");}},[e,t,r,n,o,i]),T=useCallback(async O=>{try{let _={userId:t,slotId:O};r&&(_.userHash=r);let w=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(_)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return c(O),d.removed?(s(O),g(null),m("prompting")):d.fork&&(i(O,d.fork),g(d.fork)),d}catch(_){throw y(_.message),_}},[e,t,r,n,s,i]);return {state:p,fork:f,events:I,error:R,open:M,close:A,startFork:H,undoFork:T}}function Xr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=qt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Vt(e){let t=qr(e),r=Xr(),n=Vr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=te(),m=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",g=t.id,I=t.title,E=useCallback((y,b,M,A)=>t.type==="slot"?r.submit(y,b??t.id,M,A):n.submit(y,M,A),[n,r,t]),R=useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...m,target:t,targetId:g,targetLabel:I,historyMode:f,submit:E,undo:R,buttonProps:{onClick:m.open},panelProps:{state:m.state,fork:m.fork,events:m.events,error:m.error,...t.type==="slot"?{slotId:g,targetLabel:I,historyMode:f}:{targetId:g,targetLabel:I,historyMode:f},onSubmit:E,onUndo:R,onClose:m.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function Ge(e){let{embedded:t}=e,r=Vt(e);return t?jsx(kt,{...r.panelProps,embedded:true}):r.isOpen?jsx(kt,{...r.panelProps}):jsx(zt,{...r.buttonProps})}function Ro({boundaryId:e,title:t}){return jsx(Ge,{boundaryId:e,title:t})}function Yt(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Zr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function Zt(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Qr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function en(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function tn(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Qt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let f=0;f<e.length;f+=1){let{rect:g,borderRadius:I}=e[f],E=g.left-.5,R=g.top-.5,y=g.width+1,b=g.height+1,M=Math.min(I+.5,y/2,b/2),A=tn(E,R,y,b,M),H=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",H),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let O=document.createElementNS(t,"feGaussianBlur");O.setAttribute("in","SourceGraphic"),O.setAttribute("stdDeviation","8"),T.appendChild(O),o.appendChild(T);let _=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",_),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(E-200)),w.setAttribute("y",String(R-200)),w.setAttribute("width",String(y+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(E-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(y+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",A),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let C=document.createElementNS(t,"g");C.setAttribute("mask",`url(#${_})`),C.setAttribute("opacity","0");let $=document.createElementNS(t,"g");$.setAttribute("filter",`url(#${H})`);let u=document.createElementNS(t,"path");u.setAttribute("d",A),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),$.appendChild(u),C.appendChild($),n.appendChild(C);let l=document.createElementNS(t,"path");l.setAttribute("d",A),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=C;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let g=i[f],I=i[f+1],E=g.__group;if(!E)continue;let R=I.getTotalLength(),y=g.getTotalLength();if(R<=0)continue;let b=R*.35;I.setAttribute("stroke-dasharray",`${b} ${R-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=y*.35;g.setAttribute("stroke-dasharray",`${M} ${y-M}`),g.setAttribute("stroke-dashoffset","0"),s.push(g.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(E.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let c=false,p=()=>{if(c)return;c=true,clearTimeout(m);for(let g of s)try{g.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},m=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function rn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:c,borderRadius:p}of e){let m=document.createElementNS(t,"path");m.setAttribute("d",tn(c.left,c.top,c.width,c.height,p)),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),m.setAttribute("stroke-width","1.5"),m.setAttribute("stroke-dasharray","8 4"),m.setAttribute("stroke-linecap","round"),m.setAttribute("filter","url(#__fork-removed-shadow)"),m.setAttribute("opacity","0"),n.appendChild(m),m.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var qe=new Map,Ve=new Map,er=new Map;function Co(e){for(let t of e)Ve.set(t,(Ve.get(t)??0)+1);}function $o(e){if(!(typeof document>"u"))for(let t of e){let r=(Ve.get(t)??0)-1;if(r>0){Ve.set(t,r);continue}Ve.delete(t),qe.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Po(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function on(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function Io(e){if(!e||typeof document>"u")return Promise.resolve();let t=qe.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return qe.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw qe.delete(e),o});return qe.set(e,n),n}function To(e){let t=er.get(e);if(t)return t;let r=import(e).catch(n=>{throw er.delete(e),n});return er.set(e,r),r}async function Mo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Io(i)));let o=await To(e.moduleUrl);return on(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return on(n,r)}function Oo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:m}=te(),[f,g]=useState(null),[I,E]=useState(null),R=useRef(null),y=useRef(null),b=useRef(null),M=useRef(false),A=useRef(null),H=useRef(null),T=p(e.id),O=T?`override:${T.id}`:"original",_=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{H.current&&(clearTimeout(H.current),H.current=null),A.current&&(A.current.remove(),A.current=null);},[]),useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,_]),useEffect(()=>{let w=T?.cssUrls??[];if(w.length!==0)return Co(w),()=>$o(w)},[T?.cssUrls.join("|")]),useEffect(()=>{if(o&&!i&&!f||y.current===O&&f)return;let w=false;return E(null),Mo(T,e.original,e.exportName).then(d=>{if(!w){if(T?.id&&m(e.id,T.id)&&R.current){let S=Yt(R.current);if(S){let C=Zt(S);C.length>0&&(b.current=C,M.current=true,H.current&&(clearTimeout(H.current),H.current=null),A.current&&A.current.remove(),A.current=Zr(S));}}y.current=O,startTransition(()=>{g(()=>d);});}}).catch(d=>{w||E(Po(d));}),()=>{w=true;}},[m,O,o,i,s,T?.id,T?.moduleUrl,T?.integrity,T?.cssUrls.join("|"),e.exportName,e.original,f]),useEffect(()=>{if(!M.current||!f||!R.current)return;let w=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(w||!R.current)return;let d=b.current,S=Yt(R.current);if(b.current=null,M.current=false,!d||!S){A.current&&(A.current.remove(),A.current=null);return}let C=Zt(S),$=Qr(d,C),u=en(d,C),l=A.current;if(u.length>0&&l){let k=rn(u);H.current=setTimeout(()=>{H.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),k.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),k.remove(),A.current===l&&(A.current=null),$.length>0&&Qt($);},j);},3500);}else l&&(l.remove(),A.current===l&&(A.current=null)),$.length>0&&Qt($);});}),()=>{w=true;}},[f]),I)throw I;return f?jsx("div",{ref:R,style:{display:"contents"},children:jsx(f,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function No({slotId:e,title:t,slotLabel:r}){return jsx(Ge,{slotId:e,title:t,slotLabel:r})}
|
|
45
|
+
export{Ro as ForkBoundaryUI,zt as ForkButton,Ge as ForkChatInterface,kt as ForkPanel,On as ForkProvider,qn as ForkSlot,No as ForkUI,$n as clearCachedManifest,Oo as forkable,ut as loadManifest,Pn as manifestDiffers,An as readCachedManifest,$t as registerForkShared,Jt as useBoundaryFork,qt as useFork,Vt as useForkChatPanel,dt as usePreviewSession,Cn as writeCachedManifest};
|
package/package.json
CHANGED