diff --git a/apps/web/client/public/onlook-preload-script.js b/apps/web/client/public/onlook-preload-script.js index fca54bbf6c..01eed2556e 100644 --- a/apps/web/client/public/onlook-preload-script.js +++ b/apps/web/client/public/onlook-preload-script.js @@ -1,9 +1,9 @@ -var k4=Object.create;var{getPrototypeOf:U4,defineProperty:Je,getOwnPropertyNames:J4}=Object;var P4=Object.prototype.hasOwnProperty;var Kh=(r,t,i)=>{i=r!=null?k4(U4(r)):{};let o=t||!r||!r.__esModule?Je(i,"default",{value:r,enumerable:!0}):i;for(let n of J4(r))if(!P4.call(o,n))Je(o,n,{get:()=>r[n],enumerable:!0});return o};var vr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var j=(r,t)=>{for(var i in t)Je(r,i,{get:t[i],enumerable:!0,configurable:!0,set:(o)=>t[i]=()=>o})};var Pe=vr((rU,Xh)=>{function E4(r){var t=typeof r;return r!=null&&(t=="object"||t=="function")}Xh.exports=E4});var qh=vr((tU,Wh)=>{var L4=typeof global=="object"&&global&&global.Object===Object&&global;Wh.exports=L4});var Ee=vr((nU,Nh)=>{var K4=qh(),X4=typeof self=="object"&&self&&self.Object===Object&&self,W4=K4||X4||Function("return this")();Nh.exports=W4});var Sh=vr((iU,Vh)=>{var q4=Ee(),N4=function(){return q4.Date.now()};Vh.exports=N4});var Fh=vr((oU,Yh)=>{var V4=/\s/;function S4(r){var t=r.length;while(t--&&V4.test(r.charAt(t)));return t}Yh.exports=S4});var Gh=vr((eU,Qh)=>{var Y4=Fh(),F4=/^\s+/;function Q4(r){return r?r.slice(0,Y4(r)+1).replace(F4,""):r}Qh.exports=Q4});var Le=vr((lU,Ah)=>{var G4=Ee(),A4=G4.Symbol;Ah.exports=A4});var Hh=vr((cU,Rh)=>{var Bh=Le(),yh=Object.prototype,B4=yh.hasOwnProperty,y4=yh.toString,wn=Bh?Bh.toStringTag:void 0;function R4(r){var t=B4.call(r,wn),i=r[wn];try{r[wn]=void 0;var o=!0}catch(e){}var n=y4.call(r);if(o)if(t)r[wn]=i;else delete r[wn];return n}Rh.exports=R4});var Zh=vr((uU,Mh)=>{var H4=Object.prototype,M4=H4.toString;function Z4(r){return M4.call(r)}Mh.exports=Z4});var sh=vr((gU,dh)=>{var Ch=Le(),C4=Hh(),T4=Zh(),d4="[object Null]",s4="[object Undefined]",Th=Ch?Ch.toStringTag:void 0;function ra(r){if(r==null)return r===void 0?s4:d4;return Th&&Th in Object(r)?C4(r):T4(r)}dh.exports=ra});var t$=vr((mU,r$)=>{function ta(r){return r!=null&&typeof r=="object"}r$.exports=ta});var i$=vr((bU,n$)=>{var na=sh(),ia=t$(),oa="[object Symbol]";function ea(r){return typeof r=="symbol"||ia(r)&&na(r)==oa}n$.exports=ea});var c$=vr((vU,l$)=>{var la=Gh(),o$=Pe(),ca=i$(),e$=NaN,ua=/^[-+]0x[0-9a-f]+$/i,ga=/^0b[01]+$/i,ma=/^0o[0-7]+$/i,ba=parseInt;function va(r){if(typeof r=="number")return r;if(ca(r))return e$;if(o$(r)){var t=typeof r.valueOf=="function"?r.valueOf():r;r=o$(t)?t+"":t}if(typeof r!="string")return r===0?r:+r;r=la(r);var i=ga.test(r);return i||ma.test(r)?ba(r.slice(2),i?2:8):ua.test(r)?e$:+r}l$.exports=va});var Xe=vr((hU,g$)=>{var ha=Pe(),Ke=Sh(),u$=c$(),$a="Expected a function",xa=Math.max,fa=Math.min;function wa(r,t,i){var o,n,e,l,u,g,c=0,m=!1,v=!1,h=!0;if(typeof r!="function")throw TypeError($a);if(t=u$(t)||0,ha(i))m=!!i.leading,v="maxWait"in i,e=v?xa(u$(i.maxWait)||0,t):e,h="trailing"in i?!!i.trailing:h;function b(S){var A=o,tr=n;return o=n=void 0,c=S,l=r.apply(tr,A),l}function f(S){return c=S,u=setTimeout(O,t),m?b(S):l}function D(S){var A=S-g,tr=S-c,Ue=t-A;return v?fa(Ue,e-tr):Ue}function I(S){var A=S-g,tr=S-c;return g===void 0||A>=t||A<0||v&&tr>=e}function O(){var S=Ke();if(I(S))return J(S);u=setTimeout(O,D(S))}function J(S){if(u=void 0,h&&o)return b(S);return o=n=void 0,l}function q(){if(u!==void 0)clearTimeout(u);c=0,o=g=n=u=void 0}function E(){return u===void 0?l:J(Ke())}function K(){var S=Ke(),A=I(S);if(o=arguments,n=this,g=S,A){if(u===void 0)return f(g);if(v)return clearTimeout(u),u=setTimeout(O,t),b(g)}if(u===void 0)u=setTimeout(O,t);return l}return K.cancel=q,K.flush=E,K}g$.exports=wa});var m0=vr(($6)=>{var g0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");$6.encode=function(r){if(0<=r&&r{var b0=m0(),Me=5,v0=1<>1;return t?-i:i}z6.encode=function(t){var i="",o,n=w6(t);do{if(o=n&h0,n>>>=Me,n>0)o|=$0;i+=b0.encode(o)}while(n>0);return i};z6.decode=function(t,i,o){var n=t.length,e=0,l=0,u,g;do{if(i>=n)throw Error("Expected more digits in base 64 VLQ value.");if(g=b0.decode(t.charCodeAt(i++)),g===-1)throw Error("Invalid base64 digit: "+t.charAt(i-1));u=!!(g&$0),g&=h0,e=e+(g<{function D6(r,t,i){if(t in r)return r[t];else if(arguments.length===3)return i;else throw Error('"'+t+'" is a required argument.')}N6.getArg=D6;var f0=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,p6=/^data:.+\,.+$/;function kn(r){var t=r.match(f0);if(!t)return null;return{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}}N6.urlParse=kn;function yt(r){var t="";if(r.scheme)t+=r.scheme+":";if(t+="//",r.auth)t+=r.auth+"@";if(r.host)t+=r.host;if(r.port)t+=":"+r.port;if(r.path)t+=r.path;return t}N6.urlGenerate=yt;var I6=32;function j6(r){var t=[];return function(i){for(var o=0;oI6)t.pop();return e}}var Ze=j6(function(t){var i=t,o=kn(t);if(o){if(!o.path)return t;i=o.path}var n=N6.isAbsolute(i),e=[],l=0,u=0;while(!0)if(l=u,u=i.indexOf("/",l),u===-1){e.push(i.slice(l));break}else{e.push(i.slice(l,u));while(u=0;u--)if(g=e[u],g===".")e.splice(u,1);else if(g==="..")c++;else if(c>0)if(g==="")e.splice(u+1,c),c=0;else e.splice(u,2),c--;if(i=e.join("/"),i==="")i=n?"/":".";if(o)return o.path=i,yt(o);return i});N6.normalize=Ze;function w0(r,t){if(r==="")r=".";if(t==="")t=".";var i=kn(t),o=kn(r);if(o)r=o.path||"/";if(i&&!i.scheme){if(o)i.scheme=o.scheme;return yt(i)}if(i||t.match(p6))return t;if(o&&!o.host&&!o.path)return o.host=t,yt(o);var n=t.charAt(0)==="/"?t:Ze(r.replace(/\/+$/,"")+"/"+t);if(o)return o.path=n,yt(o);return n}N6.join=w0;N6.isAbsolute=function(r){return r.charAt(0)==="/"||f0.test(r)};function k6(r,t){if(r==="")r=".";r=r.replace(/\/$/,"");var i=0;while(t.indexOf(r+"/")!==0){var o=r.lastIndexOf("/");if(o<0)return t;if(r=r.slice(0,o),r.match(/^([^\/]+:\/)?\/*$/))return t;++i}return Array(i+1).join("../")+t.substr(r.length+1)}N6.relative=k6;var a0=function(){var r=Object.create(null);return!("__proto__"in r)}();function z0(r){return r}function U6(r){if(_0(r))return"$"+r;return r}N6.toSetString=a0?z0:U6;function J6(r){if(_0(r))return r.slice(1);return r}N6.fromSetString=a0?z0:J6;function _0(r){if(!r)return!1;var t=r.length;if(t<9)return!1;if(r.charCodeAt(t-1)!==95||r.charCodeAt(t-2)!==95||r.charCodeAt(t-3)!==111||r.charCodeAt(t-4)!==116||r.charCodeAt(t-5)!==111||r.charCodeAt(t-6)!==114||r.charCodeAt(t-7)!==112||r.charCodeAt(t-8)!==95||r.charCodeAt(t-9)!==95)return!1;for(var i=t-10;i>=0;i--)if(r.charCodeAt(i)!==36)return!1;return!0}function P6(r,t,i){var o=tt(r.source,t.source);if(o!==0)return o;if(o=r.originalLine-t.originalLine,o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0||i)return o;if(o=r.generatedColumn-t.generatedColumn,o!==0)return o;if(o=r.generatedLine-t.generatedLine,o!==0)return o;return tt(r.name,t.name)}N6.compareByOriginalPositions=P6;function E6(r,t,i){var o=r.originalLine-t.originalLine;if(o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0||i)return o;if(o=r.generatedColumn-t.generatedColumn,o!==0)return o;if(o=r.generatedLine-t.generatedLine,o!==0)return o;return tt(r.name,t.name)}N6.compareByOriginalPositionsNoSource=E6;function L6(r,t,i){var o=r.generatedLine-t.generatedLine;if(o!==0)return o;if(o=r.generatedColumn-t.generatedColumn,o!==0||i)return o;if(o=tt(r.source,t.source),o!==0)return o;if(o=r.originalLine-t.originalLine,o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0)return o;return tt(r.name,t.name)}N6.compareByGeneratedPositionsDeflated=L6;function K6(r,t,i){var o=r.generatedColumn-t.generatedColumn;if(o!==0||i)return o;if(o=tt(r.source,t.source),o!==0)return o;if(o=r.originalLine-t.originalLine,o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0)return o;return tt(r.name,t.name)}N6.compareByGeneratedPositionsDeflatedNoLine=K6;function tt(r,t){if(r===t)return 0;if(r===null)return 1;if(t===null)return-1;if(r>t)return 1;return-1}function X6(r,t){var i=r.generatedLine-t.generatedLine;if(i!==0)return i;if(i=r.generatedColumn-t.generatedColumn,i!==0)return i;if(i=tt(r.source,t.source),i!==0)return i;if(i=r.originalLine-t.originalLine,i!==0)return i;if(i=r.originalColumn-t.originalColumn,i!==0)return i;return tt(r.name,t.name)}N6.compareByGeneratedPositionsInflated=X6;function W6(r){return JSON.parse(r.replace(/^\)]}'[^\n]*\n/,""))}N6.parseSourceMapInput=W6;function q6(r,t,i){if(t=t||"",r){if(r[r.length-1]!=="/"&&t[0]!=="/")r+="/";t=r+t}if(i){var o=kn(i);if(!o)throw Error("sourceMapURL could not be parsed");if(o.path){var n=o.path.lastIndexOf("/");if(n>=0)o.path=o.path.substring(0,n+1)}t=w0(yt(o),t)}return Ze(t)}N6.computeSourceURL=q6});var O0=vr((s6)=>{var Ce=Zi(),Te=Object.prototype.hasOwnProperty,kt=typeof Map<"u";function nt(){this._array=[],this._set=kt?new Map:Object.create(null)}nt.fromArray=function(t,i){var o=new nt;for(var n=0,e=t.length;n=0)return i}else{var o=Ce.toSetString(t);if(Te.call(this._set,o))return this._set[o]}throw Error('"'+t+'" is not in the set.')};nt.prototype.at=function(t){if(t>=0&&t{var D0=Zi();function tz(r,t){var i=r.generatedLine,o=t.generatedLine,n=r.generatedColumn,e=t.generatedColumn;return o>i||o==i&&e>=n||D0.compareByGeneratedPositionsInflated(r,t)<=0}function Ci(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}Ci.prototype.unsortedForEach=function(t,i){this._array.forEach(t,i)};Ci.prototype.add=function(t){if(tz(this._last,t))this._last=t,this._array.push(t);else this._sorted=!1,this._array.push(t)};Ci.prototype.toArray=function(){if(!this._sorted)this._array.sort(D0.compareByGeneratedPositionsInflated),this._sorted=!0;return this._array};nz.MappingList=Ci});var qt="PENPAL_CHILD";var I4=Kh(Xe(),1);var aa=class extends Error{code;constructor(r,t){super(t);this.name="PenpalError",this.code=r}},Or=aa,za=(r)=>({name:r.name,message:r.message,stack:r.stack,penpalCode:r instanceof Or?r.code:void 0}),_a=({name:r,message:t,stack:i,penpalCode:o})=>{let n=o?new Or(o,t):Error(t);return n.name=r,n.stack=i,n},Oa=Symbol("Reply"),Da=class{value;transferables;#r=Oa;constructor(r,t){this.value=r,this.transferables=t?.transferables}},pa=Da,Jr="penpal",Ki=(r)=>{return typeof r==="object"&&r!==null},$$=(r)=>{return typeof r==="function"},Ia=(r)=>{return Ki(r)&&r.namespace===Jr},Nt=(r)=>{return r.type==="SYN"},Xi=(r)=>{return r.type==="ACK1"},an=(r)=>{return r.type==="ACK2"},x$=(r)=>{return r.type==="CALL"},f$=(r)=>{return r.type==="REPLY"},ja=(r)=>{return r.type==="DESTROY"},w$=(r,t=[])=>{let i=[];for(let o of Object.keys(r)){let n=r[o];if($$(n))i.push([...t,o]);else if(Ki(n))i.push(...w$(n,[...t,o]))}return i},ka=(r,t)=>{let i=r.reduce((o,n)=>{return Ki(o)?o[n]:void 0},t);return $$(i)?i:void 0},mt=(r)=>{return r.join(".")},m$=(r,t,i)=>({namespace:Jr,channel:r,type:"REPLY",callId:t,isError:!0,...i instanceof Error?{value:za(i),isSerializedErrorInstance:!0}:{value:i}}),Ua=(r,t,i,o)=>{let n=!1,e=async(l)=>{if(n)return;if(!x$(l))return;o?.(`Received ${mt(l.methodPath)}() call`,l);let{methodPath:u,args:g,id:c}=l,m,v;try{let h=ka(u,t);if(!h)throw new Or("METHOD_NOT_FOUND",`Method \`${mt(u)}\` is not found.`);let b=await h(...g);if(b instanceof pa)v=b.transferables,b=await b.value;m={namespace:Jr,channel:i,type:"REPLY",callId:c,value:b}}catch(h){m=m$(i,c,h)}if(n)return;try{o?.(`Sending ${mt(u)}() reply`,m),r.sendMessage(m,v)}catch(h){if(h.name==="DataCloneError")m=m$(i,c,h),o?.(`Sending ${mt(u)}() reply`,m),r.sendMessage(m);throw h}};return r.addMessageHandler(e),()=>{n=!0,r.removeMessageHandler(e)}},Ja=Ua,a$=crypto.randomUUID?.bind(crypto)??(()=>[,,,,].fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),Pa=Symbol("CallOptions"),Ea=class{transferables;timeout;#r=Pa;constructor(r){this.transferables=r?.transferables,this.timeout=r?.timeout}},La=Ea,Ka=new Set(["apply","call","bind"]),z$=(r,t,i=[])=>{return new Proxy(i.length?()=>{}:Object.create(null),{get(o,n){if(n==="then")return;if(i.length&&Ka.has(n))return Reflect.get(o,n);return z$(r,t,[...i,n])},apply(o,n,e){return r(i,e)}})},b$=(r)=>{return new Or("CONNECTION_DESTROYED",`Method call ${mt(r)}() failed due to destroyed connection`)},Xa=(r,t,i)=>{let o=!1,n=new Map,e=(g)=>{if(!f$(g))return;let{callId:c,value:m,isError:v,isSerializedErrorInstance:h}=g,b=n.get(c);if(!b)return;if(n.delete(c),i?.(`Received ${mt(b.methodPath)}() call`,g),v)b.reject(h?_a(m):m);else b.resolve(m)};return r.addMessageHandler(e),{remoteProxy:z$((g,c)=>{if(o)throw b$(g);let m=a$(),v=c[c.length-1],h=v instanceof La,{timeout:b,transferables:f}=h?v:{},D=h?c.slice(0,-1):c;return new Promise((I,O)=>{let J=b!==void 0?window.setTimeout(()=>{n.delete(m),O(new Or("METHOD_CALL_TIMEOUT",`Method call ${mt(g)}() timed out after ${b}ms`))},b):void 0;n.set(m,{methodPath:g,resolve:I,reject:O,timeoutId:J});try{let q={namespace:Jr,channel:t,type:"CALL",id:m,methodPath:g,args:D};i?.(`Sending ${mt(g)}() call`,q),r.sendMessage(q,f)}catch(q){O(new Or("TRANSMISSION_FAILED",q.message))}})},i),destroy:()=>{o=!0,r.removeMessageHandler(e);for(let{methodPath:g,reject:c,timeoutId:m}of n.values())clearTimeout(m),c(b$(g));n.clear()}}},Wa=Xa,qa=()=>{let r,t;return{promise:new Promise((o,n)=>{r=o,t=n}),resolve:r,reject:t}},Na=qa,Va=class extends Error{constructor(r){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${r}`)}},Vt=Va,We="deprecated-penpal",Sa=(r)=>{return Ki(r)&&"penpal"in r},Ya=(r)=>r.split("."),v$=(r)=>r.join("."),_$=(r)=>{return new Vt(`Unexpected message to translate: ${JSON.stringify(r)}`)},Fa=(r)=>{if(r.penpal==="syn")return{namespace:Jr,channel:void 0,type:"SYN",participantId:We};if(r.penpal==="ack")return{namespace:Jr,channel:void 0,type:"ACK2"};if(r.penpal==="call")return{namespace:Jr,channel:void 0,type:"CALL",id:r.id,methodPath:Ya(r.methodName),args:r.args};if(r.penpal==="reply")if(r.resolution==="fulfilled")return{namespace:Jr,channel:void 0,type:"REPLY",callId:r.id,value:r.returnValue};else return{namespace:Jr,channel:void 0,type:"REPLY",callId:r.id,isError:!0,...r.returnValueIsError?{value:r.returnValue,isSerializedErrorInstance:!0}:{value:r.returnValue}};throw _$(r)},Qa=(r)=>{if(Xi(r))return{penpal:"synAck",methodNames:r.methodPaths.map(v$)};if(x$(r))return{penpal:"call",id:r.id,methodName:v$(r.methodPath),args:r.args};if(f$(r))if(r.isError)return{penpal:"reply",id:r.callId,resolution:"rejected",...r.isSerializedErrorInstance?{returnValue:r.value,returnValueIsError:!0}:{returnValue:r.value}};else return{penpal:"reply",id:r.callId,resolution:"fulfilled",returnValue:r.value};throw _$(r)},Ga=({messenger:r,methods:t,timeout:i,channel:o,log:n})=>{let e=a$(),l,u=[],g=!1,c=w$(t),{promise:m,resolve:v,reject:h}=Na(),b=i!==void 0?setTimeout(()=>{h(new Or("CONNECTION_TIMEOUT",`Connection timed out after ${i}ms`))},i):void 0,f=()=>{for(let K of u)K()},D=()=>{if(g)return;u.push(Ja(r,t,o,n));let{remoteProxy:K,destroy:S}=Wa(r,o,n);u.push(S),clearTimeout(b),g=!0,v({remoteProxy:K,destroy:f})},I=()=>{let K={namespace:Jr,type:"SYN",channel:o,participantId:e};n?.("Sending handshake SYN",K);try{r.sendMessage(K)}catch(S){h(new Or("TRANSMISSION_FAILED",S.message))}},O=(K)=>{if(n?.("Received handshake SYN",K),K.participantId===l&&l!==We)return;if(l=K.participantId,I(),!(e>l||l===We))return;let A={namespace:Jr,channel:o,type:"ACK1",methodPaths:c};n?.("Sending handshake ACK1",A);try{r.sendMessage(A)}catch(tr){h(new Or("TRANSMISSION_FAILED",tr.message));return}},J=(K)=>{n?.("Received handshake ACK1",K);let S={namespace:Jr,channel:o,type:"ACK2"};n?.("Sending handshake ACK2",S);try{r.sendMessage(S)}catch(A){h(new Or("TRANSMISSION_FAILED",A.message));return}D()},q=(K)=>{n?.("Received handshake ACK2",K),D()},E=(K)=>{if(Nt(K))O(K);if(Xi(K))J(K);if(an(K))q(K)};return r.addMessageHandler(E),u.push(()=>r.removeMessageHandler(E)),I(),m},Aa=Ga,Ba=(r)=>{let t=!1,i;return(...o)=>{if(!t)t=!0,i=r(...o);return i}},ya=Ba,h$=new WeakSet,Ra=({messenger:r,methods:t={},timeout:i,channel:o,log:n})=>{if(!r)throw new Or("INVALID_ARGUMENT","messenger must be defined");if(h$.has(r))throw new Or("INVALID_ARGUMENT","A messenger can only be used for a single connection");h$.add(r);let e=[r.destroy],l=ya((c)=>{if(c){let m={namespace:Jr,channel:o,type:"DESTROY"};try{r.sendMessage(m)}catch(v){}}for(let m of e)m();n?.("Connection destroyed")}),u=(c)=>{return Ia(c)&&c.channel===o};return{promise:(async()=>{try{r.initialize({log:n,validateReceivedMessage:u}),r.addMessageHandler((v)=>{if(ja(v))l(!1)});let{remoteProxy:c,destroy:m}=await Aa({messenger:r,methods:t,timeout:i,channel:o,log:n});return e.push(m),c}catch(c){throw l(!0),c}})(),destroy:()=>{l(!0)}}},O$=Ra,Ha=class{#r;#o;#n;#t;#l;#i=new Set;#e;#c=!1;constructor({remoteWindow:r,allowedOrigins:t}){if(!r)throw new Or("INVALID_ARGUMENT","remoteWindow must be defined");this.#r=r,this.#o=t?.length?t:[window.origin]}initialize=({log:r,validateReceivedMessage:t})=>{this.#n=r,this.#t=t,window.addEventListener("message",this.#b)};sendMessage=(r,t)=>{if(Nt(r)){let i=this.#u(r);this.#r.postMessage(r,{targetOrigin:i,transfer:t});return}if(Xi(r)||this.#c){let i=this.#c?Qa(r):r,o=this.#u(r);this.#r.postMessage(i,{targetOrigin:o,transfer:t});return}if(an(r)){let{port1:i,port2:o}=new MessageChannel;this.#e=i,i.addEventListener("message",this.#g),i.start();let n=[o,...t||[]],e=this.#u(r);this.#r.postMessage(r,{targetOrigin:e,transfer:n});return}if(this.#e){this.#e.postMessage(r,{transfer:t});return}throw new Vt("Port is undefined")};addMessageHandler=(r)=>{this.#i.add(r)};removeMessageHandler=(r)=>{this.#i.delete(r)};destroy=()=>{window.removeEventListener("message",this.#b),this.#m(),this.#i.clear()};#v=(r)=>{return this.#o.some((t)=>t instanceof RegExp?t.test(r):t===r||t==="*")};#u=(r)=>{if(Nt(r))return"*";if(!this.#l)throw new Vt("Concrete remote origin not set");return this.#l==="null"&&this.#o.includes("*")?"*":this.#l};#m=()=>{this.#e?.removeEventListener("message",this.#g),this.#e?.close(),this.#e=void 0};#b=({source:r,origin:t,ports:i,data:o})=>{if(r!==this.#r)return;if(Sa(o))this.#n?.("Please upgrade the child window to the latest version of Penpal."),this.#c=!0,o=Fa(o);if(!this.#t?.(o))return;if(!this.#v(t)){this.#n?.(`Received a message from origin \`${t}\` which did not match allowed origins \`[${this.#o.join(", ")}]\``);return}if(Nt(o))this.#m(),this.#l=t;if(an(o)&&!this.#c){if(this.#e=i[0],!this.#e)throw new Vt("No port received on ACK2");this.#e.addEventListener("message",this.#g),this.#e.start()}for(let n of this.#i)n(o)};#g=({data:r})=>{if(!this.#t?.(r))return;for(let t of this.#i)t(r)}},D$=Ha,$U=class{#r;#o;#n=new Set;#t;constructor({worker:r}){if(!r)throw new Or("INVALID_ARGUMENT","worker must be defined");this.#r=r}initialize=({validateReceivedMessage:r})=>{this.#o=r,this.#r.addEventListener("message",this.#i)};sendMessage=(r,t)=>{if(Nt(r)||Xi(r)){this.#r.postMessage(r,{transfer:t});return}if(an(r)){let{port1:i,port2:o}=new MessageChannel;this.#t=i,i.addEventListener("message",this.#i),i.start(),this.#r.postMessage(r,{transfer:[o,...t||[]]});return}if(this.#t){this.#t.postMessage(r,{transfer:t});return}throw new Vt("Port is undefined")};addMessageHandler=(r)=>{this.#n.add(r)};removeMessageHandler=(r)=>{this.#n.delete(r)};destroy=()=>{this.#r.removeEventListener("message",this.#i),this.#l(),this.#n.clear()};#l=()=>{this.#t?.removeEventListener("message",this.#i),this.#t?.close(),this.#t=void 0};#i=({ports:r,data:t})=>{if(!this.#o?.(t))return;if(Nt(t))this.#l();if(an(t)){if(this.#t=r[0],!this.#t)throw new Vt("No port received on ACK2");this.#t.addEventListener("message",this.#i),this.#t.start()}for(let i of this.#n)i(t)}};var xU=class{#r;#o;#n=new Set;constructor({port:r}){if(!r)throw new Or("INVALID_ARGUMENT","port must be defined");this.#r=r}initialize=({validateReceivedMessage:r})=>{this.#o=r,this.#r.addEventListener("message",this.#t),this.#r.start()};sendMessage=(r,t)=>{this.#r?.postMessage(r,{transfer:t})};addMessageHandler=(r)=>{this.#n.add(r)};removeMessageHandler=(r)=>{this.#n.delete(r)};destroy=()=>{this.#r.removeEventListener("message",this.#t),this.#r.close(),this.#n.clear()};#t=({data:r})=>{if(!this.#o?.(r))return;for(let t of this.#n)t(r)}};var p$=["SCRIPT","STYLE","LINK","META","NOSCRIPT"],I$=new Set(["a","abbr","area","audio","b","bdi","bdo","br","button","canvas","cite","code","data","datalist","del","dfn","em","embed","h1","h2","h3","h4","h5","h6","i","iframe","img","input","ins","kbd","label","li","map","mark","meter","noscript","object","output","p","picture","progress","q","ruby","s","samp","script","select","slot","small","span","strong","sub","sup","svg","template","textarea","time","u","var","video","wbr"]);var KU={SCALE:0.7,PAN_POSITION:{x:175,y:100},URL:"http://localhost:3000/",ASPECT_RATIO_LOCKED:!1,DEVICE:"Custom:Custom",THEME:"system",ORIENTATION:"Portrait",MIN_DIMENSIONS:{width:"280px",height:"360px"},COMMANDS:{run:"bun run dev",build:"bun run build",install:"bun install"},IMAGE_FOLDER:"public",IMAGE_DIMENSION:{width:"100px",height:"100px"},FONT_FOLDER:"fonts",FONT_CONFIG:"app/fonts.ts",TAILWIND_CONFIG:"tailwind.config.ts",CHAT_SETTINGS:{showSuggestions:!0,autoApplyCode:!0,expandCodeBlocks:!1,showMiniChat:!0,maxImages:5},EDITOR_SETTINGS:{shouldWarnDelete:!1,enableBunReplace:!0,buildFlags:"--no-lint"}};var qe=["node_modules","dist","build",".git",".next"];var WU=[...qe,"static","out",".next-prod",".onlook","public/onlook-preload-script.js"],qU=[...qe,".next-prod"],NU=[...qe,"coverage"],Ma=[".jsx",".tsx"],Za=[".js",".ts",".mjs",".cjs"],VU=[...Ma,...Za];var FU={["en"]:"English",["ja"]:"日本語",["zh"]:"中文",["ko"]:"한국어"};var J$=Kh(Xe(),1);function Q(r){return document.querySelector(`[${"data-odid"}="${r}"]`)}function Ne(r,t=!1){let i=`[${"data-odid"}="${r}"]`;if(!t)return i;return Ca(i)}function Ca(r){return CSS.escape(r)}function Dt(r){return r&&r instanceof Node&&r.nodeType===Node.ELEMENT_NODE&&!p$.includes(r.tagName)&&!r.hasAttribute("data-onlook-ignore")&&r.style.display!=="none"}var Ta="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var j$=(r=21)=>{let t="",i=r|0;while(i--)t+=Ta[Math.random()*64|0];return t};function Pr(r){let t=r.getAttribute("data-odid");if(!t)t=`odid-${j$()}`,r.setAttribute("data-odid",t);return t}function Qr(r){return r.getAttribute("data-oid")}function Gr(r){return r.getAttribute("data-oiid")}function k$(r,t){if(!ar)return;ar.onDomProcessed({layerMap:Object.fromEntries(r),rootNode:t}).catch((i)=>{console.error("Failed to send DOM processed event:",i)})}function Ve(r){window._onlookFrameId=r}function St(){let r=window._onlookFrameId;if(!r)return console.warn("Frame id not found"),ar?.getFrameId().then((t)=>{Ve(t)}),"";return r}function Se(r){window._onlookBranchId=r}function zn(){let r=window._onlookBranchId;if(!r)return console.warn("Branch id not found"),ar?.getBranchId().then((t)=>{Se(t)}),"";return r}function da(r=document.body){if(!St())return console.warn("frameView id not found, skipping dom processing"),null;let i=zr(r);if(!i)return console.warn("Error building layer tree, root element is null"),null;let o=r.getAttribute("data-odid");if(!o)return console.warn("Root dom id not found"),null;let n=i.get(o);if(!n)return console.warn("Root node not found"),null;return k$(i,n),{rootDomId:o,layerMap:Array.from(i.entries())}}var Wi=J$.default(da,500),sa=[(r)=>{let t=r.parentElement;return t&&t.tagName.toLowerCase()==="svg"},(r)=>{return r.tagName.toLowerCase()==="next-route-announcer"},(r)=>{return r.tagName.toLowerCase()==="nextjs-portal"}];function zr(r){if(!Dt(r))return null;let t=new Map,i=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,{acceptNode:(e)=>{let l=e;if(sa.some((u)=>u(l)))return NodeFilter.FILTER_REJECT;return Dt(l)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),o=U$(r);o.children=[],t.set(o.domId,o);let n=i.nextNode();while(n){let e=U$(n);e.children=[];let l=n.parentElement;if(l){let u=l.getAttribute("data-odid");if(u){e.parent=u;let g=t.get(u);if(g&&g.children)g.children.push(e.domId)}}t.set(e.domId,e),n=i.nextNode()}return t}function U$(r){let t=Pr(r),i=Qr(r),o=Gr(r),n=Array.from(r.childNodes).map((g)=>g.nodeType===Node.TEXT_NODE?g.textContent:"").join(" ").trim().slice(0,500),e=window.getComputedStyle(r),l=r.getAttribute("data-ocname");return{domId:t,oid:i||null,instanceId:o||null,textContent:n||"",tagName:r.tagName.toLowerCase(),isVisible:e.visibility!=="hidden",component:l||null,frameId:St(),children:null,parent:null,dynamicType:null,coreElementType:null}}function Ye(r){throw Error(`Expected \`never\`, found: ${JSON.stringify(r)}`)}var P$=(r)=>JSON.parse(JSON.stringify(r));function E$(r){let t=K$(r),i=r6(r),o=t6(r);return{defined:{width:"auto",height:"auto",...i,...o},computed:t}}function L$(r){let t=Q(r);if(!t)return{};return K$(t)}function K$(r){return P$(window.getComputedStyle(r))}function r6(r){let t={},i=X$(r.style.cssText);return Object.entries(i).forEach(([o,n])=>{t[o]=n}),t}function t6(r){let t={},i=document.styleSheets;for(let o=0;ot[c]=m)}}catch(u){console.warn("Error",u)}}return t}function X$(r){let t={};return r.split(";").forEach((i)=>{if(i=i.trim(),!i)return;let[o,...n]=i.split(":");t[o?.trim()??""]=n.join(":").trim()}),t}var W$=(r,t)=>{let i=document.elementFromPoint(r,t);if(!i)return;let o=(e)=>{if(e?.shadowRoot){let l=e.shadowRoot.elementFromPoint(r,t);if(l==e)return e;else if(l?.shadowRoot)return o(l);else return l||e}else return e};return o(i)||i},lr=(r,t)=>{let i=r.parentElement,o=i?{domId:i.getAttribute("data-odid"),frameId:St(),branchId:zn(),oid:i.getAttribute("data-oid"),instanceId:i.getAttribute("data-oiid"),rect:i.getBoundingClientRect()}:null,n=r.getBoundingClientRect(),e=t?E$(r):null;return{domId:r.getAttribute("data-odid"),oid:r.getAttribute("data-oid"),frameId:St(),branchId:zn(),instanceId:r.getAttribute("data-oiid"),rect:n,tagName:r.tagName,parent:o,styles:e}};function qi(r){try{let t=r.getAttribute("data-onlook-drag-saved-style");if(t){let i=JSON.parse(t);for(let o in i)r.style[o]=i[o]}}catch(t){console.warn("Error restoring style",t)}}function q$(r){let t=r.parentElement;if(!t)return;return{type:"index",targetDomId:t.getAttribute("data-odid"),targetOid:Gr(t)||Qr(t)||null,index:Array.from(r.parentElement?.children||[]).indexOf(r),originalIndex:Array.from(r.parentElement?.children||[]).indexOf(r)}}var N$=(r)=>{let t=Array.from(r.childNodes).filter((i)=>i.nodeType===Node.TEXT_NODE).map((i)=>i.textContent);if(t.length===0)return;return t.join("")};var Ni=(r,t)=>{let i=Q(r)||document.body;return lr(i,t)},V$=(r,t,i)=>{let o=n6(r,t)||document.body;return lr(o,i)},n6=(r,t)=>{let i=document.elementFromPoint(r,t);if(!i)return;let o=(e)=>{if(e?.shadowRoot){let l=e.shadowRoot.elementFromPoint(r,t);if(l==e)return e;else if(l?.shadowRoot)return o(l);else return l||e}else return e};return o(i)||i},S$=(r,t,i)=>{let o=Q(r);if(!o){console.warn("Failed to updateElementInstanceId: Element not found");return}o.setAttribute("data-oiid",t),o.setAttribute("data-ocname",i)},Y$=(r)=>{let t=Q(r);if(!t?.parentElement)return null;return lr(t.parentElement,!1)},F$=(r)=>{let t=Q(r);if(!t)return 0;return t.children.length},Q$=(r)=>{let t=Q(r);if(!t)return null;return lr(t.offsetParent,!1)};function G$(r,t,i){let o=Q(r.domId);if(!o)return console.warn("Failed to find parent element",r.domId),null;let n=i6(t),e=new Set(i.map((c)=>c.domId)),l=Array.from(o.children).map((c,m)=>({element:c,index:m,domId:Pr(c)})).filter(({domId:c})=>e.has(c));if(l.length===0)return console.warn("No valid children found to group"),null;let u=Math.min(...l.map((c)=>c.index));return o.insertBefore(n,o.children[u]??null),l.forEach(({element:c})=>{let m=c.cloneNode(!0);m.setAttribute("data-onlook-inserted","true"),n.appendChild(m),c.style.display="none",B$(c)}),{domEl:lr(n,!0),newMap:zr(n)}}function A$(r,t){let i=Q(r.domId);if(!i)return console.warn(`Parent element not found: ${r.domId}`),null;let o;if(t.domId)o=Q(t.domId);else return console.warn("Container domId is required for ungrouping"),null;if(!o)return console.warn("Container element not found for ungrouping"),null;return Array.from(o.children).forEach((l)=>{i.appendChild(l)}),o.remove(),{domEl:lr(i,!0),newMap:zr(i)}}function i6(r){let t=document.createElement(r.tagName);return Object.entries(r.attributes).forEach(([i,o])=>{t.setAttribute(i,o)}),t.setAttribute("data-onlook-inserted","true"),t.setAttribute("data-odid",r.domId),t.setAttribute("data-oid",r.oid),t}function B$(r){r.removeAttribute("data-odid"),r.removeAttribute("data-oid"),r.removeAttribute("data-onlook-inserted");let t=Array.from(r.children);if(t.length===0)return;t.forEach((i)=>{B$(i)})}function Vi(r){let t=Q(r);if(!t)return console.warn("Element not found for domId:",r),null;return y$(t)}function y$(r){let t=Array.from(r.attributes).reduce((o,n)=>{return o[n.name]=n.value,o},{}),i=Gr(r)||Qr(r)||null;if(!i)return console.warn("Element has no oid"),null;return{oid:i,branchId:zn(),domId:Pr(r),tagName:r.tagName.toLowerCase(),children:Array.from(r.children).map((o)=>y$(o)).filter(Boolean),attributes:t,textContent:N$(r)||null,styles:{}}}function R$(r){let t=Q(r);if(!t)throw Error("Element not found for domId: "+r);let i=t.parentElement;if(!i)throw Error("Inserted element has no parent");let o=Gr(i)||Qr(i);if(!o)return console.warn("Parent element has no oid"),null;let n=Pr(i),e=Array.from(i.children).indexOf(t);if(e===-1)return{type:"append",targetDomId:n,targetOid:o};return{type:"index",targetDomId:n,targetOid:o,index:e,originalIndex:e}}function H$(r){let t=document.querySelector(`[${"data-odid"}="${r}"]`);if(!t)return console.warn("No element found",{domId:r}),{dynamicType:null,coreType:null};let i=t.getAttribute("data-onlook-dynamic-type")||null,o=t.getAttribute("data-onlook-core-element-type")||null;return{dynamicType:i,coreType:o}}function M$(r,t,i){let o=document.querySelector(`[${"data-odid"}="${r}"]`);if(o){if(t)o.setAttribute("data-onlook-dynamic-type",t);if(i)o.setAttribute("data-onlook-core-element-type",i)}}function Z$(){let t=document.body.querySelector(`[${"data-oid"}]`);if(t)return lr(t,!0);return null}var Sr=0,w=1,k=2,H=3,F=4,gr=5,Yt=6,er=7,fr=8,P=9,U=10,B=11,L=12,N=13,dr=14,hr=15,d=16,nr=17,ir=18,mr=19,wr=20,X=21,p=22,Z=23,xr=24,y=25;function cr(r){return r>=48&&r<=57}function Ir(r){return cr(r)||r>=65&&r<=70||r>=97&&r<=102}function Fi(r){return r>=65&&r<=90}function o6(r){return r>=97&&r<=122}function e6(r){return Fi(r)||o6(r)}function l6(r){return r>=128}function Yi(r){return e6(r)||l6(r)||r===95}function _n(r){return Yi(r)||cr(r)||r===45}function c6(r){return r>=0&&r<=8||r===11||r>=14&&r<=31||r===127}function On(r){return r===10||r===13||r===12}function Ar(r){return On(r)||r===32||r===9}function Dr(r,t){if(r!==92)return!1;if(On(t)||t===0)return!1;return!0}function Ft(r,t,i){if(r===45)return Yi(t)||t===45||Dr(t,i);if(Yi(r))return!0;if(r===92)return Dr(r,t);return!1}function Qi(r,t,i){if(r===43||r===45){if(cr(t))return 2;return t===46&&cr(i)?3:0}if(r===46)return cr(t)?2:0;if(cr(r))return 1;return 0}function Gi(r){if(r===65279)return 1;if(r===65534)return 1;return 0}var Fe=Array(128),u6=128,Dn=130,Qe=131,Ai=132,Ge=133;for(let r=0;rr.length)return!1;for(let n=t;n=0;t--)if(!Ar(r.charCodeAt(t)))break;return t+1}function pn(r,t){for(;t=55296&&t<=57343||t>1114111)t=65533;return String.fromCodePoint(t)}var Gt=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"];function At(r=null,t){if(r===null||r.length0?Gi(t.charCodeAt(0)):0,n=At(r.lines,i),e=At(r.columns,i),l=r.startLine,u=r.startColumn;for(let g=o;g{}){r=String(r||"");let i=r.length,o=At(this.offsetAndType,r.length+1),n=At(this.balance,r.length+1),e=0,l=-1,u=0,g=r.length;this.offsetAndType=null,this.balance=null,n.fill(0),t(r,(c,m,v)=>{let h=e++;if(o[h]=c<>Rr]}else if(r0(c))g=h,u=It[c]}),o[e]=Sr<e)n[c]=e}this.source=r,this.firstCharOffset=l===-1?0:l,this.tokenCount=e,this.offsetAndType=o,this.balance=n,this.reset(),this.next()}lookupType(r){if(r+=this.tokenIndex,r>Rr;return Sr}lookupTypeNonSC(r){for(let t=this.tokenIndex;t>Rr;if(i!==N&&i!==y){if(r--===0)return i}}return Sr}lookupOffset(r){if(r+=this.tokenIndex,r>Rr;if(i!==N&&i!==y){if(r--===0)return t-this.tokenIndex}}return Sr}lookupValue(r,t){if(r+=this.tokenIndex,r0)return r>Rr,this.tokenEnd=t&yr;else this.tokenIndex=this.tokenCount,this.next()}next(){let r=this.tokenIndex+1;if(r>Rr,this.tokenEnd=r&yr;else this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=Sr,this.tokenStart=this.tokenEnd=this.source.length}skipSC(){while(this.tokenType===N||this.tokenType===y)this.next()}skipUntilBalanced(r,t){let i=r,o=0,n=0;r:for(;i0?this.offsetAndType[i-1]&yr:this.firstCharOffset,t(this.source.charCodeAt(n))){case 1:break r;case 2:i++;break r;default:if(r0(this.offsetAndType[i]>>Rr))i=o}}this.skip(i-this.tokenIndex)}forEachToken(r){for(let t=0,i=this.firstCharOffset;t>Rr;i=e,r(l,o,e,t)}}dump(){let r=Array(this.tokenCount);return this.forEachToken((t,i,o,n)=>{r[n]={idx:n,type:Gt[t],chunk:this.source.substring(i,o),balance:this.balance[n]}}),r}}function bt(r,t){function i(v){return v=r.length){if(c{i=r!=null?k4(U4(r)):{};let o=t||!r||!r.__esModule?Je(i,"default",{value:r,enumerable:!0}):i;for(let n of J4(r))if(!P4.call(o,n))Je(o,n,{get:()=>r[n],enumerable:!0});return o};var vr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var j=(r,t)=>{for(var i in t)Je(r,i,{get:t[i],enumerable:!0,configurable:!0,set:(o)=>t[i]=()=>o})};var Pe=vr((rU,Xh)=>{function E4(r){var t=typeof r;return r!=null&&(t=="object"||t=="function")}Xh.exports=E4});var qh=vr((tU,Wh)=>{var L4=typeof global=="object"&&global&&global.Object===Object&&global;Wh.exports=L4});var Ee=vr((nU,Nh)=>{var K4=qh(),X4=typeof self=="object"&&self&&self.Object===Object&&self,W4=K4||X4||Function("return this")();Nh.exports=W4});var Sh=vr((iU,Vh)=>{var q4=Ee(),N4=function(){return q4.Date.now()};Vh.exports=N4});var Fh=vr((oU,Yh)=>{var V4=/\s/;function S4(r){var t=r.length;while(t--&&V4.test(r.charAt(t)));return t}Yh.exports=S4});var Gh=vr((eU,Qh)=>{var Y4=Fh(),F4=/^\s+/;function Q4(r){return r?r.slice(0,Y4(r)+1).replace(F4,""):r}Qh.exports=Q4});var Le=vr((lU,Ah)=>{var G4=Ee(),A4=G4.Symbol;Ah.exports=A4});var Hh=vr((cU,Rh)=>{var Bh=Le(),yh=Object.prototype,B4=yh.hasOwnProperty,y4=yh.toString,wn=Bh?Bh.toStringTag:void 0;function R4(r){var t=B4.call(r,wn),i=r[wn];try{r[wn]=void 0;var o=!0}catch(e){}var n=y4.call(r);if(o)if(t)r[wn]=i;else delete r[wn];return n}Rh.exports=R4});var Zh=vr((uU,Mh)=>{var H4=Object.prototype,M4=H4.toString;function Z4(r){return M4.call(r)}Mh.exports=Z4});var sh=vr((gU,dh)=>{var Ch=Le(),C4=Hh(),T4=Zh(),d4="[object Null]",s4="[object Undefined]",Th=Ch?Ch.toStringTag:void 0;function r6(r){if(r==null)return r===void 0?s4:d4;return Th&&Th in Object(r)?C4(r):T4(r)}dh.exports=r6});var t$=vr((mU,r$)=>{function t6(r){return r!=null&&typeof r=="object"}r$.exports=t6});var i$=vr((bU,n$)=>{var n6=sh(),i6=t$(),o6="[object Symbol]";function e6(r){return typeof r=="symbol"||i6(r)&&n6(r)==o6}n$.exports=e6});var c$=vr((vU,l$)=>{var l6=Gh(),o$=Pe(),c6=i$(),e$=NaN,u6=/^[-+]0x[0-9a-f]+$/i,g6=/^0b[01]+$/i,m6=/^0o[0-7]+$/i,b6=parseInt;function v6(r){if(typeof r=="number")return r;if(c6(r))return e$;if(o$(r)){var t=typeof r.valueOf=="function"?r.valueOf():r;r=o$(t)?t+"":t}if(typeof r!="string")return r===0?r:+r;r=l6(r);var i=g6.test(r);return i||m6.test(r)?b6(r.slice(2),i?2:8):u6.test(r)?e$:+r}l$.exports=v6});var Xe=vr((hU,g$)=>{var h6=Pe(),Ke=Sh(),u$=c$(),$6="Expected a function",x6=Math.max,f6=Math.min;function w6(r,t,i){var o,n,e,l,u,g,c=0,m=!1,v=!1,h=!0;if(typeof r!="function")throw TypeError($6);if(t=u$(t)||0,h6(i))m=!!i.leading,v="maxWait"in i,e=v?x6(u$(i.maxWait)||0,t):e,h="trailing"in i?!!i.trailing:h;function b(S){var A=o,tr=n;return o=n=void 0,c=S,l=r.apply(tr,A),l}function f(S){return c=S,u=setTimeout(O,t),m?b(S):l}function D(S){var A=S-g,tr=S-c,Ue=t-A;return v?f6(Ue,e-tr):Ue}function I(S){var A=S-g,tr=S-c;return g===void 0||A>=t||A<0||v&&tr>=e}function O(){var S=Ke();if(I(S))return J(S);u=setTimeout(O,D(S))}function J(S){if(u=void 0,h&&o)return b(S);return o=n=void 0,l}function q(){if(u!==void 0)clearTimeout(u);c=0,o=g=n=u=void 0}function E(){return u===void 0?l:J(Ke())}function K(){var S=Ke(),A=I(S);if(o=arguments,n=this,g=S,A){if(u===void 0)return f(g);if(v)return clearTimeout(u),u=setTimeout(O,t),b(g)}if(u===void 0)u=setTimeout(O,t);return l}return K.cancel=q,K.flush=E,K}g$.exports=w6});var m0=vr(($a)=>{var g0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");$a.encode=function(r){if(0<=r&&r{var b0=m0(),Me=5,v0=1<>1;return t?-i:i}za.encode=function(t){var i="",o,n=wa(t);do{if(o=n&h0,n>>>=Me,n>0)o|=$0;i+=b0.encode(o)}while(n>0);return i};za.decode=function(t,i,o){var n=t.length,e=0,l=0,u,g;do{if(i>=n)throw Error("Expected more digits in base 64 VLQ value.");if(g=b0.decode(t.charCodeAt(i++)),g===-1)throw Error("Invalid base64 digit: "+t.charAt(i-1));u=!!(g&$0),g&=h0,e=e+(g<{function Da(r,t,i){if(t in r)return r[t];else if(arguments.length===3)return i;else throw Error('"'+t+'" is a required argument.')}Na.getArg=Da;var f0=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,pa=/^data:.+\,.+$/;function kn(r){var t=r.match(f0);if(!t)return null;return{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}}Na.urlParse=kn;function yt(r){var t="";if(r.scheme)t+=r.scheme+":";if(t+="//",r.auth)t+=r.auth+"@";if(r.host)t+=r.host;if(r.port)t+=":"+r.port;if(r.path)t+=r.path;return t}Na.urlGenerate=yt;var Ia=32;function ja(r){var t=[];return function(i){for(var o=0;oIa)t.pop();return e}}var Ze=ja(function(t){var i=t,o=kn(t);if(o){if(!o.path)return t;i=o.path}var n=Na.isAbsolute(i),e=[],l=0,u=0;while(!0)if(l=u,u=i.indexOf("/",l),u===-1){e.push(i.slice(l));break}else{e.push(i.slice(l,u));while(u=0;u--)if(g=e[u],g===".")e.splice(u,1);else if(g==="..")c++;else if(c>0)if(g==="")e.splice(u+1,c),c=0;else e.splice(u,2),c--;if(i=e.join("/"),i==="")i=n?"/":".";if(o)return o.path=i,yt(o);return i});Na.normalize=Ze;function w0(r,t){if(r==="")r=".";if(t==="")t=".";var i=kn(t),o=kn(r);if(o)r=o.path||"/";if(i&&!i.scheme){if(o)i.scheme=o.scheme;return yt(i)}if(i||t.match(pa))return t;if(o&&!o.host&&!o.path)return o.host=t,yt(o);var n=t.charAt(0)==="/"?t:Ze(r.replace(/\/+$/,"")+"/"+t);if(o)return o.path=n,yt(o);return n}Na.join=w0;Na.isAbsolute=function(r){return r.charAt(0)==="/"||f0.test(r)};function ka(r,t){if(r==="")r=".";r=r.replace(/\/$/,"");var i=0;while(t.indexOf(r+"/")!==0){var o=r.lastIndexOf("/");if(o<0)return t;if(r=r.slice(0,o),r.match(/^([^\/]+:\/)?\/*$/))return t;++i}return Array(i+1).join("../")+t.substr(r.length+1)}Na.relative=ka;var a0=function(){var r=Object.create(null);return!("__proto__"in r)}();function z0(r){return r}function Ua(r){if(_0(r))return"$"+r;return r}Na.toSetString=a0?z0:Ua;function Ja(r){if(_0(r))return r.slice(1);return r}Na.fromSetString=a0?z0:Ja;function _0(r){if(!r)return!1;var t=r.length;if(t<9)return!1;if(r.charCodeAt(t-1)!==95||r.charCodeAt(t-2)!==95||r.charCodeAt(t-3)!==111||r.charCodeAt(t-4)!==116||r.charCodeAt(t-5)!==111||r.charCodeAt(t-6)!==114||r.charCodeAt(t-7)!==112||r.charCodeAt(t-8)!==95||r.charCodeAt(t-9)!==95)return!1;for(var i=t-10;i>=0;i--)if(r.charCodeAt(i)!==36)return!1;return!0}function Pa(r,t,i){var o=tt(r.source,t.source);if(o!==0)return o;if(o=r.originalLine-t.originalLine,o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0||i)return o;if(o=r.generatedColumn-t.generatedColumn,o!==0)return o;if(o=r.generatedLine-t.generatedLine,o!==0)return o;return tt(r.name,t.name)}Na.compareByOriginalPositions=Pa;function Ea(r,t,i){var o=r.originalLine-t.originalLine;if(o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0||i)return o;if(o=r.generatedColumn-t.generatedColumn,o!==0)return o;if(o=r.generatedLine-t.generatedLine,o!==0)return o;return tt(r.name,t.name)}Na.compareByOriginalPositionsNoSource=Ea;function La(r,t,i){var o=r.generatedLine-t.generatedLine;if(o!==0)return o;if(o=r.generatedColumn-t.generatedColumn,o!==0||i)return o;if(o=tt(r.source,t.source),o!==0)return o;if(o=r.originalLine-t.originalLine,o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0)return o;return tt(r.name,t.name)}Na.compareByGeneratedPositionsDeflated=La;function Ka(r,t,i){var o=r.generatedColumn-t.generatedColumn;if(o!==0||i)return o;if(o=tt(r.source,t.source),o!==0)return o;if(o=r.originalLine-t.originalLine,o!==0)return o;if(o=r.originalColumn-t.originalColumn,o!==0)return o;return tt(r.name,t.name)}Na.compareByGeneratedPositionsDeflatedNoLine=Ka;function tt(r,t){if(r===t)return 0;if(r===null)return 1;if(t===null)return-1;if(r>t)return 1;return-1}function Xa(r,t){var i=r.generatedLine-t.generatedLine;if(i!==0)return i;if(i=r.generatedColumn-t.generatedColumn,i!==0)return i;if(i=tt(r.source,t.source),i!==0)return i;if(i=r.originalLine-t.originalLine,i!==0)return i;if(i=r.originalColumn-t.originalColumn,i!==0)return i;return tt(r.name,t.name)}Na.compareByGeneratedPositionsInflated=Xa;function Wa(r){return JSON.parse(r.replace(/^\)]}'[^\n]*\n/,""))}Na.parseSourceMapInput=Wa;function qa(r,t,i){if(t=t||"",r){if(r[r.length-1]!=="/"&&t[0]!=="/")r+="/";t=r+t}if(i){var o=kn(i);if(!o)throw Error("sourceMapURL could not be parsed");if(o.path){var n=o.path.lastIndexOf("/");if(n>=0)o.path=o.path.substring(0,n+1)}t=w0(yt(o),t)}return Ze(t)}Na.computeSourceURL=qa});var O0=vr((sa)=>{var Ce=Zi(),Te=Object.prototype.hasOwnProperty,kt=typeof Map<"u";function nt(){this._array=[],this._set=kt?new Map:Object.create(null)}nt.fromArray=function(t,i){var o=new nt;for(var n=0,e=t.length;n=0)return i}else{var o=Ce.toSetString(t);if(Te.call(this._set,o))return this._set[o]}throw Error('"'+t+'" is not in the set.')};nt.prototype.at=function(t){if(t>=0&&t{var D0=Zi();function tz(r,t){var i=r.generatedLine,o=t.generatedLine,n=r.generatedColumn,e=t.generatedColumn;return o>i||o==i&&e>=n||D0.compareByGeneratedPositionsInflated(r,t)<=0}function Ci(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}Ci.prototype.unsortedForEach=function(t,i){this._array.forEach(t,i)};Ci.prototype.add=function(t){if(tz(this._last,t))this._last=t,this._array.push(t);else this._sorted=!1,this._array.push(t)};Ci.prototype.toArray=function(){if(!this._sorted)this._array.sort(D0.compareByGeneratedPositionsInflated),this._sorted=!0;return this._array};nz.MappingList=Ci});var qt="PENPAL_CHILD";var I4=Kh(Xe(),1);var a6=class extends Error{code;constructor(r,t){super(t);this.name="PenpalError",this.code=r}},Or=a6,z6=(r)=>({name:r.name,message:r.message,stack:r.stack,penpalCode:r instanceof Or?r.code:void 0}),_6=({name:r,message:t,stack:i,penpalCode:o})=>{let n=o?new Or(o,t):Error(t);return n.name=r,n.stack=i,n},O6=Symbol("Reply"),D6=class{value;transferables;#r=O6;constructor(r,t){this.value=r,this.transferables=t?.transferables}},p6=D6,Jr="penpal",Ki=(r)=>{return typeof r==="object"&&r!==null},$$=(r)=>{return typeof r==="function"},I6=(r)=>{return Ki(r)&&r.namespace===Jr},Nt=(r)=>{return r.type==="SYN"},Xi=(r)=>{return r.type==="ACK1"},an=(r)=>{return r.type==="ACK2"},x$=(r)=>{return r.type==="CALL"},f$=(r)=>{return r.type==="REPLY"},j6=(r)=>{return r.type==="DESTROY"},w$=(r,t=[])=>{let i=[];for(let o of Object.keys(r)){let n=r[o];if($$(n))i.push([...t,o]);else if(Ki(n))i.push(...w$(n,[...t,o]))}return i},k6=(r,t)=>{let i=r.reduce((o,n)=>{return Ki(o)?o[n]:void 0},t);return $$(i)?i:void 0},mt=(r)=>{return r.join(".")},m$=(r,t,i)=>({namespace:Jr,channel:r,type:"REPLY",callId:t,isError:!0,...i instanceof Error?{value:z6(i),isSerializedErrorInstance:!0}:{value:i}}),U6=(r,t,i,o)=>{let n=!1,e=async(l)=>{if(n)return;if(!x$(l))return;o?.(`Received ${mt(l.methodPath)}() call`,l);let{methodPath:u,args:g,id:c}=l,m,v;try{let h=k6(u,t);if(!h)throw new Or("METHOD_NOT_FOUND",`Method \`${mt(u)}\` is not found.`);let b=await h(...g);if(b instanceof p6)v=b.transferables,b=await b.value;m={namespace:Jr,channel:i,type:"REPLY",callId:c,value:b}}catch(h){m=m$(i,c,h)}if(n)return;try{o?.(`Sending ${mt(u)}() reply`,m),r.sendMessage(m,v)}catch(h){if(h.name==="DataCloneError")m=m$(i,c,h),o?.(`Sending ${mt(u)}() reply`,m),r.sendMessage(m);throw h}};return r.addMessageHandler(e),()=>{n=!0,r.removeMessageHandler(e)}},J6=U6,a$=crypto.randomUUID?.bind(crypto)??(()=>[,,,,].fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),P6=Symbol("CallOptions"),E6=class{transferables;timeout;#r=P6;constructor(r){this.transferables=r?.transferables,this.timeout=r?.timeout}},L6=E6,K6=new Set(["apply","call","bind"]),z$=(r,t,i=[])=>{return new Proxy(i.length?()=>{}:Object.create(null),{get(o,n){if(n==="then")return;if(i.length&&K6.has(n))return Reflect.get(o,n);return z$(r,t,[...i,n])},apply(o,n,e){return r(i,e)}})},b$=(r)=>{return new Or("CONNECTION_DESTROYED",`Method call ${mt(r)}() failed due to destroyed connection`)},X6=(r,t,i)=>{let o=!1,n=new Map,e=(g)=>{if(!f$(g))return;let{callId:c,value:m,isError:v,isSerializedErrorInstance:h}=g,b=n.get(c);if(!b)return;if(n.delete(c),i?.(`Received ${mt(b.methodPath)}() call`,g),v)b.reject(h?_6(m):m);else b.resolve(m)};return r.addMessageHandler(e),{remoteProxy:z$((g,c)=>{if(o)throw b$(g);let m=a$(),v=c[c.length-1],h=v instanceof L6,{timeout:b,transferables:f}=h?v:{},D=h?c.slice(0,-1):c;return new Promise((I,O)=>{let J=b!==void 0?window.setTimeout(()=>{n.delete(m),O(new Or("METHOD_CALL_TIMEOUT",`Method call ${mt(g)}() timed out after ${b}ms`))},b):void 0;n.set(m,{methodPath:g,resolve:I,reject:O,timeoutId:J});try{let q={namespace:Jr,channel:t,type:"CALL",id:m,methodPath:g,args:D};i?.(`Sending ${mt(g)}() call`,q),r.sendMessage(q,f)}catch(q){O(new Or("TRANSMISSION_FAILED",q.message))}})},i),destroy:()=>{o=!0,r.removeMessageHandler(e);for(let{methodPath:g,reject:c,timeoutId:m}of n.values())clearTimeout(m),c(b$(g));n.clear()}}},W6=X6,q6=()=>{let r,t;return{promise:new Promise((o,n)=>{r=o,t=n}),resolve:r,reject:t}},N6=q6,V6=class extends Error{constructor(r){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${r}`)}},Vt=V6,We="deprecated-penpal",S6=(r)=>{return Ki(r)&&"penpal"in r},Y6=(r)=>r.split("."),v$=(r)=>r.join("."),_$=(r)=>{return new Vt(`Unexpected message to translate: ${JSON.stringify(r)}`)},F6=(r)=>{if(r.penpal==="syn")return{namespace:Jr,channel:void 0,type:"SYN",participantId:We};if(r.penpal==="ack")return{namespace:Jr,channel:void 0,type:"ACK2"};if(r.penpal==="call")return{namespace:Jr,channel:void 0,type:"CALL",id:r.id,methodPath:Y6(r.methodName),args:r.args};if(r.penpal==="reply")if(r.resolution==="fulfilled")return{namespace:Jr,channel:void 0,type:"REPLY",callId:r.id,value:r.returnValue};else return{namespace:Jr,channel:void 0,type:"REPLY",callId:r.id,isError:!0,...r.returnValueIsError?{value:r.returnValue,isSerializedErrorInstance:!0}:{value:r.returnValue}};throw _$(r)},Q6=(r)=>{if(Xi(r))return{penpal:"synAck",methodNames:r.methodPaths.map(v$)};if(x$(r))return{penpal:"call",id:r.id,methodName:v$(r.methodPath),args:r.args};if(f$(r))if(r.isError)return{penpal:"reply",id:r.callId,resolution:"rejected",...r.isSerializedErrorInstance?{returnValue:r.value,returnValueIsError:!0}:{returnValue:r.value}};else return{penpal:"reply",id:r.callId,resolution:"fulfilled",returnValue:r.value};throw _$(r)},G6=({messenger:r,methods:t,timeout:i,channel:o,log:n})=>{let e=a$(),l,u=[],g=!1,c=w$(t),{promise:m,resolve:v,reject:h}=N6(),b=i!==void 0?setTimeout(()=>{h(new Or("CONNECTION_TIMEOUT",`Connection timed out after ${i}ms`))},i):void 0,f=()=>{for(let K of u)K()},D=()=>{if(g)return;u.push(J6(r,t,o,n));let{remoteProxy:K,destroy:S}=W6(r,o,n);u.push(S),clearTimeout(b),g=!0,v({remoteProxy:K,destroy:f})},I=()=>{let K={namespace:Jr,type:"SYN",channel:o,participantId:e};n?.("Sending handshake SYN",K);try{r.sendMessage(K)}catch(S){h(new Or("TRANSMISSION_FAILED",S.message))}},O=(K)=>{if(n?.("Received handshake SYN",K),K.participantId===l&&l!==We)return;if(l=K.participantId,I(),!(e>l||l===We))return;let A={namespace:Jr,channel:o,type:"ACK1",methodPaths:c};n?.("Sending handshake ACK1",A);try{r.sendMessage(A)}catch(tr){h(new Or("TRANSMISSION_FAILED",tr.message));return}},J=(K)=>{n?.("Received handshake ACK1",K);let S={namespace:Jr,channel:o,type:"ACK2"};n?.("Sending handshake ACK2",S);try{r.sendMessage(S)}catch(A){h(new Or("TRANSMISSION_FAILED",A.message));return}D()},q=(K)=>{n?.("Received handshake ACK2",K),D()},E=(K)=>{if(Nt(K))O(K);if(Xi(K))J(K);if(an(K))q(K)};return r.addMessageHandler(E),u.push(()=>r.removeMessageHandler(E)),I(),m},A6=G6,B6=(r)=>{let t=!1,i;return(...o)=>{if(!t)t=!0,i=r(...o);return i}},y6=B6,h$=new WeakSet,R6=({messenger:r,methods:t={},timeout:i,channel:o,log:n})=>{if(!r)throw new Or("INVALID_ARGUMENT","messenger must be defined");if(h$.has(r))throw new Or("INVALID_ARGUMENT","A messenger can only be used for a single connection");h$.add(r);let e=[r.destroy],l=y6((c)=>{if(c){let m={namespace:Jr,channel:o,type:"DESTROY"};try{r.sendMessage(m)}catch(v){}}for(let m of e)m();n?.("Connection destroyed")}),u=(c)=>{return I6(c)&&c.channel===o};return{promise:(async()=>{try{r.initialize({log:n,validateReceivedMessage:u}),r.addMessageHandler((v)=>{if(j6(v))l(!1)});let{remoteProxy:c,destroy:m}=await A6({messenger:r,methods:t,timeout:i,channel:o,log:n});return e.push(m),c}catch(c){throw l(!0),c}})(),destroy:()=>{l(!0)}}},O$=R6,H6=class{#r;#o;#n;#t;#l;#i=new Set;#e;#c=!1;constructor({remoteWindow:r,allowedOrigins:t}){if(!r)throw new Or("INVALID_ARGUMENT","remoteWindow must be defined");this.#r=r,this.#o=t?.length?t:[window.origin]}initialize=({log:r,validateReceivedMessage:t})=>{this.#n=r,this.#t=t,window.addEventListener("message",this.#b)};sendMessage=(r,t)=>{if(Nt(r)){let i=this.#u(r);this.#r.postMessage(r,{targetOrigin:i,transfer:t});return}if(Xi(r)||this.#c){let i=this.#c?Q6(r):r,o=this.#u(r);this.#r.postMessage(i,{targetOrigin:o,transfer:t});return}if(an(r)){let{port1:i,port2:o}=new MessageChannel;this.#e=i,i.addEventListener("message",this.#g),i.start();let n=[o,...t||[]],e=this.#u(r);this.#r.postMessage(r,{targetOrigin:e,transfer:n});return}if(this.#e){this.#e.postMessage(r,{transfer:t});return}throw new Vt("Port is undefined")};addMessageHandler=(r)=>{this.#i.add(r)};removeMessageHandler=(r)=>{this.#i.delete(r)};destroy=()=>{window.removeEventListener("message",this.#b),this.#m(),this.#i.clear()};#v=(r)=>{return this.#o.some((t)=>t instanceof RegExp?t.test(r):t===r||t==="*")};#u=(r)=>{if(Nt(r))return"*";if(!this.#l)throw new Vt("Concrete remote origin not set");return this.#l==="null"&&this.#o.includes("*")?"*":this.#l};#m=()=>{this.#e?.removeEventListener("message",this.#g),this.#e?.close(),this.#e=void 0};#b=({source:r,origin:t,ports:i,data:o})=>{if(r!==this.#r)return;if(S6(o))this.#n?.("Please upgrade the child window to the latest version of Penpal."),this.#c=!0,o=F6(o);if(!this.#t?.(o))return;if(!this.#v(t)){this.#n?.(`Received a message from origin \`${t}\` which did not match allowed origins \`[${this.#o.join(", ")}]\``);return}if(Nt(o))this.#m(),this.#l=t;if(an(o)&&!this.#c){if(this.#e=i[0],!this.#e)throw new Vt("No port received on ACK2");this.#e.addEventListener("message",this.#g),this.#e.start()}for(let n of this.#i)n(o)};#g=({data:r})=>{if(!this.#t?.(r))return;for(let t of this.#i)t(r)}},D$=H6,$U=class{#r;#o;#n=new Set;#t;constructor({worker:r}){if(!r)throw new Or("INVALID_ARGUMENT","worker must be defined");this.#r=r}initialize=({validateReceivedMessage:r})=>{this.#o=r,this.#r.addEventListener("message",this.#i)};sendMessage=(r,t)=>{if(Nt(r)||Xi(r)){this.#r.postMessage(r,{transfer:t});return}if(an(r)){let{port1:i,port2:o}=new MessageChannel;this.#t=i,i.addEventListener("message",this.#i),i.start(),this.#r.postMessage(r,{transfer:[o,...t||[]]});return}if(this.#t){this.#t.postMessage(r,{transfer:t});return}throw new Vt("Port is undefined")};addMessageHandler=(r)=>{this.#n.add(r)};removeMessageHandler=(r)=>{this.#n.delete(r)};destroy=()=>{this.#r.removeEventListener("message",this.#i),this.#l(),this.#n.clear()};#l=()=>{this.#t?.removeEventListener("message",this.#i),this.#t?.close(),this.#t=void 0};#i=({ports:r,data:t})=>{if(!this.#o?.(t))return;if(Nt(t))this.#l();if(an(t)){if(this.#t=r[0],!this.#t)throw new Vt("No port received on ACK2");this.#t.addEventListener("message",this.#i),this.#t.start()}for(let i of this.#n)i(t)}};var xU=class{#r;#o;#n=new Set;constructor({port:r}){if(!r)throw new Or("INVALID_ARGUMENT","port must be defined");this.#r=r}initialize=({validateReceivedMessage:r})=>{this.#o=r,this.#r.addEventListener("message",this.#t),this.#r.start()};sendMessage=(r,t)=>{this.#r?.postMessage(r,{transfer:t})};addMessageHandler=(r)=>{this.#n.add(r)};removeMessageHandler=(r)=>{this.#n.delete(r)};destroy=()=>{this.#r.removeEventListener("message",this.#t),this.#r.close(),this.#n.clear()};#t=({data:r})=>{if(!this.#o?.(r))return;for(let t of this.#n)t(r)}};var p$=["SCRIPT","STYLE","LINK","META","NOSCRIPT"],I$=new Set(["a","abbr","area","audio","b","bdi","bdo","br","button","canvas","cite","code","data","datalist","del","dfn","em","embed","h1","h2","h3","h4","h5","h6","i","iframe","img","input","ins","kbd","label","li","map","mark","meter","noscript","object","output","p","picture","progress","q","ruby","s","samp","script","select","slot","small","span","strong","sub","sup","svg","template","textarea","time","u","var","video","wbr"]);var KU={SCALE:0.7,PAN_POSITION:{x:175,y:100},URL:"http://localhost:3000/",ASPECT_RATIO_LOCKED:!1,DEVICE:"Custom:Custom",THEME:"system",ORIENTATION:"Portrait",MIN_DIMENSIONS:{width:"280px",height:"360px"},COMMANDS:{run:"bun run dev",build:"bun run build",install:"bun install"},IMAGE_FOLDER:"public",IMAGE_DIMENSION:{width:"100px",height:"100px"},FONT_FOLDER:"fonts",FONT_CONFIG:"app/fonts.ts",TAILWIND_CONFIG:"tailwind.config.ts",CHAT_SETTINGS:{showSuggestions:!0,autoApplyCode:!0,expandCodeBlocks:!1,showMiniChat:!0,maxImages:5},EDITOR_SETTINGS:{shouldWarnDelete:!1,enableBunReplace:!0,buildFlags:"--no-lint"}};var qe=["node_modules","dist","build",".git",".next"];var WU=[...qe,"static","out",".next-prod",".onlook","public/onlook-preload-script.js"],qU=[...qe,".next-prod"],NU=[...qe,"coverage"],M6=[".jsx",".tsx"],Z6=[".js",".ts",".mjs",".cjs"],VU=[...M6,...Z6];var FU={["en"]:"English",["ja"]:"日本語",["zh"]:"中文",["ko"]:"한국어"};var J$=Kh(Xe(),1);function Q(r){return document.querySelector(`[${"data-odid"}="${r}"]`)}function Ne(r,t=!1){let i=`[${"data-odid"}="${r}"]`;if(!t)return i;return C6(i)}function C6(r){return CSS.escape(r)}function Dt(r){return r&&r instanceof Node&&r.nodeType===Node.ELEMENT_NODE&&!p$.includes(r.tagName)&&!r.hasAttribute("data-onlook-ignore")&&r.style.display!=="none"}var T6="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var j$=(r=21)=>{let t="",i=r|0;while(i--)t+=T6[Math.random()*64|0];return t};function Pr(r){let t=r.getAttribute("data-odid");if(!t)t=`odid-${j$()}`,r.setAttribute("data-odid",t);return t}function Qr(r){return r.getAttribute("data-oid")}function Gr(r){return r.getAttribute("data-oiid")}function k$(r,t){if(!ar)return;ar.onDomProcessed({layerMap:Object.fromEntries(r),rootNode:t}).catch((i)=>{console.error("Failed to send DOM processed event:",i)})}function Ve(r){window._onlookFrameId=r}function St(){let r=window._onlookFrameId;if(!r)return console.warn("Frame id not found"),ar?.getFrameId().then((t)=>{Ve(t)}),"";return r}function Se(r){window._onlookBranchId=r}function zn(){let r=window._onlookBranchId;if(!r)return console.warn("Branch id not found"),ar?.getBranchId().then((t)=>{Se(t)}),"";return r}function d6(r=document.body){if(!St())return console.warn("frameView id not found, skipping dom processing"),null;let i=zr(r);if(!i)return console.warn("Error building layer tree, root element is null"),null;let o=r.getAttribute("data-odid");if(!o)return console.warn("Root dom id not found"),null;let n=i.get(o);if(!n)return console.warn("Root node not found"),null;return k$(i,n),{rootDomId:o,layerMap:Array.from(i.entries())}}var Wi=J$.default(d6,500),s6=[(r)=>{let t=r.parentElement;return t&&t.tagName.toLowerCase()==="svg"},(r)=>{return r.tagName.toLowerCase()==="next-route-announcer"},(r)=>{return r.tagName.toLowerCase()==="nextjs-portal"}];function zr(r){if(!Dt(r))return null;let t=new Map,i=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,{acceptNode:(e)=>{let l=e;if(s6.some((u)=>u(l)))return NodeFilter.FILTER_REJECT;return Dt(l)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),o=U$(r);o.children=[],t.set(o.domId,o);let n=i.nextNode();while(n){let e=U$(n);e.children=[];let l=n.parentElement;if(l){let u=l.getAttribute("data-odid");if(u){e.parent=u;let g=t.get(u);if(g&&g.children)g.children.push(e.domId)}}t.set(e.domId,e),n=i.nextNode()}return t}function U$(r){let t=Pr(r),i=Qr(r),o=Gr(r),n=Array.from(r.childNodes).map((g)=>g.nodeType===Node.TEXT_NODE?g.textContent:"").join(" ").trim().slice(0,500),e=window.getComputedStyle(r),l=r.getAttribute("data-ocname");return{domId:t,oid:i||null,instanceId:o||null,textContent:n||"",tagName:r.tagName.toLowerCase(),isVisible:e.visibility!=="hidden",component:l||null,frameId:St(),children:null,parent:null,dynamicType:null,coreElementType:null}}function Ye(r){throw Error(`Expected \`never\`, found: ${JSON.stringify(r)}`)}var P$=(r)=>JSON.parse(JSON.stringify(r));function E$(r){let t=K$(r),i=ra(r),o=ta(r);return{defined:{width:"auto",height:"auto",...i,...o},computed:t}}function L$(r){let t=Q(r);if(!t)return{};return K$(t)}function K$(r){return P$(window.getComputedStyle(r))}function ra(r){let t={},i=X$(r.style.cssText);return Object.entries(i).forEach(([o,n])=>{t[o]=n}),t}function ta(r){let t={},i=document.styleSheets;for(let o=0;ot[c]=m)}}catch(u){console.warn("Error",u)}}return t}function X$(r){let t={};return r.split(";").forEach((i)=>{if(i=i.trim(),!i)return;let[o,...n]=i.split(":");t[o?.trim()??""]=n.join(":").trim()}),t}var W$=(r,t)=>{let i=document.elementFromPoint(r,t);if(!i)return;let o=(e)=>{if(e?.shadowRoot){let l=e.shadowRoot.elementFromPoint(r,t);if(l==e)return e;else if(l?.shadowRoot)return o(l);else return l||e}else return e};return o(i)||i},lr=(r,t)=>{let i=r.parentElement,o=i?{domId:i.getAttribute("data-odid"),frameId:St(),branchId:zn(),oid:i.getAttribute("data-oid"),instanceId:i.getAttribute("data-oiid"),rect:i.getBoundingClientRect()}:null,n=r.getBoundingClientRect(),e=t?E$(r):null;return{domId:r.getAttribute("data-odid"),oid:r.getAttribute("data-oid"),frameId:St(),branchId:zn(),instanceId:r.getAttribute("data-oiid"),rect:n,tagName:r.tagName,parent:o,styles:e}};function qi(r){try{let t=r.getAttribute("data-onlook-drag-saved-style");if(t){let i=JSON.parse(t);for(let o in i)r.style[o]=i[o]}}catch(t){console.warn("Error restoring style",t)}}function q$(r){let t=r.parentElement;if(!t)return;return{type:"index",targetDomId:t.getAttribute("data-odid"),targetOid:Gr(t)||Qr(t)||null,index:Array.from(r.parentElement?.children||[]).indexOf(r),originalIndex:Array.from(r.parentElement?.children||[]).indexOf(r)}}var N$=(r)=>{let t=Array.from(r.childNodes).filter((i)=>i.nodeType===Node.TEXT_NODE).map((i)=>i.textContent);if(t.length===0)return;return t.join("")};var Ni=(r,t)=>{let i=Q(r)||document.body;return lr(i,t)},V$=(r,t,i)=>{let o=na(r,t)||document.body;return lr(o,i)},na=(r,t)=>{let i=document.elementFromPoint(r,t);if(!i)return;let o=(e)=>{if(e?.shadowRoot){let l=e.shadowRoot.elementFromPoint(r,t);if(l==e)return e;else if(l?.shadowRoot)return o(l);else return l||e}else return e};return o(i)||i},S$=(r,t,i)=>{let o=Q(r);if(!o){console.warn("Failed to updateElementInstanceId: Element not found");return}o.setAttribute("data-oiid",t),o.setAttribute("data-ocname",i)},Y$=(r)=>{let t=Q(r);if(!t?.parentElement)return null;return lr(t.parentElement,!1)},F$=(r)=>{let t=Q(r);if(!t)return 0;return t.children.length},Q$=(r)=>{let t=Q(r);if(!t)return null;return lr(t.offsetParent,!1)};function G$(r,t,i){let o=Q(r.domId);if(!o)return console.warn("Failed to find parent element",r.domId),null;let n=ia(t),e=new Set(i.map((c)=>c.domId)),l=Array.from(o.children).map((c,m)=>({element:c,index:m,domId:Pr(c)})).filter(({domId:c})=>e.has(c));if(l.length===0)return console.warn("No valid children found to group"),null;let u=Math.min(...l.map((c)=>c.index));return o.insertBefore(n,o.children[u]??null),l.forEach(({element:c})=>{let m=c.cloneNode(!0);m.setAttribute("data-onlook-inserted","true"),n.appendChild(m),c.style.display="none",B$(c)}),{domEl:lr(n,!0),newMap:zr(n)}}function A$(r,t){let i=Q(r.domId);if(!i)return console.warn(`Parent element not found: ${r.domId}`),null;let o;if(t.domId)o=Q(t.domId);else return console.warn("Container domId is required for ungrouping"),null;if(!o)return console.warn("Container element not found for ungrouping"),null;return Array.from(o.children).forEach((l)=>{i.appendChild(l)}),o.remove(),{domEl:lr(i,!0),newMap:zr(i)}}function ia(r){let t=document.createElement(r.tagName);return Object.entries(r.attributes).forEach(([i,o])=>{t.setAttribute(i,o)}),t.setAttribute("data-onlook-inserted","true"),t.setAttribute("data-odid",r.domId),t.setAttribute("data-oid",r.oid),t}function B$(r){r.removeAttribute("data-odid"),r.removeAttribute("data-oid"),r.removeAttribute("data-onlook-inserted");let t=Array.from(r.children);if(t.length===0)return;t.forEach((i)=>{B$(i)})}function Vi(r){let t=Q(r);if(!t)return console.warn("Element not found for domId:",r),null;return y$(t)}function y$(r){let t=Array.from(r.attributes).reduce((o,n)=>{return o[n.name]=n.value,o},{}),i=Gr(r)||Qr(r)||null;if(!i)return console.warn("Element has no oid"),null;return{oid:i,branchId:zn(),domId:Pr(r),tagName:r.tagName.toLowerCase(),children:Array.from(r.children).map((o)=>y$(o)).filter(Boolean),attributes:t,textContent:N$(r)||null,styles:{}}}function R$(r){let t=Q(r);if(!t)throw Error("Element not found for domId: "+r);let i=t.parentElement;if(!i)throw Error("Inserted element has no parent");let o=Gr(i)||Qr(i);if(!o)return console.warn("Parent element has no oid"),null;let n=Pr(i),e=Array.from(i.children).indexOf(t);if(e===-1)return{type:"append",targetDomId:n,targetOid:o};return{type:"index",targetDomId:n,targetOid:o,index:e,originalIndex:e}}function H$(r){let t=document.querySelector(`[${"data-odid"}="${r}"]`);if(!t)return console.warn("No element found",{domId:r}),{dynamicType:null,coreType:null};let i=t.getAttribute("data-onlook-dynamic-type")||null,o=t.getAttribute("data-onlook-core-element-type")||null;return{dynamicType:i,coreType:o}}function M$(r,t,i){let o=document.querySelector(`[${"data-odid"}="${r}"]`);if(o){if(t)o.setAttribute("data-onlook-dynamic-type",t);if(i)o.setAttribute("data-onlook-core-element-type",i)}}function Z$(){let t=document.body.querySelector(`[${"data-oid"}]`);if(t)return lr(t,!0);return null}var Sr=0,w=1,k=2,H=3,F=4,gr=5,Yt=6,er=7,fr=8,P=9,U=10,B=11,L=12,N=13,dr=14,hr=15,d=16,nr=17,ir=18,mr=19,wr=20,X=21,p=22,Z=23,xr=24,y=25;function cr(r){return r>=48&&r<=57}function Ir(r){return cr(r)||r>=65&&r<=70||r>=97&&r<=102}function Fi(r){return r>=65&&r<=90}function oa(r){return r>=97&&r<=122}function ea(r){return Fi(r)||oa(r)}function la(r){return r>=128}function Yi(r){return ea(r)||la(r)||r===95}function _n(r){return Yi(r)||cr(r)||r===45}function ca(r){return r>=0&&r<=8||r===11||r>=14&&r<=31||r===127}function On(r){return r===10||r===13||r===12}function Ar(r){return On(r)||r===32||r===9}function Dr(r,t){if(r!==92)return!1;if(On(t)||t===0)return!1;return!0}function Ft(r,t,i){if(r===45)return Yi(t)||t===45||Dr(t,i);if(Yi(r))return!0;if(r===92)return Dr(r,t);return!1}function Qi(r,t,i){if(r===43||r===45){if(cr(t))return 2;return t===46&&cr(i)?3:0}if(r===46)return cr(t)?2:0;if(cr(r))return 1;return 0}function Gi(r){if(r===65279)return 1;if(r===65534)return 1;return 0}var Fe=Array(128),ua=128,Dn=130,Qe=131,Ai=132,Ge=133;for(let r=0;rr.length)return!1;for(let n=t;n=0;t--)if(!Ar(r.charCodeAt(t)))break;return t+1}function pn(r,t){for(;t=55296&&t<=57343||t>1114111)t=65533;return String.fromCodePoint(t)}var Gt=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"];function At(r=null,t){if(r===null||r.length0?Gi(t.charCodeAt(0)):0,n=At(r.lines,i),e=At(r.columns,i),l=r.startLine,u=r.startColumn;for(let g=o;g{}){r=String(r||"");let i=r.length,o=At(this.offsetAndType,r.length+1),n=At(this.balance,r.length+1),e=0,l=-1,u=0,g=r.length;this.offsetAndType=null,this.balance=null,n.fill(0),t(r,(c,m,v)=>{let h=e++;if(o[h]=c<>Rr]}else if(r0(c))g=h,u=It[c]}),o[e]=Sr<e)n[c]=e}this.source=r,this.firstCharOffset=l===-1?0:l,this.tokenCount=e,this.offsetAndType=o,this.balance=n,this.reset(),this.next()}lookupType(r){if(r+=this.tokenIndex,r>Rr;return Sr}lookupTypeNonSC(r){for(let t=this.tokenIndex;t>Rr;if(i!==N&&i!==y){if(r--===0)return i}}return Sr}lookupOffset(r){if(r+=this.tokenIndex,r>Rr;if(i!==N&&i!==y){if(r--===0)return t-this.tokenIndex}}return Sr}lookupValue(r,t){if(r+=this.tokenIndex,r0)return r>Rr,this.tokenEnd=t&yr;else this.tokenIndex=this.tokenCount,this.next()}next(){let r=this.tokenIndex+1;if(r>Rr,this.tokenEnd=r&yr;else this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=Sr,this.tokenStart=this.tokenEnd=this.source.length}skipSC(){while(this.tokenType===N||this.tokenType===y)this.next()}skipUntilBalanced(r,t){let i=r,o=0,n=0;r:for(;i0?this.offsetAndType[i-1]&yr:this.firstCharOffset,t(this.source.charCodeAt(n))){case 1:break r;case 2:i++;break r;default:if(r0(this.offsetAndType[i]>>Rr))i=o}}this.skip(i-this.tokenIndex)}forEachToken(r){for(let t=0,i=this.firstCharOffset;t>Rr;i=e,r(l,o,e,t)}}dump(){let r=Array(this.tokenCount);return this.forEachToken((t,i,o,n)=>{r[n]={idx:n,type:Gt[t],chunk:this.source.substring(i,o),balance:this.balance[n]}}),r}}function bt(r,t){function i(v){return v=r.length){if(cString(f+O+1).padStart(h)+" |"+I).join(` `)}let u=` `.repeat(Math.max(o-1,0)),g=" ".repeat(Math.max(n-1,0)),c=(u+g+r).split(/\r\n?|\n|\f/),m=Math.max(1,t-e)-1,v=Math.min(t+e,c.length+1),h=Math.max(4,String(v).length)+1,b=0;if(i+=(n0.length-1)*(c[t-1].substr(0,i-1).match(/\t/g)||[]).length,i>Be)b=i-t0+3,i=t0-2;for(let f=m;f<=v;f++)if(f>=0&&f0&&c[f].length>b?"…":"")+c[f].substr(b,Be-2)+(c[f].length>b+Be-1?"…":"");return[l(m,t),Array(i+h+2).join("-")+"^",l(t,v)].filter(Boolean).join(` `).replace(/^(\s+\d+\s+\|\n)+/,"").replace(/\n(\s+\d+\s+\|)+$/,"")}function ye(r,t,i,o,n,e=1,l=1){return Object.assign(jt("SyntaxError",r),{source:t,offset:i,line:o,column:n,sourceFragment(g){return i0({source:t,line:o,column:n,baseLine:e,baseColumn:l},isNaN(g)?0:g)},get formattedMessage(){return`Parse error: ${r} -`+i0({source:t,line:o,column:n,baseLine:e,baseColumn:l},2)}})}function o0(r){let t=this.createList(),i=!1,o={recognizer:r};while(!this.eof){switch(this.tokenType){case y:this.next();continue;case N:i=!0,this.next();continue}let n=r.getNode.call(this,o);if(n===void 0)break;if(i){if(r.onWhiteSpace)r.onWhiteSpace.call(this,n,t,o);i=!1}t.push(n)}if(i&&r.onWhiteSpace)r.onWhiteSpace.call(this,null,t,o);return t}var e0=()=>{},m6=33,b6=35,Re=59,l0=123,c0=0;function v6(r){return function(){return this[r]()}}function He(r){let t=Object.create(null);for(let i of Object.keys(r)){let o=r[i],n=o.parse||o;if(n)t[i]=n}return t}function h6(r){let t={context:Object.create(null),features:Object.assign(Object.create(null),r.features),scope:Object.assign(Object.create(null),r.scope),atrule:He(r.atrule),pseudo:He(r.pseudo),node:He(r.node)};for(let[i,o]of Object.entries(r.parseContext))switch(typeof o){case"function":t.context[i]=o;break;case"string":t.context[i]=v6(o);break}return{config:t,...t,...t.node}}function u0(r){let t="",i="",o=!1,n=e0,e=!1,l=new Hi,u=Object.assign(new Mi,h6(r||{}),{parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:o0,consumeUntilBalanceEnd:()=>0,consumeUntilLeftCurlyBracket(c){return c===l0?1:0},consumeUntilLeftCurlyBracketOrSemicolon(c){return c===l0||c===Re?1:0},consumeUntilExclamationMarkOrSemicolon(c){return c===m6||c===Re?1:0},consumeUntilSemicolonIncluded(c){return c===Re?2:0},createList(){return new or},createSingleNodeList(c){return new or().appendData(c)},getFirstListNode(c){return c&&c.first},getLastListNode(c){return c&&c.last},parseWithFallback(c,m){let v=this.tokenIndex;try{return c.call(this)}catch(h){if(e)throw h;this.skip(v-this.tokenIndex);let b=m.call(this);return e=!0,n(h,b),e=!1,b}},lookupNonWSType(c){let m;do if(m=this.lookupType(c++),m!==N&&m!==y)return m;while(m!==c0);return c0},charCodeAt(c){return c>=0&&cb.toUpperCase()),v=`${/[[\](){}]/.test(m)?`"${m}"`:m} is expected`,h=this.tokenStart;switch(c){case w:if(this.tokenType===k||this.tokenType===er)h=this.tokenEnd-1,v="Identifier is expected but function found";else v="Identifier is expected";break;case F:if(this.isDelim(b6))this.next(),h++,v="Name is expected";break;case B:if(this.tokenType===U)h=this.tokenEnd,v="Percent sign is expected";break}this.error(v,h)}this.next()},eatIdent(c){if(this.tokenType!==w||this.lookupValue(0,c)===!1)this.error(`Identifier "${c}" is expected`);this.next()},eatDelim(c){if(!this.isDelim(c))this.error(`Delim "${String.fromCharCode(c)}" is expected`);this.next()},getLocation(c,m){if(o)return l.getLocationRange(c,m,i);return null},getLocationFromList(c){if(o){let m=this.getFirstListNode(c),v=this.getLastListNode(c);return l.getLocationRange(m!==null?m.loc.start.offset-l.startOffset:this.tokenStart,v!==null?v.loc.end.offset-l.startOffset:this.tokenStart,i)}return null},error(c,m){let v=typeof m<"u"&&m",o=Boolean(m.positions),n=typeof m.onParseError==="function"?m.onParseError:e0,e=!1,u.parseAtrulePrelude="parseAtrulePrelude"in m?Boolean(m.parseAtrulePrelude):!0,u.parseRulePrelude="parseRulePrelude"in m?Boolean(m.parseRulePrelude):!0,u.parseValue="parseValue"in m?Boolean(m.parseValue):!0,u.parseCustomProperty="parseCustomProperty"in m?Boolean(m.parseCustomProperty):!1;let{context:v="default",onComment:h}=m;if(v in u.context===!1)throw Error("Unknown context `"+v+"`");if(typeof h==="function")u.forEachToken((f,D,I)=>{if(f===y){let O=u.getLocation(D,I),J=rt(t,I-2,I,"*/")?t.slice(D+2,I-2):t.slice(D+2,I);h(J,O)}});let b=u.context[v].call(u,m);if(!u.eof)u.error();return b},{SyntaxError:ye,config:u.config})}var Un=x0(),ur=Zi(),Ti=O0().ArraySet,oz=p0().MappingList;function Wr(r){if(!r)r={};this._file=ur.getArg(r,"file",null),this._sourceRoot=ur.getArg(r,"sourceRoot",null),this._skipValidation=ur.getArg(r,"skipValidation",!1),this._ignoreInvalidMapping=ur.getArg(r,"ignoreInvalidMapping",!1),this._sources=new Ti,this._names=new Ti,this._mappings=new oz,this._sourcesContents=null}Wr.prototype._version=3;Wr.fromSourceMap=function(t,i){var o=t.sourceRoot,n=new Wr(Object.assign(i||{},{file:t.file,sourceRoot:o}));return t.eachMapping(function(e){var l={generated:{line:e.generatedLine,column:e.generatedColumn}};if(e.source!=null){if(l.source=e.source,o!=null)l.source=ur.relative(o,l.source);if(l.original={line:e.originalLine,column:e.originalColumn},e.name!=null)l.name=e.name}n.addMapping(l)}),t.sources.forEach(function(e){var l=e;if(o!==null)l=ur.relative(o,e);if(!n._sources.has(l))n._sources.add(l);var u=t.sourceContentFor(e);if(u!=null)n.setSourceContent(e,u)}),n};Wr.prototype.addMapping=function(t){var i=ur.getArg(t,"generated"),o=ur.getArg(t,"original",null),n=ur.getArg(t,"source",null),e=ur.getArg(t,"name",null);if(!this._skipValidation){if(this._validateMapping(i,o,n,e)===!1)return}if(n!=null){if(n=String(n),!this._sources.has(n))this._sources.add(n)}if(e!=null){if(e=String(e),!this._names.has(e))this._names.add(e)}this._mappings.add({generatedLine:i.line,generatedColumn:i.column,originalLine:o!=null&&o.line,originalColumn:o!=null&&o.column,source:n,name:e})};Wr.prototype.setSourceContent=function(t,i){var o=t;if(this._sourceRoot!=null)o=ur.relative(this._sourceRoot,o);if(i!=null){if(!this._sourcesContents)this._sourcesContents=Object.create(null);this._sourcesContents[ur.toSetString(o)]=i}else if(this._sourcesContents){if(delete this._sourcesContents[ur.toSetString(o)],Object.keys(this._sourcesContents).length===0)this._sourcesContents=null}};Wr.prototype.applySourceMap=function(t,i,o){var n=i;if(i==null){if(t.file==null)throw Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);n=t.file}var e=this._sourceRoot;if(e!=null)n=ur.relative(e,n);var l=new Ti,u=new Ti;this._mappings.unsortedForEach(function(g){if(g.source===n&&g.originalLine!=null){var c=t.originalPositionFor({line:g.originalLine,column:g.originalColumn});if(c.source!=null){if(g.source=c.source,o!=null)g.source=ur.join(o,g.source);if(e!=null)g.source=ur.relative(e,g.source);if(g.originalLine=c.line,g.originalColumn=c.column,c.name!=null)g.name=c.name}}var m=g.source;if(m!=null&&!l.has(m))l.add(m);var v=g.name;if(v!=null&&!u.has(v))u.add(v)},this),this._sources=l,this._names=u,t.sources.forEach(function(g){var c=t.sourceContentFor(g);if(c!=null){if(o!=null)g=ur.join(o,g);if(e!=null)g=ur.relative(e,g);this.setSourceContent(g,c)}},this)};Wr.prototype._validateMapping=function(t,i,o,n){if(i&&typeof i.line!=="number"&&typeof i.column!=="number"){var e="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping){if(typeof console<"u"&&console.warn)console.warn(e);return!1}else throw Error(e)}if(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!i&&!o&&!n)return;else if(t&&"line"in t&&"column"in t&&i&&"line"in i&&"column"in i&&t.line>0&&t.column>=0&&i.line>0&&i.column>=0&&o)return;else{var e="Invalid mapping: "+JSON.stringify({generated:t,source:o,original:i,name:n});if(this._ignoreInvalidMapping){if(typeof console<"u"&&console.warn)console.warn(e);return!1}else throw Error(e)}};Wr.prototype._serializeMappings=function(){var t=0,i=1,o=0,n=0,e=0,l=0,u="",g,c,m,v,h=this._mappings.toArray();for(var b=0,f=h.length;b0){if(!ur.compareByGeneratedPositionsInflated(c,h[b-1]))continue;g+=","}if(g+=Un.encode(c.generatedColumn-t),t=c.generatedColumn,c.source!=null){if(v=this._sources.indexOf(c.source),g+=Un.encode(v-l),l=v,g+=Un.encode(c.originalLine-1-n),n=c.originalLine-1,g+=Un.encode(c.originalColumn-o),o=c.originalColumn,c.name!=null)m=this._names.indexOf(c.name),g+=Un.encode(m-e),e=m}u+=g}return u};Wr.prototype._generateSourcesContent=function(t,i){return t.map(function(o){if(!this._sourcesContents)return null;if(i!=null)o=ur.relative(i,o);var n=ur.toSetString(o);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)};Wr.prototype.toJSON=function(){var t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null)t.file=this._file;if(this._sourceRoot!=null)t.sourceRoot=this._sourceRoot;if(this._sourcesContents)t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot);return t};Wr.prototype.toString=function(){return JSON.stringify(this.toJSON())};var de=Wr;var I0=new Set(["Atrule","Selector","Declaration"]);function j0(r){let t=new de,i={line:1,column:0},o={line:0,column:0},n={line:1,column:0},e={generated:n},l=1,u=0,g=!1,c=r.node;r.node=function(h){if(h.loc&&h.loc.start&&I0.has(h.type)){let b=h.loc.start.line,f=h.loc.start.column-1;if(o.line!==b||o.column!==f){if(o.line=b,o.column=f,i.line=l,i.column=u,g){if(g=!1,i.line!==n.line||i.column!==n.column)t.addMapping(e)}g=!0,t.addMapping({source:h.loc.source,original:o,generated:i})}}if(c.call(this,h),g&&I0.has(h.type))n.line=l,n.column=u};let m=r.emit;r.emit=function(h,b,f){for(let D=0;Duz,safe:()=>rl});var ez=43,lz=45,se=(r,t)=>{if(r===P)r=t;if(typeof r==="string"){let i=r.charCodeAt(0);return i>127?32768:i<<8}return r},k0=[[w,w],[w,k],[w,er],[w,fr],[w,"-"],[w,U],[w,B],[w,L],[w,hr],[w,X],[H,w],[H,k],[H,er],[H,fr],[H,"-"],[H,U],[H,B],[H,L],[H,hr],[F,w],[F,k],[F,er],[F,fr],[F,"-"],[F,U],[F,B],[F,L],[F,hr],[L,w],[L,k],[L,er],[L,fr],[L,"-"],[L,U],[L,B],[L,L],[L,hr],["#",w],["#",k],["#",er],["#",fr],["#","-"],["#",U],["#",B],["#",L],["#",hr],["-",w],["-",k],["-",er],["-",fr],["-","-"],["-",U],["-",B],["-",L],["-",hr],[U,w],[U,k],[U,er],[U,fr],[U,U],[U,B],[U,L],[U,"%"],[U,hr],["@",w],["@",k],["@",er],["@",fr],["@","-"],["@",hr],[".",U],[".",B],[".",L],["+",U],["+",B],["+",L],["/","*"]],cz=k0.concat([[w,F],[L,F],[F,F],[H,X],[H,gr],[H,d],[B,B],[B,L],[B,k],[B,"-"],[p,w],[p,k],[p,B],[p,L],[p,F],[p,"-"]]);function U0(r){let t=new Set(r.map(([i,o])=>se(i)<<16|se(o)));return function(i,o,n){let e=se(o,n),l=n.charCodeAt(0);if(l===lz&&o!==w&&o!==k&&o!==hr||l===ez?t.has(i<<16|l<<8):t.has(i<<16|e))this.emit(" ",N,!0);return e}}var uz=U0(k0),rl=U0(cz);var gz=92;function mz(r,t){if(typeof t==="function"){let i=null;r.children.forEach((o)=>{if(i!==null)t.call(this,i);this.node(o),i=o});return}r.children.forEach(this.node,this)}function bz(r){bt(r,(t,i,o)=>{this.token(t,r.slice(i,o))})}function J0(r){let t=new Map;for(let[i,o]of Object.entries(r.node))if(typeof(o.generate||o)==="function")t.set(i,o.generate||o);return function(i,o){let n="",e=0,l={node(g){if(t.has(g.type))t.get(g.type).call(u,g);else throw Error("Unknown node type: "+g.type)},tokenBefore:rl,token(g,c){if(e=this.tokenBefore(e,g,c),this.emit(c,g,!1),g===P&&c.charCodeAt(0)===gz)this.emit(` +`+i0({source:t,line:o,column:n,baseLine:e,baseColumn:l},2)}})}function o0(r){let t=this.createList(),i=!1,o={recognizer:r};while(!this.eof){switch(this.tokenType){case y:this.next();continue;case N:i=!0,this.next();continue}let n=r.getNode.call(this,o);if(n===void 0)break;if(i){if(r.onWhiteSpace)r.onWhiteSpace.call(this,n,t,o);i=!1}t.push(n)}if(i&&r.onWhiteSpace)r.onWhiteSpace.call(this,null,t,o);return t}var e0=()=>{},ma=33,ba=35,Re=59,l0=123,c0=0;function va(r){return function(){return this[r]()}}function He(r){let t=Object.create(null);for(let i of Object.keys(r)){let o=r[i],n=o.parse||o;if(n)t[i]=n}return t}function ha(r){let t={context:Object.create(null),features:Object.assign(Object.create(null),r.features),scope:Object.assign(Object.create(null),r.scope),atrule:He(r.atrule),pseudo:He(r.pseudo),node:He(r.node)};for(let[i,o]of Object.entries(r.parseContext))switch(typeof o){case"function":t.context[i]=o;break;case"string":t.context[i]=va(o);break}return{config:t,...t,...t.node}}function u0(r){let t="",i="",o=!1,n=e0,e=!1,l=new Hi,u=Object.assign(new Mi,ha(r||{}),{parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:o0,consumeUntilBalanceEnd:()=>0,consumeUntilLeftCurlyBracket(c){return c===l0?1:0},consumeUntilLeftCurlyBracketOrSemicolon(c){return c===l0||c===Re?1:0},consumeUntilExclamationMarkOrSemicolon(c){return c===ma||c===Re?1:0},consumeUntilSemicolonIncluded(c){return c===Re?2:0},createList(){return new or},createSingleNodeList(c){return new or().appendData(c)},getFirstListNode(c){return c&&c.first},getLastListNode(c){return c&&c.last},parseWithFallback(c,m){let v=this.tokenIndex;try{return c.call(this)}catch(h){if(e)throw h;this.skip(v-this.tokenIndex);let b=m.call(this);return e=!0,n(h,b),e=!1,b}},lookupNonWSType(c){let m;do if(m=this.lookupType(c++),m!==N&&m!==y)return m;while(m!==c0);return c0},charCodeAt(c){return c>=0&&cb.toUpperCase()),v=`${/[[\](){}]/.test(m)?`"${m}"`:m} is expected`,h=this.tokenStart;switch(c){case w:if(this.tokenType===k||this.tokenType===er)h=this.tokenEnd-1,v="Identifier is expected but function found";else v="Identifier is expected";break;case F:if(this.isDelim(ba))this.next(),h++,v="Name is expected";break;case B:if(this.tokenType===U)h=this.tokenEnd,v="Percent sign is expected";break}this.error(v,h)}this.next()},eatIdent(c){if(this.tokenType!==w||this.lookupValue(0,c)===!1)this.error(`Identifier "${c}" is expected`);this.next()},eatDelim(c){if(!this.isDelim(c))this.error(`Delim "${String.fromCharCode(c)}" is expected`);this.next()},getLocation(c,m){if(o)return l.getLocationRange(c,m,i);return null},getLocationFromList(c){if(o){let m=this.getFirstListNode(c),v=this.getLastListNode(c);return l.getLocationRange(m!==null?m.loc.start.offset-l.startOffset:this.tokenStart,v!==null?v.loc.end.offset-l.startOffset:this.tokenStart,i)}return null},error(c,m){let v=typeof m<"u"&&m",o=Boolean(m.positions),n=typeof m.onParseError==="function"?m.onParseError:e0,e=!1,u.parseAtrulePrelude="parseAtrulePrelude"in m?Boolean(m.parseAtrulePrelude):!0,u.parseRulePrelude="parseRulePrelude"in m?Boolean(m.parseRulePrelude):!0,u.parseValue="parseValue"in m?Boolean(m.parseValue):!0,u.parseCustomProperty="parseCustomProperty"in m?Boolean(m.parseCustomProperty):!1;let{context:v="default",onComment:h}=m;if(v in u.context===!1)throw Error("Unknown context `"+v+"`");if(typeof h==="function")u.forEachToken((f,D,I)=>{if(f===y){let O=u.getLocation(D,I),J=rt(t,I-2,I,"*/")?t.slice(D+2,I-2):t.slice(D+2,I);h(J,O)}});let b=u.context[v].call(u,m);if(!u.eof)u.error();return b},{SyntaxError:ye,config:u.config})}var Un=x0(),ur=Zi(),Ti=O0().ArraySet,oz=p0().MappingList;function Wr(r){if(!r)r={};this._file=ur.getArg(r,"file",null),this._sourceRoot=ur.getArg(r,"sourceRoot",null),this._skipValidation=ur.getArg(r,"skipValidation",!1),this._ignoreInvalidMapping=ur.getArg(r,"ignoreInvalidMapping",!1),this._sources=new Ti,this._names=new Ti,this._mappings=new oz,this._sourcesContents=null}Wr.prototype._version=3;Wr.fromSourceMap=function(t,i){var o=t.sourceRoot,n=new Wr(Object.assign(i||{},{file:t.file,sourceRoot:o}));return t.eachMapping(function(e){var l={generated:{line:e.generatedLine,column:e.generatedColumn}};if(e.source!=null){if(l.source=e.source,o!=null)l.source=ur.relative(o,l.source);if(l.original={line:e.originalLine,column:e.originalColumn},e.name!=null)l.name=e.name}n.addMapping(l)}),t.sources.forEach(function(e){var l=e;if(o!==null)l=ur.relative(o,e);if(!n._sources.has(l))n._sources.add(l);var u=t.sourceContentFor(e);if(u!=null)n.setSourceContent(e,u)}),n};Wr.prototype.addMapping=function(t){var i=ur.getArg(t,"generated"),o=ur.getArg(t,"original",null),n=ur.getArg(t,"source",null),e=ur.getArg(t,"name",null);if(!this._skipValidation){if(this._validateMapping(i,o,n,e)===!1)return}if(n!=null){if(n=String(n),!this._sources.has(n))this._sources.add(n)}if(e!=null){if(e=String(e),!this._names.has(e))this._names.add(e)}this._mappings.add({generatedLine:i.line,generatedColumn:i.column,originalLine:o!=null&&o.line,originalColumn:o!=null&&o.column,source:n,name:e})};Wr.prototype.setSourceContent=function(t,i){var o=t;if(this._sourceRoot!=null)o=ur.relative(this._sourceRoot,o);if(i!=null){if(!this._sourcesContents)this._sourcesContents=Object.create(null);this._sourcesContents[ur.toSetString(o)]=i}else if(this._sourcesContents){if(delete this._sourcesContents[ur.toSetString(o)],Object.keys(this._sourcesContents).length===0)this._sourcesContents=null}};Wr.prototype.applySourceMap=function(t,i,o){var n=i;if(i==null){if(t.file==null)throw Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);n=t.file}var e=this._sourceRoot;if(e!=null)n=ur.relative(e,n);var l=new Ti,u=new Ti;this._mappings.unsortedForEach(function(g){if(g.source===n&&g.originalLine!=null){var c=t.originalPositionFor({line:g.originalLine,column:g.originalColumn});if(c.source!=null){if(g.source=c.source,o!=null)g.source=ur.join(o,g.source);if(e!=null)g.source=ur.relative(e,g.source);if(g.originalLine=c.line,g.originalColumn=c.column,c.name!=null)g.name=c.name}}var m=g.source;if(m!=null&&!l.has(m))l.add(m);var v=g.name;if(v!=null&&!u.has(v))u.add(v)},this),this._sources=l,this._names=u,t.sources.forEach(function(g){var c=t.sourceContentFor(g);if(c!=null){if(o!=null)g=ur.join(o,g);if(e!=null)g=ur.relative(e,g);this.setSourceContent(g,c)}},this)};Wr.prototype._validateMapping=function(t,i,o,n){if(i&&typeof i.line!=="number"&&typeof i.column!=="number"){var e="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping){if(typeof console<"u"&&console.warn)console.warn(e);return!1}else throw Error(e)}if(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!i&&!o&&!n)return;else if(t&&"line"in t&&"column"in t&&i&&"line"in i&&"column"in i&&t.line>0&&t.column>=0&&i.line>0&&i.column>=0&&o)return;else{var e="Invalid mapping: "+JSON.stringify({generated:t,source:o,original:i,name:n});if(this._ignoreInvalidMapping){if(typeof console<"u"&&console.warn)console.warn(e);return!1}else throw Error(e)}};Wr.prototype._serializeMappings=function(){var t=0,i=1,o=0,n=0,e=0,l=0,u="",g,c,m,v,h=this._mappings.toArray();for(var b=0,f=h.length;b0){if(!ur.compareByGeneratedPositionsInflated(c,h[b-1]))continue;g+=","}if(g+=Un.encode(c.generatedColumn-t),t=c.generatedColumn,c.source!=null){if(v=this._sources.indexOf(c.source),g+=Un.encode(v-l),l=v,g+=Un.encode(c.originalLine-1-n),n=c.originalLine-1,g+=Un.encode(c.originalColumn-o),o=c.originalColumn,c.name!=null)m=this._names.indexOf(c.name),g+=Un.encode(m-e),e=m}u+=g}return u};Wr.prototype._generateSourcesContent=function(t,i){return t.map(function(o){if(!this._sourcesContents)return null;if(i!=null)o=ur.relative(i,o);var n=ur.toSetString(o);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)};Wr.prototype.toJSON=function(){var t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null)t.file=this._file;if(this._sourceRoot!=null)t.sourceRoot=this._sourceRoot;if(this._sourcesContents)t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot);return t};Wr.prototype.toString=function(){return JSON.stringify(this.toJSON())};var de=Wr;var I0=new Set(["Atrule","Selector","Declaration"]);function j0(r){let t=new de,i={line:1,column:0},o={line:0,column:0},n={line:1,column:0},e={generated:n},l=1,u=0,g=!1,c=r.node;r.node=function(h){if(h.loc&&h.loc.start&&I0.has(h.type)){let b=h.loc.start.line,f=h.loc.start.column-1;if(o.line!==b||o.column!==f){if(o.line=b,o.column=f,i.line=l,i.column=u,g){if(g=!1,i.line!==n.line||i.column!==n.column)t.addMapping(e)}g=!0,t.addMapping({source:h.loc.source,original:o,generated:i})}}if(c.call(this,h),g&&I0.has(h.type))n.line=l,n.column=u};let m=r.emit;r.emit=function(h,b,f){for(let D=0;Duz,safe:()=>rl});var ez=43,lz=45,se=(r,t)=>{if(r===P)r=t;if(typeof r==="string"){let i=r.charCodeAt(0);return i>127?32768:i<<8}return r},k0=[[w,w],[w,k],[w,er],[w,fr],[w,"-"],[w,U],[w,B],[w,L],[w,hr],[w,X],[H,w],[H,k],[H,er],[H,fr],[H,"-"],[H,U],[H,B],[H,L],[H,hr],[F,w],[F,k],[F,er],[F,fr],[F,"-"],[F,U],[F,B],[F,L],[F,hr],[L,w],[L,k],[L,er],[L,fr],[L,"-"],[L,U],[L,B],[L,L],[L,hr],["#",w],["#",k],["#",er],["#",fr],["#","-"],["#",U],["#",B],["#",L],["#",hr],["-",w],["-",k],["-",er],["-",fr],["-","-"],["-",U],["-",B],["-",L],["-",hr],[U,w],[U,k],[U,er],[U,fr],[U,U],[U,B],[U,L],[U,"%"],[U,hr],["@",w],["@",k],["@",er],["@",fr],["@","-"],["@",hr],[".",U],[".",B],[".",L],["+",U],["+",B],["+",L],["/","*"]],cz=k0.concat([[w,F],[L,F],[F,F],[H,X],[H,gr],[H,d],[B,B],[B,L],[B,k],[B,"-"],[p,w],[p,k],[p,B],[p,L],[p,F],[p,"-"]]);function U0(r){let t=new Set(r.map(([i,o])=>se(i)<<16|se(o)));return function(i,o,n){let e=se(o,n),l=n.charCodeAt(0);if(l===lz&&o!==w&&o!==k&&o!==hr||l===ez?t.has(i<<16|l<<8):t.has(i<<16|e))this.emit(" ",N,!0);return e}}var uz=U0(k0),rl=U0(cz);var gz=92;function mz(r,t){if(typeof t==="function"){let i=null;r.children.forEach((o)=>{if(i!==null)t.call(this,i);this.node(o),i=o});return}r.children.forEach(this.node,this)}function bz(r){bt(r,(t,i,o)=>{this.token(t,r.slice(i,o))})}function J0(r){let t=new Map;for(let[i,o]of Object.entries(r.node))if(typeof(o.generate||o)==="function")t.set(i,o.generate||o);return function(i,o){let n="",e=0,l={node(g){if(t.has(g.type))t.get(g.type).call(u,g);else throw Error("Unknown node type: "+g.type)},tokenBefore:rl,token(g,c){if(e=this.tokenBefore(e,g,c),this.emit(c,g,!1),g===P&&c.charCodeAt(0)===gz)this.emit(` `,N,!0)},emit(g){n+=g},result(){return n}};if(o){if(typeof o.decorator==="function")l=o.decorator(l);if(o.sourceMap)l=j0(l);if(o.mode in di)l.tokenBefore=di[o.mode]}let u={node:(g)=>l.node(g),children:mz,token:(g,c)=>l.token(g,c),tokenize:bz};return l.node(i),l.result()}}function P0(r){return{fromPlainObject(t){return r(t,{enter(i){if(i.children&&i.children instanceof or===!1)i.children=new or().fromArray(i.children)}}),t},toPlainObject(t){return r(t,{leave(i){if(i.children&&i.children instanceof or)i.children=i.children.toArray()}}),t}}}var{hasOwnProperty:tl}=Object.prototype,Jn=function(){};function E0(r){return typeof r==="function"?r:Jn}function L0(r,t){return function(i,o,n){if(i.type===t)r.call(this,i,o,n)}}function vz(r,t){let i=t.structure,o=[];for(let n in i){if(tl.call(i,n)===!1)continue;let e=i[n],l={name:n,type:!1,nullable:!1};if(!Array.isArray(e))e=[e];for(let u of e)if(u===null)l.nullable=!0;else if(typeof u==="string")l.type="node";else if(Array.isArray(u))l.type="list";if(l.type)o.push(l)}if(o.length)return{context:t.walkContext,fields:o};return null}function hz(r){let t={};for(let i in r.node)if(tl.call(r.node,i)){let o=r.node[i];if(!o.structure)throw Error("Missed `structure` field in `"+i+"` node type definition");t[i]=vz(i,o)}return t}function K0(r,t){let i=r.fields.slice(),o=r.context,n=typeof o==="string";if(t)i.reverse();return function(e,l,u,g){let c;if(n)c=l[o],l[o]=e;for(let m of i){let v=e[m.name];if(!m.nullable||v){if(m.type==="list"){if(t?v.reduceRight(g,!1):v.reduce(g,!1))return!0}else if(u(v))return!0}}if(n)l[o]=c}}function X0({StyleSheet:r,Atrule:t,Rule:i,Block:o,DeclarationList:n}){return{Atrule:{StyleSheet:r,Atrule:t,Rule:i,Block:o},Rule:{StyleSheet:r,Atrule:t,Rule:i,Block:o},Declaration:{StyleSheet:r,Atrule:t,Rule:i,Block:o,DeclarationList:n}}}function W0(r){let t=hz(r),i={},o={},n=Symbol("break-walk"),e=Symbol("skip-node");for(let c in t)if(tl.call(t,c)&&t[c]!==null)i[c]=K0(t[c],!1),o[c]=K0(t[c],!0);let l=X0(i),u=X0(o),g=function(c,m){function v(O,J,q){let E=h.call(I,O,J,q);if(E===n)return!0;if(E===e)return!1;if(f.hasOwnProperty(O.type)){if(f[O.type](O,I,v,D))return!0}if(b.call(I,O,J,q)===n)return!0;return!1}let h=Jn,b=Jn,f=i,D=(O,J,q,E)=>O||v(J,q,E),I={break:n,skip:e,root:c,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null};if(typeof m==="function")h=m;else if(m){if(h=E0(m.enter),b=E0(m.leave),m.reverse)f=o;if(m.visit){if(l.hasOwnProperty(m.visit))f=m.reverse?u[m.visit]:l[m.visit];else if(!t.hasOwnProperty(m.visit))throw Error("Bad value `"+m.visit+"` for `visit` option (should be: "+Object.keys(t).sort().join(", ")+")");h=L0(h,m.visit),b=L0(b,m.visit)}}if(h===Jn&&b===Jn)throw Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");v(c)};return g.break=n,g.skip=e,g.find=function(c,m){let v=null;return g(c,function(h,b,f){if(m.call(this,h,b,f))return v=h,n}),v},g.findLast=function(c,m){let v=null;return g(c,{reverse:!0,enter(h,b,f){if(m.call(this,h,b,f))return v=h,n}}),v},g.findAll=function(c,m){let v=[];return g(c,function(h,b,f){if(m.call(this,h,b,f))v.push(h)}),v},g}function $z(r){return r}function xz(r){let{min:t,max:i,comma:o}=r;if(t===0&&i===0)return o?"#?":"*";if(t===0&&i===1)return"?";if(t===1&&i===0)return o?"#":"+";if(t===1&&i===1)return"";return(o?"#":"")+(t===i?"{"+t+"}":"{"+t+","+(i!==0?i:"")+"}")}function fz(r){switch(r.type){case"Range":return" ["+(r.min===null?"-∞":r.min)+","+(r.max===null?"∞":r.max)+"]";default:throw Error("Unknown node type `"+r.type+"`")}}function wz(r,t,i,o){let n=r.combinator===" "||o?r.combinator:" "+r.combinator+" ",e=r.terms.map((l)=>si(l,t,i,o)).join(n);if(r.explicit||i)return(o||e[0]===","?"[":"[ ")+e+(o?"]":" ]");return e}function si(r,t,i,o){let n;switch(r.type){case"Group":n=wz(r,t,i,o)+(r.disallowEmpty?"!":"");break;case"Multiplier":return si(r.term,t,i,o)+t(xz(r),r);case"Boolean":n="";break;case"Type":n="<"+r.name+(r.opts?t(fz(r.opts),r.opts):"")+">";break;case"Property":n="<'"+r.name+"'>";break;case"Keyword":n=r.name;break;case"AtKeyword":n="@"+r.name;break;case"Function":n=r.name+"(";break;case"String":case"Token":n=r.value;break;case"Comma":n=",";break;default:throw Error("Unknown node type `"+r.type+"`")}return t(n,r)}function Rt(r,t){let i=$z,o=!1,n=!1;if(typeof t==="function")i=t;else if(t){if(o=Boolean(t.forceBraces),n=Boolean(t.compact),typeof t.decorate==="function")i=t.decorate}return si(r,i,o,n)}var q0={offset:0,line:1,column:1};function az(r,t){let{tokens:i,longestMatch:o}=r,n=o1)m=ro(e||t,"end")||Pn(q0,c),v=Pn(m);else m=ro(e,"start")||Pn(ro(t,"start")||q0,c.slice(0,l)),v=ro(e,"end")||Pn(m,c.substr(l,u));return{css:c,mismatchOffset:l,mismatchLength:u,start:m,end:v}}function ro(r,t){let i=r&&r.loc&&r.loc[t];if(i)return"line"in i?Pn(i):i;return null}function Pn({offset:r,line:t,column:i},o){let n={offset:r,line:t,column:i};if(o){let e=o.split(/\n|\r\n?|\f/);n.offset+=o.length,n.line+=e.length-1,n.column=e.length===1?n.column+o.length:e.pop().length+1}return n}var Ht=function(r,t){let i=jt("SyntaxReferenceError",r+(t?" `"+t+"`":""));return i.reference=t,i},N0=function(r,t,i,o){let n=jt("SyntaxMatchError",r),{css:e,mismatchOffset:l,mismatchLength:u,start:g,end:c}=az(o,i);return n.rawMessage=r,n.syntax=t?Rt(t):"",n.css=e,n.mismatchOffset=l,n.mismatchLength=u,n.message=r+` syntax: `+n.syntax+` value: `+(e||"")+` diff --git a/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/multi-branch-revert-modal.tsx b/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/multi-branch-revert-modal.tsx new file mode 100644 index 0000000000..cee7a27a50 --- /dev/null +++ b/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/multi-branch-revert-modal.tsx @@ -0,0 +1,183 @@ +'use client'; + +import { useState } from 'react'; + +import type { GitMessageCheckpoint } from '@onlook/models'; +import { Button } from '@onlook/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@onlook/ui/dialog'; +import { Icons } from '@onlook/ui/icons'; +import { toast } from '@onlook/ui/sonner'; +import { cn } from '@onlook/ui/utils'; + +import { useEditorEngine } from '@/components/store/editor'; +import { restoreCheckpoint } from '@/components/store/editor/git'; + +interface MultiBranchRevertModalProps { + open: boolean; + onOpenChange: (open: boolean) => void; + checkpoints: GitMessageCheckpoint[]; +} + +export const MultiBranchRevertModal = ({ + open, + onOpenChange, + checkpoints, +}: MultiBranchRevertModalProps) => { + const editorEngine = useEditorEngine(); + const [selectedBranchIds, setSelectedBranchIds] = useState([]); + const [isRestoring, setIsRestoring] = useState(false); + + const allAreSelected = selectedBranchIds.length === checkpoints.length; + + const toggleBranch = (branchId: string) => { + setSelectedBranchIds((prev) => + prev.includes(branchId) ? prev.filter((id) => id !== branchId) : [...prev, branchId], + ); + }; + + const selectAll = () => { + setSelectedBranchIds(checkpoints.map((cp) => cp.branchId).filter((id): id is string => !!id)); + }; + + const selectNone = () => { + setSelectedBranchIds([]); + }; + + const handleRevert = async () => { + try { + if (selectedBranchIds.length === 0) { + toast.error('Please select at least one branch to revert'); + return; + } + + setIsRestoring(true); + + const restorePromises = selectedBranchIds.map(async (branchId) => { + const checkpoint = checkpoints.find((cp) => cp.branchId === branchId); + if (!checkpoint) { + return { success: false }; + } + return restoreCheckpoint(checkpoint, editorEngine); + }); + + const results = await Promise.all(restorePromises); + const successCount = results.filter((r) => r.success).length; + const failCount = results.length - successCount; + + if (successCount > 0) { + toast.success( + `Successfully restored ${successCount} branch${successCount > 1 ? 'es' : ''}`, + { + description: + failCount > 0 + ? `${failCount} branch${failCount > 1 ? 'es' : ''} failed to restore` + : undefined, + }, + ); + } else if (failCount > 0) { + toast.error('Failed to restore all selected branches'); + } + } catch (error) { + toast.error('Failed to restore branches', { + description: error instanceof Error ? error.message : 'Unknown error', + }); + } finally { + + setIsRestoring(false); + onOpenChange(false); + setSelectedBranchIds([]); + } + }; + + return ( + + + + Restore Multiple Branches + + Select the branches you want to restore to their previous state. + + +
+
+ {allAreSelected ? ( + + ) : ( + + )} +
+
+ {checkpoints.map((checkpoint) => { + // Skip legacy checkpoints without branchId (shouldn't happen in multi-branch modal) + if (!checkpoint.branchId) return null; + const isSelected = selectedBranchIds.includes(checkpoint.branchId); + return ( + + ); + })} +
+
+ + + + +
+
+ ); +}; diff --git a/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/user-message.tsx b/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/user-message.tsx index 0279ffd22b..8b2858b8a7 100644 --- a/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/user-message.tsx +++ b/apps/web/client/src/app/project/[id]/_components/right-panel/chat-tab/chat-messages/user-message.tsx @@ -1,16 +1,29 @@ -import type { EditMessage } from '@/app/project/[id]/_hooks/use-chat'; -import { useEditorEngine } from '@/components/store/editor'; -import { ChatType, MessageCheckpointType, type ChatMessage } from '@onlook/models'; +import React, { useEffect, useRef, useState } from 'react'; +import { nanoid } from 'nanoid'; + +import type { ChatMessage, GitMessageCheckpoint } from '@onlook/models'; +import { ChatType, MessageCheckpointType } from '@onlook/models'; import { Button } from '@onlook/ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@onlook/ui/dropdown-menu'; import { Icons } from '@onlook/ui/icons'; import { toast } from '@onlook/ui/sonner'; import { Textarea } from '@onlook/ui/textarea'; import { Tooltip, TooltipContent, TooltipTrigger } from '@onlook/ui/tooltip'; import { cn } from '@onlook/ui/utils'; -import { nanoid } from 'nanoid'; -import React, { useEffect, useRef, useState } from 'react'; + +import type { EditMessage } from '@/app/project/[id]/_hooks/use-chat'; +import { useEditorEngine } from '@/components/store/editor'; +import { restoreCheckpoint } from '@/components/store/editor/git'; import { SentContextPill } from '../context-pills/sent-context-pill'; import { MessageContent } from './message-content'; +import { MultiBranchRevertModal } from './multi-branch-revert-modal'; interface UserMessageProps { onEditMessage: EditMessage; @@ -18,13 +31,15 @@ interface UserMessageProps { } export const getUserMessageContent = (message: ChatMessage) => { - return message.parts.map((part) => { - if (part.type === 'text') { - return part.text; - } - return ''; - }).join(''); -} + return message.parts + .map((part) => { + if (part.type === 'text') { + return part.text; + } + return ''; + }) + .join(''); +}; export const UserMessage = ({ onEditMessage, message }: UserMessageProps) => { const editorEngine = useEditorEngine(); @@ -33,11 +48,15 @@ export const UserMessage = ({ onEditMessage, message }: UserMessageProps) => { const [editValue, setEditValue] = useState(''); const [isComposing, setIsComposing] = useState(false); const [isRestoring, setIsRestoring] = useState(false); + const [isMultiBranchModalOpen, setIsMultiBranchModalOpen] = useState(false); const textareaRef = useRef(null); - const commitOid = message.metadata?.checkpoints?.find( - (s) => s.type === MessageCheckpointType.GIT, - )?.oid; + const gitCheckpoints = + message.metadata?.checkpoints?.filter((s) => s.type === MessageCheckpointType.GIT) ?? []; + + // Legacy checkpoints (created before multi-branch support) don't have branchId. + // If any exist, fall back to simple single-branch restore UI. + const hasLegacyCheckpoints = gitCheckpoints.some((cp) => !cp.branchId); useEffect(() => { if (isEditing && textareaRef.current) { @@ -81,49 +100,43 @@ export const UserMessage = ({ onEditMessage, message }: UserMessageProps) => { }; const handleRetry = async () => { - toast.promise( - onEditMessage(message.id, getUserMessageContent(message), ChatType.EDIT), - { - error: 'Failed to resubmit message', - } - ) + toast.promise(onEditMessage(message.id, getUserMessageContent(message), ChatType.EDIT), { + error: 'Failed to resubmit message', + }); }; const sendMessage = async (newContent: string) => { - toast.promise( - onEditMessage(message.id, newContent, ChatType.EDIT), - { - loading: 'Editing message...', - success: 'Message resubmitted successfully', - error: 'Failed to resubmit message', - } - ) + toast.promise(onEditMessage(message.id, newContent, ChatType.EDIT), { + loading: 'Editing message...', + success: 'Message resubmitted successfully', + error: 'Failed to resubmit message', + }); }; - const handleRestoreCheckpoint = async () => { - try { + const handleRestoreSingleBranch = async (checkpoint: GitMessageCheckpoint) => { + setIsRestoring(true); + await restoreCheckpoint(checkpoint, editorEngine); + setIsRestoring(false); + }; + + const handleRestoreLegacy = async () => { + // Legacy checkpoints without branchId will restore to the active branch + const firstCheckpoint = gitCheckpoints[0]; + if (firstCheckpoint) { setIsRestoring(true); - if (!commitOid) { - throw new Error('No commit oid found'); - } - const commit = await editorEngine.versions.getCommitByOid(commitOid); - if (!commit) { - throw new Error('Failed to get commit'); - } - const success = await editorEngine.versions.checkoutCommit(commit); - if (!success) { - throw new Error('Failed to checkout commit'); - } - } catch (error) { - console.error('Failed to restore checkpoint', error); - toast.error('Failed to restore checkpoint', { - description: error instanceof Error ? error.message : 'Unknown error', - }); - } finally { + await restoreCheckpoint(firstCheckpoint, editorEngine); setIsRestoring(false); } }; + const getBranchName = (branchId: string | undefined): string => { + if (!branchId) { + return editorEngine.branches.activeBranch.name; + } + const branch = editorEngine.branches.getBranchById(branchId); + return branch?.name || branchId; + }; + function renderEditingInput() { return (
@@ -131,7 +144,7 @@ export const UserMessage = ({ onEditMessage, message }: UserMessageProps) => { ref={textareaRef} value={editValue} onChange={(e) => setEditValue(e.target.value)} - className="text-small border-none resize-none px-0 mt-[-8px]" + className="text-small mt-[-8px] resize-none border-none px-0" rows={2} onKeyDown={handleKeyDown} onCompositionStart={() => setIsComposing(true)} @@ -151,7 +164,7 @@ export const UserMessage = ({ onEditMessage, message }: UserMessageProps) => { function renderButtons() { return ( -
+
- - - {isRestoring ? 'Restoring Checkpoint...' : 'Restore Checkpoint'} - - + {gitCheckpoints.length > 0 && ( +
+ {hasLegacyCheckpoints ? ( + + + + + + {isRestoring ? 'Restoring...' : 'Restore to here'} + + + ) : ( + <> + + + + + + + + + {isRestoring ? 'Restoring...' : 'Restore to here'} + + + Restore Branch + {gitCheckpoints.map((checkpoint) => ( + handleRestoreSingleBranch(checkpoint)} + > + {getBranchName(checkpoint.branchId)} + + ))} + {gitCheckpoints.length > 1 && ( + <> + + setIsMultiBranchModalOpen(true)} + > + Select Multiple Branches... + + + )} + + + + + + )}
)}
diff --git a/apps/web/client/src/app/project/[id]/_hooks/use-chat/index.tsx b/apps/web/client/src/app/project/[id]/_hooks/use-chat/index.tsx index 17ff63d158..fd2d431dc1 100644 --- a/apps/web/client/src/app/project/[id]/_hooks/use-chat/index.tsx +++ b/apps/web/client/src/app/project/[id]/_hooks/use-chat/index.tsx @@ -2,15 +2,16 @@ import { useEditorEngine } from '@/components/store/editor'; import { handleToolCall } from '@/components/tools'; +import { api } from '@/trpc/client'; import { useChat as useAiChat } from '@ai-sdk/react'; -import { ChatType, type ChatMessage, type MessageContext, type QueuedMessage } from '@onlook/models'; +import { ChatType, type ChatMessage, type GitMessageCheckpoint, type MessageContext, type QueuedMessage } from '@onlook/models'; import { jsonClone } from '@onlook/utility'; import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls, type FinishReason } from 'ai'; import { usePostHog } from 'posthog-js/react'; import { useCallback, useEffect, useRef, useState } from 'react'; import { v4 as uuidv4 } from 'uuid'; import { - attachCommitToUserMessage, + createCheckpointsForAllBranches, getUserChatMessageFromString } from './utils'; @@ -244,20 +245,40 @@ export function useChat({ conversationId, projectId, initialMessages }: UseChatP return; } - const { commit } = await editorEngine.versions.createCommit(content, false); - if (!commit) { - throw new Error('Failed to create commit'); + // Create checkpoints for all branches + const checkpoints = await createCheckpointsForAllBranches(editorEngine, content); + + if (checkpoints.length === 0) { + return; } - const messageWithCommit = attachCommitToUserMessage( - commit, - lastUserMessage, + // Update message with all checkpoints + const oldCheckpoints = lastUserMessage.metadata?.checkpoints.map((checkpoint) => ({ + ...checkpoint, + createdAt: new Date(checkpoint.createdAt), + })) ?? []; + + lastUserMessage.metadata = { + ...lastUserMessage.metadata, + createdAt: lastUserMessage.metadata?.createdAt ?? new Date(), conversationId, + checkpoints: [...oldCheckpoints, ...checkpoints], + context: lastUserMessage.metadata?.context ?? [], + }; + + // Save checkpoints to database (filter out legacy checkpoints without branchId) + const checkpointsWithBranchId = [...oldCheckpoints, ...checkpoints].filter( + (cp): cp is GitMessageCheckpoint & { branchId: string } => !!cp.branchId ); + void api.chat.message.updateCheckpoints.mutate({ + messageId: lastUserMessage.id, + checkpoints: checkpointsWithBranchId, + }); + setMessages( jsonClone( messagesRef.current.map((m) => - m.id === lastUserMessage.id ? messageWithCommit : m, + m.id === lastUserMessage.id ? lastUserMessage : m, ), ), ); diff --git a/apps/web/client/src/app/project/[id]/_hooks/use-chat/utils.ts b/apps/web/client/src/app/project/[id]/_hooks/use-chat/utils.ts index 6518fece12..c4c72bcc57 100644 --- a/apps/web/client/src/app/project/[id]/_hooks/use-chat/utils.ts +++ b/apps/web/client/src/app/project/[id]/_hooks/use-chat/utils.ts @@ -1,6 +1,5 @@ -import { api } from "@/trpc/client"; -import type { GitCommit } from "@onlook/git"; -import { type ChatMessage, MessageCheckpointType, type MessageContext } from "@onlook/models"; +import type { EditorEngine } from '@/components/store/editor/engine'; +import { type ChatMessage, type GitMessageCheckpoint, type MessageContext, MessageCheckpointType } from "@onlook/models"; import { v4 as uuidv4 } from 'uuid'; export const prepareMessagesForSuggestions = (messages: ChatMessage[]) => { @@ -34,35 +33,33 @@ export const getUserChatMessageFromString = ( } } +export async function createCheckpointsForAllBranches( + editorEngine: EditorEngine, + commitMessage: string, +): Promise { + const checkpoints: GitMessageCheckpoint[] = []; -export const attachCommitToUserMessage = (commit: GitCommit, message: ChatMessage, conversationId: string) => { - // Vercel converts createdAt to a string, which our API doesn't accept. - const oldCheckpoints = message.metadata?.checkpoints.map((checkpoint) => ({ - ...checkpoint, - createdAt: new Date(checkpoint.createdAt), - })) ?? []; - const newCheckpoints = [ - ...oldCheckpoints, - { - type: MessageCheckpointType.GIT, - oid: commit.oid, - createdAt: new Date(), - }, - ]; + for (const branch of editorEngine.branches.allBranches) { + const branchData = editorEngine.branches.getBranchDataById(branch.id); + if (!branchData) { + continue; + } + + const result = await branchData.sandbox.gitManager.createCommit(commitMessage); - message.metadata = { - ...message.metadata, - createdAt: message.metadata?.createdAt ?? new Date(), - conversationId, - checkpoints: newCheckpoints, - context: message.metadata?.context ?? [], - }; + if (result.success) { + const commits = branchData.sandbox.gitManager.commits; + const latestCommit = commits?.[0]; + if (latestCommit) { + checkpoints.push({ + type: MessageCheckpointType.GIT, + oid: latestCommit.oid, + branchId: branch.id, + createdAt: new Date(), + }); + } + } + } - // Very hacky - but since we only save messages when we submit a new message, we need to update the checkpoints here. - void api.chat.message.updateCheckpoints.mutate({ - messageId: message.id, - checkpoints: newCheckpoints, - }); - - return message; + return checkpoints; } diff --git a/apps/web/client/src/components/store/editor/engine.ts b/apps/web/client/src/components/store/editor/engine.ts index cc9b4ffbae..4275fc237a 100644 --- a/apps/web/client/src/components/store/editor/engine.ts +++ b/apps/web/client/src/components/store/editor/engine.ts @@ -29,7 +29,6 @@ import { StateManager } from './state'; import { StyleManager } from './style'; import { TextEditingManager } from './text'; import { ThemeManager } from './theme'; -import { VersionsManager } from './version'; export class EditorEngine { readonly projectId: string; @@ -61,7 +60,6 @@ export class EditorEngine { readonly action: ActionManager = new ActionManager(this); readonly style: StyleManager = new StyleManager(this); readonly code: CodeManager = new CodeManager(this); - readonly versions: VersionsManager = new VersionsManager(this); readonly chat: ChatManager = new ChatManager(this); readonly image: ImageManager = new ImageManager(this); readonly theme: ThemeManager = new ThemeManager(this); diff --git a/apps/web/client/src/components/store/editor/version/git.ts b/apps/web/client/src/components/store/editor/git/git.ts similarity index 60% rename from apps/web/client/src/components/store/editor/version/git.ts rename to apps/web/client/src/components/store/editor/git/git.ts index c88e94c126..9a9be384d4 100644 --- a/apps/web/client/src/components/store/editor/version/git.ts +++ b/apps/web/client/src/components/store/editor/git/git.ts @@ -1,8 +1,11 @@ -import { prepareCommitMessage, sanitizeCommitMessage } from '@/utils/git'; +import { makeAutoObservable } from 'mobx'; +import stripAnsi from 'strip-ansi'; + import { SUPPORT_EMAIL } from '@onlook/constants'; import { type GitCommit } from '@onlook/git'; -import stripAnsi from 'strip-ansi'; -import type { EditorEngine } from '../engine'; + +import { prepareCommitMessage, sanitizeCommitMessage } from '@/utils/git'; +import type { SandboxManager } from '../sandbox'; export const ONLOOK_DISPLAY_NAME_NOTE_REF = 'refs/notes/onlook-display-name'; @@ -17,14 +20,30 @@ export interface GitCommandResult { } export class GitManager { - constructor(private editorEngine: EditorEngine) { } + commits: GitCommit[] | null = null; + isLoadingCommits = false; + + constructor(private sandbox: SandboxManager) { + makeAutoObservable(this); + } + + /** + * Initialize git manager - auto-initializes repo if needed and preloads commits + */ + async init(): Promise { + const isInitialized = await this.isRepoInitialized(); + if (!isInitialized) { + await this.initRepo(); + } + await this.listCommits(); + } /** * Check if git repository is initialized */ async isRepoInitialized(): Promise { try { - return (await this.editorEngine?.activeSandbox.fileExists('.git')) || false; + return (await this.sandbox.fileExists('.git')) || false; } catch (error) { console.error('Error checking if repository is initialized:', error); return false; @@ -36,8 +55,8 @@ export class GitManager { */ async ensureGitConfig(): Promise { try { - if (!this.editorEngine.activeSandbox.session) { - console.error('No editor engine or session available'); + if (!this.sandbox.session) { + console.error('No sandbox session available'); return false; } @@ -89,8 +108,8 @@ export class GitManager { return true; } - if (!this.editorEngine.activeSandbox.session) { - console.error('No editor engine or session available'); + if (!this.sandbox.session) { + console.error('No sandbox session available'); return false; } @@ -122,7 +141,7 @@ export class GitManager { */ async getStatus(): Promise { try { - const status = await this.editorEngine?.activeSandbox.session.provider?.gitStatus({}); + const status = await this.sandbox.session.provider?.gitStatus({}); if (!status) { console.error('Failed to get git status'); return null; @@ -145,75 +164,138 @@ export class GitManager { } /** - * Create a commit + * Create a commit (low-level) - auto-refreshes commits after successful commit */ async commit(message: string): Promise { const sanitizedMessage = sanitizeCommitMessage(message); const escapedMessage = prepareCommitMessage(sanitizedMessage); - return this.runCommand(`git commit --allow-empty --no-verify -m ${escapedMessage}`); + const result = await this.runCommand(`git commit --allow-empty --no-verify -m ${escapedMessage}`); + if (result.success) { + await this.listCommits(); + } + return result; } /** - * List commits with formatted output + * Create a commit (high-level) - handles full flow: stage, config, commit */ - async listCommits(maxRetries = 2): Promise { - let lastError: Error | null = null; - - for (let attempt = 0; attempt <= maxRetries; attempt++) { - try { - // Use a more robust format with unique separators and handle multiline messages - const result = await this.runCommand( - 'git --no-pager log --pretty=format:"COMMIT_START%n%H%n%an <%ae>%n%ad%n%B%nCOMMIT_END" --date=iso', - ); + async createCommit(message: string = 'New Onlook backup'): Promise { + const status = await this.getStatus(); - if (result.success && result.output) { - return this.parseGitLog(result.output); - } + // Stage all files + const addResult = await this.stageAll(); + if (!addResult.success) { + return addResult; + } - // If git command failed but didn't throw, treat as error for retry logic - lastError = new Error(`Git command failed: ${result.error || 'Unknown error'}`); + // Ensure git config + await this.ensureGitConfig(); - if (attempt < maxRetries) { - // Wait before retry with exponential backoff - await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 100)); - continue; - } + // Create the commit + return await this.commit(message); + } - return []; - } catch (error) { - lastError = error instanceof Error ? error : new Error(String(error)); - console.warn(`Attempt ${attempt + 1} failed to list commits:`, lastError.message); + /** + * List commits with formatted output - stores results in this.commits + */ + async listCommits(maxRetries = 2): Promise { + this.isLoadingCommits = true; + let lastError: Error | null = null; - if (attempt < maxRetries) { - // Wait before retry with exponential backoff - await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 100)); - continue; + try { + for (let attempt = 0; attempt <= maxRetries; attempt++) { + try { + // Use a more robust format with unique separators and handle multiline messages + const result = await this.runCommand( + 'git --no-pager log --pretty=format:"COMMIT_START%n%H%n%an <%ae>%n%ad%n%B%nCOMMIT_END" --date=iso', + ); + + if (result.success && result.output) { + const parsedCommits = this.parseGitLog(result.output); + + // Enhance commits with display names from notes + if (parsedCommits.length > 0) { + const enhancedCommits = await Promise.all( + parsedCommits.map(async (commit) => { + const displayName = await this.getCommitNote(commit.oid); + return { + ...commit, + displayName: displayName || commit.message, + }; + }), + ); + this.commits = enhancedCommits; + return enhancedCommits; + } + + this.commits = parsedCommits; + return parsedCommits; + } + + // If git command failed but didn't throw, treat as error for retry logic + lastError = new Error(`Git command failed: ${result.error || 'Unknown error'}`); + + if (attempt < maxRetries) { + // Wait before retry with exponential backoff + await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 100)); + continue; + } + + this.commits = []; + return []; + } catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + console.warn(`Attempt ${attempt + 1} failed to list commits:`, lastError.message); + + if (attempt < maxRetries) { + // Wait before retry with exponential backoff + await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 100)); + continue; + } + + console.error('All attempts failed to list commits', lastError); + this.commits = []; + return []; } - - console.error('All attempts failed to list commits', lastError); - return []; } - } - return []; + this.commits = []; + return []; + } finally { + this.isLoadingCommits = false; + } } /** - * Checkout/restore to a specific commit + * Checkout/restore to a specific commit - auto-refreshes commits after restore */ async restoreToCommit(commitOid: string): Promise { - return this.runCommand(`git restore --source ${commitOid} .`); + const result = await this.runCommand(`git restore --source ${commitOid} .`); + if (result.success) { + await this.listCommits(); + } + return result; } /** - * Add a display name note to a commit + * Add a display name note to a commit - updates commit in local cache */ async addCommitNote(commitOid: string, displayName: string): Promise { const sanitizedDisplayName = sanitizeCommitMessage(displayName); const escapedDisplayName = prepareCommitMessage(sanitizedDisplayName); - return this.runCommand( + const result = await this.runCommand( `git --no-pager notes --ref=${ONLOOK_DISPLAY_NAME_NOTE_REF} add -f -m ${escapedDisplayName} ${commitOid}`, ); + + if (result.success && this.commits) { + // Update the commit in local cache instead of re-fetching all commits + const commitIndex = this.commits.findIndex((commit) => commit.oid === commitOid); + if (commitIndex !== -1) { + this.commits[commitIndex]!.displayName = sanitizedDisplayName; + } + } + + return result; } /** @@ -239,8 +321,8 @@ export class GitManager { /** * Run a git command through the sandbox session */ - private runCommand(command: string, ignoreError: boolean = false): Promise { - return this.editorEngine.activeSandbox.session.runCommand(command, undefined, ignoreError); + private runCommand(command: string, ignoreError = false): Promise { + return this.sandbox.session.runCommand(command, undefined, ignoreError); } /** @@ -280,7 +362,7 @@ export class GitManager { if (!hash || !authorLine || !dateLine) continue; // Parse author name and email - const authorMatch = authorLine.match(/^(.+?)\s*<(.+?)>$/); + const authorMatch = /^(.+?)\s*<(.+?)>$/.exec(authorLine); const authorName = authorMatch?.[1]?.trim() || authorLine; const authorEmail = authorMatch?.[2]?.trim() || ''; diff --git a/apps/web/client/src/components/store/editor/git/index.ts b/apps/web/client/src/components/store/editor/git/index.ts new file mode 100644 index 0000000000..fdc0b32c0b --- /dev/null +++ b/apps/web/client/src/components/store/editor/git/index.ts @@ -0,0 +1,2 @@ +export * from './git'; +export * from './utils'; diff --git a/apps/web/client/src/components/store/editor/git/utils.ts b/apps/web/client/src/components/store/editor/git/utils.ts new file mode 100644 index 0000000000..9d4b27640e --- /dev/null +++ b/apps/web/client/src/components/store/editor/git/utils.ts @@ -0,0 +1,60 @@ +import type { GitMessageCheckpoint } from '@onlook/models'; +import { toast } from '@onlook/ui/sonner'; +import type { EditorEngine } from '../engine'; + +export const BACKUP_COMMIT_MESSAGE = 'Save before restoring backup'; + +export interface RestoreResult { + success: boolean; + error?: string; +} + +/** + * Restore a branch to a specific checkpoint + * - Creates a backup commit before restoring + * - Restores the branch to the checkpoint's commit + * - Shows appropriate toast notifications + * - Falls back to active branch for legacy checkpoints without branchId + */ +export async function restoreCheckpoint( + checkpoint: GitMessageCheckpoint, + editorEngine: EditorEngine, +): Promise { + try { + // Fall back to active branch for legacy checkpoints + const targetBranchId = checkpoint.branchId ?? editorEngine.branches.activeBranch.id; + const branchData = editorEngine.branches.getBranchDataById(targetBranchId); + + if (!branchData) { + toast.error('Branch not found'); + return { success: false, error: 'Branch not found' }; + } + + // Save current state before restoring + const saveResult = await branchData.sandbox.gitManager.createCommit(BACKUP_COMMIT_MESSAGE); + if (!saveResult.success) { + toast.warning('Failed to save before restoring backup'); + } + + // Restore to the specified commit + const restoreResult = await branchData.sandbox.gitManager.restoreToCommit(checkpoint.oid); + + if (!restoreResult.success) { + throw new Error(restoreResult.error || 'Failed to restore commit'); + } + + const branchName = editorEngine.branches.getBranchById(targetBranchId)?.name || targetBranchId; + toast.success('Restored to backup!', { + description: `Branch "${branchName}" has been restored`, + }); + + return { success: true }; + } catch (error) { + console.error('Failed to restore checkpoint:', error); + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; + toast.error('Failed to restore checkpoint', { + description: errorMessage, + }); + return { success: false, error: errorMessage }; + } +} diff --git a/apps/web/client/src/components/store/editor/sandbox/index.ts b/apps/web/client/src/components/store/editor/sandbox/index.ts index 8f13c5b0ca..4a9f1c5a27 100644 --- a/apps/web/client/src/components/store/editor/sandbox/index.ts +++ b/apps/web/client/src/components/store/editor/sandbox/index.ts @@ -7,12 +7,14 @@ import type { Branch, RouterConfig } from '@onlook/models'; import { makeAutoObservable, reaction } from 'mobx'; import type { EditorEngine } from '../engine'; import type { ErrorManager } from '../error'; +import { GitManager } from '../git'; import { detectRouterConfig } from '../pages/helper'; import { copyPreloadScriptToPublic, getLayoutPath as detectLayoutPath } from './preload-script'; import { SessionManager } from './session'; export class SandboxManager { readonly session: SessionManager; + readonly gitManager: GitManager; private providerReactionDisposer?: () => void; private sync: CodeProviderSync | null = null; preloadScriptInjected: boolean = false; @@ -26,15 +28,18 @@ export class SandboxManager { private readonly fs: CodeFileSystem, ) { this.session = new SessionManager(this.branch, this.errorManager); + this.gitManager = new GitManager(this); makeAutoObservable(this); } async init() { this.providerReactionDisposer = reaction( () => this.session.provider, - (provider) => { + async (provider) => { if (provider) { - this.initializeSyncEngine(provider); + await this.initializeSyncEngine(provider); + // Initialize git after provider is ready + await this.gitManager.init(); } else if (this.sync) { // If the provider is null, stop the sync engine this.sync.stop(); diff --git a/apps/web/client/src/components/store/editor/version/index.ts b/apps/web/client/src/components/store/editor/version/index.ts deleted file mode 100644 index db31848334..0000000000 --- a/apps/web/client/src/components/store/editor/version/index.ts +++ /dev/null @@ -1,326 +0,0 @@ -import { sanitizeCommitMessage } from '@/utils/git'; -import { type GitCommit } from '@onlook/git'; -import { toast } from '@onlook/ui/sonner'; -import { makeAutoObservable } from 'mobx'; -import type { EditorEngine } from '../engine'; -import { GitManager } from './git'; - -export enum CreateCommitFailureReason { - NOT_INITIALIZED = 'NOT_INITIALIZED', - FAILED_TO_SAVE = 'FAILED_TO_SAVE', - COMMIT_IN_PROGRESS = 'COMMIT_IN_PROGRESS', -} - -export class VersionsManager { - commits: GitCommit[] | null = null; - savedCommits: GitCommit[] = []; - isSaving = false; - isLoadingCommits = false; - private gitManager: GitManager; - private listCommitsPromise: Promise | null = null; - - constructor(private editorEngine: EditorEngine) { - makeAutoObservable(this); - this.gitManager = new GitManager(editorEngine); - } - - initializeRepo = async () => { - const isInitialized = await this.gitManager.isRepoInitialized(); - - if (!isInitialized) { - await this.gitManager.initRepo(); - await this.createCommit('Initial commit'); - } - - await this.listCommits(); - }; - - get latestCommit() { - if (!this.commits || this.commits.length === 0) { - return undefined; - } - return this.commits[0]; - } - - createCommit = async ( - message = 'New Onlook backup', - showToast = true, - ): Promise<{ - success: boolean; - commit: GitCommit | null; - errorReason?: CreateCommitFailureReason; - }> => { - try { - if (this.isSaving) { - if (showToast) { - toast.error('Backup already in progress'); - } - return { - success: false, - commit: null, - errorReason: CreateCommitFailureReason.COMMIT_IN_PROGRESS, - }; - } - - const isInitialized = await this.gitManager.isRepoInitialized(); - if (!isInitialized) { - await this.gitManager.initRepo(); - } - - const status = await this.gitManager.getStatus(); - - if (!status) { - if (showToast) { - toast.error('Could not create backup, please initialize a git repository'); - } - - return { - success: false, - commit: null, - errorReason: CreateCommitFailureReason.NOT_INITIALIZED, - }; - } - - // Stage all files - const addResult = await this.gitManager.stageAll(); - if (!addResult.success) { - if (showToast) { - toast.error('Failed to stage files for commit'); - } - return { - success: false, - commit: null, - errorReason: CreateCommitFailureReason.FAILED_TO_SAVE, - }; - } - - //Check config is set - await this.gitManager.ensureGitConfig(); - - // Create the commit with sanitized message - const sanitizedMessage = sanitizeCommitMessage(message); - const commitResult = await this.gitManager.commit(sanitizedMessage); - if (!commitResult.success) { - if (showToast) { - toast.error('Failed to create backup'); - } - return { - success: false, - commit: null, - errorReason: CreateCommitFailureReason.FAILED_TO_SAVE, - }; - } - - // Refresh the commits list after creating commit - const commits = await this.listCommits(); - - if (showToast) { - toast.success('Backup created successfully!', { - description: `Created backup: "${sanitizedMessage}"`, - }); - } - this.isSaving = true; - - this.editorEngine.posthog.capture('versions_create_commit_success', { - message: sanitizedMessage, - }); - - const latestCommit = commits.length > 0 ? commits[0] ?? null : null; - return { - success: true, - commit: latestCommit, - }; - } catch (error) { - if (showToast) { - toast.error('Failed to create backup'); - } - this.editorEngine.posthog.capture('versions_create_commit_failed', { - message, - error: error instanceof Error ? error.message : 'Unknown error', - }); - return { - success: false, - commit: null, - errorReason: CreateCommitFailureReason.FAILED_TO_SAVE, - }; - } finally { - this.isSaving = false; - } - }; - - listCommits = async (): Promise => { - // Return existing promise if already in progress - if (this.listCommitsPromise) { - return this.listCommitsPromise; - } - - // Create and store the promise - this.listCommitsPromise = this.performListCommits(); - - try { - const result = await this.listCommitsPromise; - return result; - } finally { - // Clear the promise when complete - this.listCommitsPromise = null; - } - }; - - private performListCommits = async (): Promise => { - try { - this.isLoadingCommits = true; - this.commits = await this.gitManager.listCommits(); - - // Enhance commits with display names from notes - if (this.commits.length > 0) { - const enhancedCommits = await Promise.all( - this.commits.map(async (commit) => { - const displayName = await this.gitManager.getCommitNote(commit.oid); - return { - ...commit, - displayName: displayName || commit.message, - }; - }), - ); - this.commits = enhancedCommits; - } - return this.commits; - } catch (error) { - this.commits = []; - return []; - } finally { - this.isLoadingCommits = false; - } - }; - - getCommitByOid = async (oid: string): Promise => { - if (!this.commits) { - this.commits = await this.gitManager.listCommits(); - } - const commit = this.commits.find((commit) => commit.oid === oid); - if (!commit) { - return null; - } - return commit; - }; - - checkoutCommit = async (commit: GitCommit): Promise => { - this.editorEngine.posthog.capture('versions_checkout_commit', { - commit: commit.displayName || commit.message, - }); - const res = await this.createCommit('Save before restoring backup', false); - - // If failed to create commit, warn the user but continue - if (!res?.success) { - toast.warning('Failed to save before restoring backup'); - } - - const restoreResult = await this.gitManager.restoreToCommit(commit.oid); - if (!restoreResult.success) { - toast.error('Failed to restore backup'); - this.editorEngine.posthog.capture('versions_checkout_commit_failed', { - commit: commit.displayName || commit.message, - error: restoreResult.error, - }); - return false; - } - - toast.success(`Restored to backup!`, { - description: `Your project has been restored to version "${commit.displayName || commit.message}"`, - }); - - await this.listCommits(); - - this.editorEngine.posthog.capture('versions_checkout_commit_success', { - commit: commit.displayName || commit.message, - }); - return true; - }; - - renameCommit = async (commitOid: string, newName: string): Promise => { - try { - this.editorEngine.posthog.capture('versions_rename_commit', { - commit: commitOid, - newName, - }); - - const result = await this.gitManager.addCommitNote(commitOid, newName); - if (!result.success) { - toast.error('Failed to rename backup'); - return false; - } - - if (this.commits) { - const commitIndex = this.commits.findIndex((commit) => commit.oid === commitOid); - if (commitIndex !== -1) { - this.commits[commitIndex]!.displayName = newName; - } - } - - const savedCommitIndex = this.savedCommits.findIndex( - (commit) => commit.oid === commitOid, - ); - if (savedCommitIndex !== -1) { - this.savedCommits[savedCommitIndex]!.displayName = newName; - } - - toast.success('Backup renamed successfully!', { - description: `Renamed to: "${newName}"`, - }); - - this.editorEngine.posthog.capture('versions_rename_commit_success', { - commit: commitOid, - newName, - }); - - return true; - } catch (error) { - toast.error('Failed to rename backup'); - this.editorEngine.posthog.capture('versions_rename_commit_failed', { - commit: commitOid, - newName, - error: error instanceof Error ? error.message : 'Unknown error', - }); - return false; - } - }; - - saveCommit = async (commit: GitCommit) => { - if (this.savedCommits.some((c) => c.oid === commit.oid)) { - toast.error('Backup already saved'); - return; - } - this.savedCommits?.push(commit); - toast.success('Backup bookmarked!'); - - this.editorEngine.posthog.capture('versions_save_commit', { - commit: commit.displayName || commit.message, - }); - }; - - removeSavedCommit = async (commit: GitCommit) => { - this.savedCommits = this.savedCommits.filter((c) => c.oid !== commit.oid); - - this.editorEngine.posthog.capture('versions_remove_saved_commit', { - commit: commit.displayName || commit.message, - }); - }; - - saveLatestCommit = async (): Promise => { - if (!this.commits || this.commits.length === 0) { - toast.error('No backups found'); - return; - } - const latestCommit = this.commits[0]; - - if (!latestCommit) { - toast.error('No backups found'); - return; - } - - await this.saveCommit(latestCommit); - toast.success('Latest backup bookmarked!'); - }; - - dispose() { } -} diff --git a/apps/web/client/src/components/ui/settings-modal/versions/empty-state/saved.tsx b/apps/web/client/src/components/ui/settings-modal/versions/empty-state/saved.tsx deleted file mode 100644 index 81c9589a98..0000000000 --- a/apps/web/client/src/components/ui/settings-modal/versions/empty-state/saved.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { useEditorEngine } from '@/components/store/editor'; -import { Button } from '@onlook/ui/button'; -import { Icons } from '@onlook/ui/icons/index'; -import { observer } from 'mobx-react-lite'; - -export const NoSavedVersions = observer(() => { - const editorEngine = useEditorEngine(); - - const handleSaveLatestCommit = async () => { - editorEngine.versions?.saveLatestCommit(); - }; - - return ( -
-
No saved versions
-
- Your saved backups will appear here -
- -
- ); -}); \ No newline at end of file diff --git a/apps/web/client/src/components/ui/settings-modal/versions/empty-state/version.tsx b/apps/web/client/src/components/ui/settings-modal/versions/empty-state/version.tsx index b2f3b7fddf..2d6bec86c0 100644 --- a/apps/web/client/src/components/ui/settings-modal/versions/empty-state/version.tsx +++ b/apps/web/client/src/components/ui/settings-modal/versions/empty-state/version.tsx @@ -1,10 +1,39 @@ import { useEditorEngine } from '@/components/store/editor'; import { Button } from '@onlook/ui/button'; import { Icons } from '@onlook/ui/icons/index'; +import { toast } from '@onlook/ui/sonner'; import { observer } from 'mobx-react-lite'; +import { useState } from 'react'; export const NoVersions = observer(() => { const editorEngine = useEditorEngine(); + const [isCreating, setIsCreating] = useState(false); + + const handleCreateBackup = async () => { + try { + setIsCreating(true); + const branchData = editorEngine.branches.activeBranchData; + + if (!branchData) { + throw new Error('No active branch available to create backup'); + } + + const result = await branchData.sandbox.gitManager.createCommit('Initial commit'); + if (!result.success) { + throw new Error(result.error || 'Failed to create backup'); + } + + toast.success('Backup created successfully!'); + editorEngine.posthog.capture('versions_create_first_commit'); + } catch (error) { + toast.error('Failed to create backup', { + description: error instanceof Error ? error.message : 'Unknown error', + }); + } finally { + setIsCreating(false); + } + }; + return (
No backups
@@ -14,15 +43,15 @@ export const NoVersions = observer(() => {
); diff --git a/apps/web/client/src/components/ui/settings-modal/versions/index.tsx b/apps/web/client/src/components/ui/settings-modal/versions/index.tsx index 34e209c3ab..4557c31dc7 100644 --- a/apps/web/client/src/components/ui/settings-modal/versions/index.tsx +++ b/apps/web/client/src/components/ui/settings-modal/versions/index.tsx @@ -1,14 +1,6 @@ -import { useEditorEngine } from '@/components/store/editor'; -import { useEffect } from 'react'; import { Versions } from './versions'; export const VersionsTab = () => { - const editorEngine = useEditorEngine(); - - useEffect(() => { - editorEngine.versions.listCommits(); - }, []); - return (
diff --git a/apps/web/client/src/components/ui/settings-modal/versions/saved-version.tsx b/apps/web/client/src/components/ui/settings-modal/versions/saved-version.tsx deleted file mode 100644 index 477cf5720d..0000000000 --- a/apps/web/client/src/components/ui/settings-modal/versions/saved-version.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { useEditorEngine } from '@/components/store/editor'; -import { Separator } from '@onlook/ui/separator'; -import { observer } from 'mobx-react-lite'; -import { VersionRow, VersionRowType } from './version-row'; -import { NoSavedVersions } from './empty-state/saved'; - -export const SavedVersions = observer(() => { - const editorEngine = useEditorEngine(); - const commits = editorEngine.versions.savedCommits; - - return ( -
-

Saved Versions

- - {commits && commits.length > 0 ? ( -
- {commits?.map((commit) => ( - - ))} -
- ) : ( - - )} -
- ); -}); \ No newline at end of file diff --git a/apps/web/client/src/components/ui/settings-modal/versions/version-row.tsx b/apps/web/client/src/components/ui/settings-modal/versions/version-row.tsx index f23e7c85d6..9b818e526b 100644 --- a/apps/web/client/src/components/ui/settings-modal/versions/version-row.tsx +++ b/apps/web/client/src/components/ui/settings-modal/versions/version-row.tsx @@ -1,16 +1,19 @@ -import { useEditorEngine } from '@/components/store/editor'; -import { useStateManager } from '@/components/store/state'; +import { observer } from 'mobx-react-lite'; +import { useEffect, useRef, useState } from 'react'; + import type { GitCommit } from '@onlook/git'; +import { MessageCheckpointType } from '@onlook/models'; import { Button } from '@onlook/ui/button'; import { Icons } from '@onlook/ui/icons'; import { Input } from '@onlook/ui/input'; import { toast } from '@onlook/ui/sonner'; import { Tooltip, TooltipContent, TooltipTrigger } from '@onlook/ui/tooltip'; - import { cn } from '@onlook/ui/utils'; import { formatCommitDate, timeAgo } from '@onlook/utility'; -import { observer } from 'mobx-react-lite'; -import { useEffect, useRef, useState } from 'react'; + +import { useEditorEngine } from '@/components/store/editor'; +import { restoreCheckpoint } from '@/components/store/editor/git'; +import { useStateManager } from '@/components/store/state'; export enum VersionRowType { SAVED = 'saved', @@ -64,8 +67,33 @@ export const VersionRow = observer( }); }; - const updateCommitDisplayName = (name: string) => { - editorEngine.versions.renameCommit(commit.oid, name); + const updateCommitDisplayName = async (name: string) => { + const branchData = editorEngine.branches.activeBranchData; + if (!branchData) { + toast.error('No active branch'); + return; + } + + const result = await branchData.sandbox.gitManager.addCommitNote(commit.oid, name); + + if (!result.success) { + toast.error('Failed to rename backup'); + editorEngine.posthog.capture('versions_rename_commit_failed', { + commit: commit.oid, + newName: name, + error: result.error, + }); + return; + } + + toast.success('Backup renamed successfully!', { + description: `Renamed to: "${name}"`, + }); + + editorEngine.posthog.capture('versions_rename_commit_success', { + commit: commit.oid, + newName: name, + }); }; const startRenaming = () => { @@ -83,82 +111,92 @@ export const VersionRow = observer( }; const handleCheckout = async () => { - setIsCheckingOut(true); - const success = await editorEngine.versions.checkoutCommit(commit); - setIsCheckingOut(false); - setIsCheckoutSuccess(success ?? false); - - if (!success) { - console.error('Failed to checkout commit', commit.displayName || commit.message); - toast.error('Failed to restore'); - return; + try { + setIsCheckingOut(true); + + editorEngine.posthog.capture('versions_checkout_commit', { + commit: commit.displayName ?? commit.message, + }); + + const checkpoint = { + type: MessageCheckpointType.GIT, + oid: commit.oid, + branchId: editorEngine.branches.activeBranch.id, + createdAt: new Date(), + }; + + const result = await restoreCheckpoint(checkpoint, editorEngine); + + setIsCheckingOut(false); + + if (!result.success) { + editorEngine.posthog.capture('versions_checkout_commit_failed', { + commit: commit.displayName || commit.message, + error: result.error, + }); + setIsCheckoutSuccess(false); + return; + } + + editorEngine.posthog.capture('versions_checkout_commit_success', { + commit: commit.displayName || commit.message, + }); + + setIsCheckoutSuccess(true); + setTimeout(() => { + stateManager.isSettingsModalOpen = false; + }, 1000); + } catch (error) { + toast.error('Failed to restore backup', { + description: error instanceof Error ? error.message : 'Unknown error', + }); + } finally { + setIsCheckingOut(false); } - setTimeout(() => { - stateManager.isSettingsModalOpen = false; - }, 1000); }; return (
- {isRenaming ? ( - setCommitDisplayName(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === 'Escape') { - e.currentTarget.blur(); - } - }} - onBlur={finishRenaming} - className="p-0 pl-2 h-8 border border-transparent hover:border-border/50 focus-visible:border-primary/10 focus-visible:ring-0 focus-visible:outline-none focus-visible:bg-transparent bg-transparent hover:bg-transparent transition-all duration-100" - /> - ) : ( - {commit.displayName ?? commit.message ?? 'Backup'} - )} +
+ {isRenaming ? ( + setCommitDisplayName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === 'Escape') { + e.currentTarget.blur(); + } + }} + onBlur={finishRenaming} + className="hover:border-border/50 focus-visible:border-primary/10 -mt-0.5 -ml-[10px] h-8 w-full border border-transparent bg-transparent p-0 pl-2 transition-all duration-100 hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:outline-none" + /> + ) : ( + {commit.displayName ?? commit.message ?? 'Backup'} + )} +
{commit.author.name}{' '} - {' '} + {' '} {renderDate()}
- +
- {type === VersionRowType.SAVED ? ( - - ) : ( - - )} {isCheckoutSuccess ? ( @@ -191,7 +229,7 @@ export const VersionRow = observer( onClick={handleCheckout} disabled={isCheckingOut} > - + {isCheckingOut ? 'Restoring...' : 'Restore'} @@ -203,4 +241,4 @@ export const VersionRow = observer(
); }, -); \ No newline at end of file +); diff --git a/apps/web/client/src/components/ui/settings-modal/versions/versions.tsx b/apps/web/client/src/components/ui/settings-modal/versions/versions.tsx index 0a381ae631..1b81fcd131 100644 --- a/apps/web/client/src/components/ui/settings-modal/versions/versions.tsx +++ b/apps/web/client/src/components/ui/settings-modal/versions/versions.tsx @@ -2,6 +2,7 @@ import { useEditorEngine } from '@/components/store/editor'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@onlook/ui/accordion'; import { Button } from '@onlook/ui/button'; import { Icons } from '@onlook/ui/icons/index'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@onlook/ui/select'; import { Separator } from '@onlook/ui/separator'; import { toast } from '@onlook/ui/sonner'; import { observer } from 'mobx-react-lite'; @@ -11,9 +12,13 @@ import { VersionRow, VersionRowType } from './version-row'; export const Versions = observer(() => { const editorEngine = useEditorEngine(); - const commits = editorEngine.versions.commits; - const isLoadingCommits = editorEngine.versions.isLoadingCommits; const [commitToRename, setCommitToRename] = useState(null); + const [isCreatingBackup, setIsCreatingBackup] = useState(false); + const selectedBranchId = editorEngine.branches.activeBranch.id; + const branchData = editorEngine.branches.getBranchDataById(selectedBranchId); + const gitManager = branchData?.sandbox.gitManager; + const commits = gitManager?.commits; + const isLoadingCommits = gitManager?.isLoadingCommits; // Group commits by date const groupedCommits = commits?.reduce( @@ -47,44 +52,76 @@ export const Versions = observer(() => { ); const handleNewBackup = async () => { - const res = await editorEngine.versions.createCommit(); - if (!res?.success) { - toast.error('Failed to create commit', { - description: res?.errorReason, + try { + setIsCreatingBackup(true); + if (!gitManager) { + toast.error('Git not initialized'); + return; + } + + const result = await gitManager.createCommit(); + if (!result.success) { + toast.error('Failed to create backup', { + description: result.error || 'Unknown error', + }); + return; + } + + toast.success('Backup created successfully!'); + editorEngine.posthog.capture('versions_create_commit_success'); + + const latestCommit = gitManager.commits?.[0]; + if (!latestCommit) { + console.error('No latest commit found'); + return; + } + setCommitToRename(latestCommit.oid); + } catch (error) { + toast.error('Failed to create backup', { + description: error instanceof Error ? error.message : 'Unknown error', }); - return; - } - const latestCommit = editorEngine.versions.latestCommit; - if (!latestCommit) { - console.error('No latest commit found'); - return; + } finally { + setIsCreatingBackup(false); } - setCommitToRename(latestCommit.oid); }; return (
-
-

Versions

+
+

Backup Versions

+ {isLoadingCommits && ( )} - {commits && commits.length > 0 ? ( + + {/* Branch selector */} + + {gitManager && ( - ) : null} + )}
diff --git a/apps/web/client/src/server/api/routers/chat/message.ts b/apps/web/client/src/server/api/routers/chat/message.ts index 30c9a64e06..a8ee15fa16 100644 --- a/apps/web/client/src/server/api/routers/chat/message.ts +++ b/apps/web/client/src/server/api/routers/chat/message.ts @@ -71,6 +71,7 @@ export const messageRouter = createTRPCRouter({ checkpoints: z.array(z.object({ type: z.enum(MessageCheckpointType), oid: z.string(), + branchId: z.string(), createdAt: z.date(), })), })) diff --git a/packages/models/src/chat/message/checkpoint.ts b/packages/models/src/chat/message/checkpoint.ts index 251ae59fa0..0736ae0027 100644 --- a/packages/models/src/chat/message/checkpoint.ts +++ b/packages/models/src/chat/message/checkpoint.ts @@ -10,6 +10,7 @@ interface BaseMessageCheckpoint { export interface GitMessageCheckpoint extends BaseMessageCheckpoint { type: MessageCheckpointType.GIT; oid: string; + branchId?: string; // Optional for backwards compatibility with old checkpoints } export type MessageCheckpoints = GitMessageCheckpoint;