orquesta-embed 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/version.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/vanilla.js +1 -1
- package/dist/vanilla.min.js +1 -1
- package/package.json +1 -1
package/dist/vanilla.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Orquesta=function(t){"use strict";const e=Object.create(null);e.open="0",e.close="1",e.ping="2",e.pong="3",e.message="4",e.upgrade="5",e.noop="6";const n=Object.create(null);Object.keys(e).forEach(t=>{n[e[t]]=t});const i={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,a=({type:t,data:n},i,a)=>s&&n instanceof Blob?i?a(n):l(n,a):o&&(n instanceof ArrayBuffer||r(n))?i?a(n):l(new Blob([n]),a):a(e[t]+(n||"")),l=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let p;const d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)h[d.charCodeAt(t)]=t;const u="function"==typeof ArrayBuffer,m=(t,e)=>{if("string"!=typeof t)return{type:"message",data:f(t,e)};const s=t.charAt(0);if("b"===s)return{type:"message",data:g(t.substring(1),e)};return n[s]?t.length>1?{type:n[s],data:t.substring(1)}:{type:n[s]}:i},g=(t,e)=>{if(u){const n=(t=>{let e,n,i,s,o,r=.75*t.length,a=t.length,l=0;"="===t[t.length-1]&&(r--,"="===t[t.length-2]&&r--);const c=new ArrayBuffer(r),p=new Uint8Array(c);for(e=0;e<a;e+=4)n=h[t.charCodeAt(e)],i=h[t.charCodeAt(e+1)],s=h[t.charCodeAt(e+2)],o=h[t.charCodeAt(e+3)],p[l++]=n<<2|i>>4,p[l++]=(15&i)<<4|s>>2,p[l++]=(3&s)<<6|63&o;return c})(t);return f(n,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,b=String.fromCharCode(30);function x(){return new TransformStream({transform(t,e){!function(t,e){s&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):o&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):a(t,!1,t=>{p||(p=new TextEncoder),e(p.encode(t))})}(t,n=>{const i=n.length;let s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);const t=new DataView(s.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{s=new Uint8Array(9);const t=new DataView(s.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(s[0]|=128),e.enqueue(s),e.enqueue(n)})}})}let y;function w(t){return t.reduce((t,e)=>t+e.length,0)}function C(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let i=0;for(let s=0;s<e;s++)n[s]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),n}function v(t){if(t)return function(t){for(var e in v.prototype)t[e]=v.prototype[e];return t}(t)}v.prototype.on=v.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},v.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},v.prototype.off=v.prototype.removeListener=v.prototype.removeAllListeners=v.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<i.length;s++)if((n=i[s])===e||n.fn===e){i.splice(s,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},v.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(n){i=0;for(var s=(n=n.slice(0)).length;i<s;++i)n[i].apply(this,e)}return this},v.prototype.emitReserved=v.prototype.emit,v.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},v.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),S="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function q(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const E=S.setTimeout,_=S.clearTimeout;function R(t,e){e.useNativeTimers?(t.setTimeoutFn=E.bind(S),t.clearTimeoutFn=_.bind(S)):(t.setTimeoutFn=S.setTimeout.bind(S),t.clearTimeoutFn=S.clearTimeout.bind(S))}function O(t){return"string"==typeof t?function(t){let e=0,n=0;for(let i=0,s=t.length;i<s;i++)e=t.charCodeAt(i),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function T(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class A extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class N extends v{constructor(t){super(),this.writable=!1,R(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new A(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=m(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class B extends N{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const n=t.split(b),i=[];for(let t=0;t<n.length;t++){const s=m(n[t],e);if(i.push(s),"error"===s.type)break}return i})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,i=new Array(n);let s=0;t.forEach((t,o)=>{a(t,!1,t=>{i[o]=t,++s===n&&e(i.join(b))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=T()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let z=!1;try{z="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const L=z;function M(){}class H extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class P extends v{constructor(t,e,n){super(),this.createRequest=t,R(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=q(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=P.requestsCount++,P.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=M,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete P.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(P.requestsCount=0,P.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",I);else if("function"==typeof addEventListener){addEventListener("onpagehide"in S?"pagehide":"unload",I,!1)}function I(){for(let t in P.requests)P.requests.hasOwnProperty(t)&&P.requests[t].abort()}const F=function(){const t=j({xdomain:!1});return t&&null!==t.responseType}();function j(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||L))return new XMLHttpRequest}catch(t){}if(!e)try{return new(S[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const $="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class D extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=$?{}:q(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;a(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=T()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const U=S.WebSocket||S.MozWebSocket;const W={websocket:class extends D{createSocket(t,e,n){return $?new U(t,e,n):e?new U(t,e):new U(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){y||(y=new TextDecoder);const n=[];let s=0,o=-1,r=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(0===s){if(w(n)<1)break;const t=C(n,1);r=!(128&~t[0]),o=127&t[0],s=o<126?3:126===o?1:2}else if(1===s){if(w(n)<2)break;const t=C(n,2);o=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),s=3}else if(2===s){if(w(n)<8)break;const t=C(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){l.enqueue(i);break}o=r*Math.pow(2,32)+e.getUint32(4),s=3}else{if(w(n)<o)break;const t=C(n,o);l.enqueue(m(r?t:y.decode(t),e)),s=0}if(0===o||o>t){l.enqueue(i);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),s=x();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const o=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),o())}).catch(t=>{})};o();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;this._writer.write(n).then(()=>{i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends H{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=F&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new P(j,this.uri(),t)}}},V=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,X=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),i=t.indexOf("]");-1!=n&&-1!=i&&(t=t.substring(0,n)+t.substring(n,i).replace(/:/g,";")+t.substring(i,t.length));let s=V.exec(t||""),o={},r=14;for(;r--;)o[X[r]]=s[r]||"";return-1!=n&&-1!=i&&(o.source=e,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=function(t,e){const n=/\/{2,9}/g,i=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1);"/"==e.slice(-1)&&i.splice(i.length-1,1);return i}(0,o.path),o.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(n[e]=i)}),n}(0,o.query),o}const Q="function"==typeof addEventListener&&"function"==typeof removeEventListener,Y=[];Q&&addEventListener("offline",()=>{Y.forEach(t=>t())},!1);class J extends v{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const n=K(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=K(e.host).host);R(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},n=t.split("&");for(let t=0,i=n.length;t<i;t++){let i=n[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),Q&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Y.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&J.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",J.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=O(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,k(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const s={type:t,data:e,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(J.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Q&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=Y.indexOf(this._offlineEventListener);-1!==t&&Y.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}J.protocol=4;class G extends J{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;J.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;J.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function s(){n||(n=!0,c(),e.close(),e=null)}const o=t=>{const n=new Error("probe error: "+t);n.transport=e.name,s(),this.emitReserved("upgradeError",n)};function r(){o("transport closed")}function a(){o("socket closed")}function l(t){e&&t.name!==e.name&&s()}const c=()=>{e.removeListener("open",i),e.removeListener("error",o),e.removeListener("close",r),this.off("close",a),this.off("upgrading",l)};e.once("open",i),e.once("error",o),e.once("close",r),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let Z=class extends G{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>W[t]).filter(t=>!!t)),super(t,n)}};const tt="function"==typeof ArrayBuffer,et=Object.prototype.toString,nt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===et.call(Blob),it="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===et.call(File);function st(t){return tt&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||nt&&t instanceof Blob||it&&t instanceof File}function ot(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(ot(t[e]))return!0;return!1}if(st(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return ot(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&ot(t[e]))return!0;return!1}function rt(t){const e=[],n=t.data,i=t;return i.data=at(n,e),i.attachments=e.length,{packet:i,buffers:e}}function at(t,e){if(!t)return t;if(st(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=at(t[i],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=at(t[i],e));return n}return t}function lt(t,e){return t.data=ct(t.data,e),delete t.attachments,t}function ct(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=ct(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=ct(t[n],e));return t}const pt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var dt;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(dt||(dt={}));class ht extends v{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===dt.BINARY_EVENT;n||e.type===dt.BINARY_ACK?(e.type=n?dt.EVENT:dt.ACK,this.reconstructor=new ut(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!st(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===dt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===dt.BINARY_EVENT||n.type===dt.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const s=t.substring(i,e);if(s!=Number(s)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const o=Number(s);if(!mt(o)||o<0)throw new Error("Illegal attachments");if(o>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=o}if("/"===t.charAt(e+1)){const i=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(i,e)}else n.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!ht.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case dt.CONNECT:return gt(e);case dt.DISCONNECT:return void 0===e;case dt.CONNECT_ERROR:return"string"==typeof e||gt(e);case dt.EVENT:case dt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===pt.indexOf(e[0]));case dt.ACK:case dt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ut{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=lt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const mt=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function gt(t){return"[object Object]"===Object.prototype.toString.call(t)}var ft=Object.freeze({__proto__:null,Decoder:ht,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==dt.EVENT&&t.type!==dt.ACK||!ot(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===dt.EVENT?dt.BINARY_EVENT:dt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==dt.BINARY_EVENT&&t.type!==dt.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=rt(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}},get PacketType(){return dt},isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||mt(e))&&function(t,e){switch(t){case dt.CONNECT:return void 0===e||gt(e);case dt.DISCONNECT:return void 0===e;case dt.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===pt.indexOf(e[0]));case dt.ACK:return Array.isArray(e);case dt.CONNECT_ERROR:return"string"==typeof e||gt(e);default:return!1}}(t.type,t.data);var e},protocol:5});function bt(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const xt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class yt extends v{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[bt(t,"open",this.onopen.bind(this)),bt(t,"packet",this.onpacket.bind(this)),bt(t,"error",this.onerror.bind(this)),bt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,i,s;if(xt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:dt.EVENT,data:e,options:{}};if(o.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),o.id=t}const r=null===(i=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!r||(a?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const s=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),o=(...t)=>{this.io.clearTimeoutFn(s),e.apply(this,t)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,i)=>{const s=(t,e)=>t?i(t):n(e);s.withError=!0,e.push(s),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>{this._queue[0];return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:dt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case dt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case dt.EVENT:case dt.BINARY_EVENT:this.onevent(t);break;case dt.ACK:case dt.BINARY_ACK:this.onack(t);break;case dt.DISCONNECT:this.ondisconnect();break;case dt.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...i){n||(n=!0,e.packet({type:dt.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:dt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function wt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}wt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},wt.prototype.reset=function(){this.attempts=0},wt.prototype.setMin=function(t){this.ms=t},wt.prototype.setMax=function(t){this.max=t},wt.prototype.setJitter=function(t){this.jitter=t};class Ct extends v{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,R(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||ft;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Z(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=bt(e,"open",function(){n.onopen(),t&&t()}),s=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},o=bt(e,"error",s);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{i(),s(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(i),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(bt(t,"ping",this.onping.bind(this)),bt(t,"data",this.ondata.bind(this)),bt(t,"error",this.onerror.bind(this)),bt(t,"close",this.onclose.bind(this)),bt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new yt(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const vt={};function kt(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let i=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),i=K(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const s=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+e,i.href=i.protocol+"://"+s+(n&&n.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=n.source,s=n.id,o=n.path,r=vt[s]&&o in vt[s].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||r?a=new Ct(i,e):(vt[s]||(vt[s]=new Ct(i,e)),a=vt[s]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(kt,{Manager:Ct,Socket:yt,io:kt,connect:kt});const St={mode:"widget",position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class qt{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[],isSubmitting:!1,promptQueue:[],outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1}}getState(){return{...this.state}}setState(t){this.state={...this.state,...t},this.notify()}subscribe(t){return this.listeners.add(t),t(this.getState()),()=>this.listeners.delete(t)}notify(){const t=this.getState();this.listeners.forEach(e=>e(t))}setConnected(t,e,n){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:t,projectName:e,agentOnline:n})}setConnectionError(t){this.setState({isConnected:!1,isConnecting:!1,connectionError:t})}setOpen(t){this.setState({isOpen:t})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(t){this.setState({activeTab:t})}setCurrentPrompt(t){this.setState({currentPrompt:t}),t&&!this.state.promptHistory.find(e=>e.id===t.id)&&this.setState({promptHistory:[t,...this.state.promptHistory].slice(0,50)})}updatePrompt(t,e){this.state.currentPrompt?.id===t&&this.setState({currentPrompt:{...this.state.currentPrompt,...e}}),this.setState({promptHistory:this.state.promptHistory.map(n=>n.id===t?{...n,...e}:n)})}addOutputLine(t){const e={...t,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,e]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(t){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[t]:[...this.state.outputLines]}})}addToQueue(t){this.setState({promptQueue:[...this.state.promptQueue,t]})}getNextFromQueue(){if(0===this.state.promptQueue.length)return null;const[t,...e]=this.state.promptQueue;return this.setState({promptQueue:e}),t}clearQueue(){this.setState({promptQueue:[]})}getQueueLength(){return this.state.promptQueue.length}setSelectedElement(t){this.setState({selectedElement:t,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(t){this.setState({overlayMode:t}),"off"===t&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(t){this.setState({highlightedPromptId:t})}setElementMarkers(t){this.setState({elementMarkers:t})}setCommentsForPrompt(t,e){this.setState({comments:{...this.state.comments,[t]:e}})}addComment(t,e){const n=this.state.comments[t]||[];this.setState({comments:{...this.state.comments,[t]:[...n,e]}}),this.setState({promptHistory:this.state.promptHistory.map(e=>e.id===t?{...e,comment_count:(e.comment_count||0)+1}:e)})}setExpandedPromptId(t){this.setState({expandedPromptId:t})}setLoadingComments(t){this.setState({isLoadingComments:t})}addConsoleLogs(t){this.setState({consoleLogs:[...this.state.consoleLogs,...t].slice(-100)})}addNetworkLogs(t){this.setState({networkLogs:[...this.state.networkLogs,...t].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}toggleIncludeHistory(){this.setState({includeHistory:!this.state.includeHistory})}toggleIncludeContext(){this.setState({includeContext:!this.state.includeContext})}setAuth(t,e){this.setState({user:t,isAuthenticated:e,isAuthenticating:!1,authError:null})}setAuthenticating(t){this.setState({isAuthenticating:t})}setAuthError(t){this.setState({authError:t,isAuthenticating:!1})}setRequireAuth(t){this.setState({requireAuth:t})}reset(){this.state=this.getInitialState(),this.notify()}}class Et{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const t=t=>(...e)=>{const n=this.createEntry(t,e);this.addEntry(n),this.originalConsole?.[t](...e)};console.log=t("log"),console.info=t("info"),console.warn=t("warn"),console.error=t("error"),this.errorHandler=t=>{const e=this.createEntry("error",[t.message],t.error?.stack);this.addEntry(e)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason),n=t.reason instanceof Error?t.reason.stack:void 0,i=this.createEntry("error",[`Unhandled Promise Rejection: ${e}`],n);this.addEntry(i)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}formatArg(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(null===t)return"null";if(void 0===t)return"undefined";if("object"==typeof t)try{const e=JSON.stringify(t,null,2);if("{}"===e||"[]"===e){const e=Object.prototype.toString.call(t);if("[object Object]"!==e&&"[object Array]"!==e)return e}return e}catch{return Object.prototype.toString.call(t)}return String(t)}createEntry(t,e,n){const i=e.map(t=>this.formatArg(t)).join(" ");return{timestamp:Date.now(),level:t,message:i||"(empty)",args:e,stack:n}}addEntry(t){this.buffer.push(t),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(e=>e(t))}getAll(){return[...this.buffer]}getRecent(t=20){return this.buffer.slice(-t)}getErrors(){return this.buffer.filter(t=>"error"===t.level||"warn"===t.level)}clear(){this.buffer=[]}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}formatForPrompt(t){const e=t||this.getRecent(20);return 0===e.length?"":e.map(t=>`${`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}]`} ${t.message}${t.stack?`\n${t.stack}`:""}`).join("\n")}}class _t{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(t,e)=>{const n="string"==typeof t?t:t instanceof URL?t.href:t.url,i=e?.method||"GET",s=Date.now(),o={timestamp:s,method:i,url:n,requestBody:e?.body};try{const n=await this.originalFetch(t,e);if(o.status=n.status,o.duration=Date.now()-s,!n.ok)try{const t=n.clone();o.responseBody=await t.text()}catch{}return this.addEntry(o),n}catch(t){throw o.duration=Date.now()-s,o.error=t instanceof Error?t.message:String(t),this.addEntry(o),t}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const t=this,e=new WeakMap;XMLHttpRequest.prototype.open=function(n,i,...s){return e.set(this,{method:n,url:"string"==typeof i?i:i.href,startTime:0}),t.originalXHROpen.apply(this,[n,i,...s])},XMLHttpRequest.prototype.send=function(n){const i=e.get(this);return i&&(i.startTime=Date.now(),this.addEventListener("loadend",()=>{const e={timestamp:i.startTime,method:i.method,url:i.url,status:this.status,duration:Date.now()-i.startTime};if(this.status>=400||0===this.status){e.error=this.statusText||"Request failed";try{e.responseBody=this.responseText}catch{}}t.addEntry(e)})),t.originalXHRSend.call(this,n)}}addEntry(t){this.buffer.push(t),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(e=>e(t))}getAll(){return[...this.buffer]}getRecent(t=20){return this.buffer.slice(-t)}getErrors(){return this.buffer.filter(t=>t.status&&t.status>=400||t.error)}clear(){this.buffer=[]}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}formatForPrompt(t){const e=t||this.getErrors();return 0===e.length?"":e.map(t=>{const e=new Date(t.timestamp).toISOString(),n=t.status?`[${t.status}]`:"[FAILED]";return`[${e}] ${t.method} ${t.url} ${n}${t.error?` - ${t.error}`:""}`}).join("\n")}}class Rt{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=t=>{if(!this.isActive||!this.highlight)return;const e=document.elementFromPoint(t.clientX,t.clientY);if(!e||e.id?.startsWith("orquesta-"))return;this.selectedElement=e;const n=e.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${n.top}px`,this.highlight.style.left=`${n.left}px`,this.highlight.style.width=`${n.width}px`,this.highlight.style.height=`${n.height}px`;const i=this.highlight.querySelector("#orquesta-element-label");if(i){const t=e.tagName.toLowerCase(),n=e.id?`#${e.id}`:"",s=e.className&&"string"==typeof e.className?`.${e.className.split(" ").slice(0,2).join(".")}`:"";i.textContent=`<${t}${n}${s}>`}},this.handleClick=t=>{if(!this.isActive)return;const e=t.target;if(!e.id?.startsWith("orquesta-")&&(t.preventDefault(),t.stopPropagation(),this.selectedElement)){const t=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(t)}},this.handleKeyDown=t=>{"Escape"===t.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(t){return this.globalRightClickCallback=t,this.globalRightClickHandler=t=>{const e=t.target;if(e.closest('[id^="orquesta-"]'))return;if(this.isActive)return;t.preventDefault(),t.stopPropagation();const n=this.getElementContext(e);this.globalRightClickCallback?.(n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(t){return this.globalRightClickWithPositionCallback=t,this.globalRightClickHandler=t=>{const e=t.target;if(e.closest('[id^="orquesta-"]'))return;if(this.isActive)return;t.preventDefault(),t.stopPropagation();const n=this.getElementContext(e),i={x:t.clientX,y:t.clientY};this.globalRightClickWithPositionCallback?.(n,i)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(t){try{const e=this.safeQuerySelector(t);if(!e)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const n=document.createElement("div");n.id="orquesta-selected-element-label",n.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const i=e.tagName.toLowerCase(),s=e.id?`#${e.id}`:"",o=e.className&&"string"==typeof e.className?`.${e.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Selected: <${i}${s}${o}>`,this.selectedHighlight.appendChild(n);const r=()=>{if(!this.selectedHighlight)return;const t=e.getBoundingClientRect();this.selectedHighlight.style.top=t.top-3+"px",this.selectedHighlight.style.left=t.left-3+"px",this.selectedHighlight.style.width=`${t.width+6}px`,this.selectedHighlight.style.height=`${t.height+6}px`};return r(),this.selectedElementScrollHandler=r,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),e}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(t,e){this.isActive||(this.isActive=!0,this.onSelect=t,this.onCancel=e||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const t=document.createElement("div");t.id="orquesta-element-label",t.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(t)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(t){try{const e=this.safeQuerySelector(t);if(!e)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let n=document.getElementById("orquesta-prompt-highlight");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight",n.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(n));let i=n.querySelector("#orquesta-prompt-highlight-label");i||(i=document.createElement("div"),i.id="orquesta-prompt-highlight-label",i.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',n.appendChild(i));const s=e.tagName.toLowerCase(),o=e.id?`#${e.id}`:"",r=e.className&&"string"==typeof e.className?`.${e.className.split(" ").slice(0,2).join(".")}`:"";i.textContent=`Highlighted: <${s}${o}${r}>`;const a=()=>{const t=e.getBoundingClientRect();n.style.display="block",n.style.top=t.top-3+"px",n.style.left=t.left-3+"px",n.style.width=`${t.width+6}px`,n.style.height=`${t.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=e.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&e.scrollIntoView({behavior:"smooth",block:"center"}),e}catch{return null}}removeHighlight(){const t=document.getElementById("orquesta-prompt-highlight");t&&(t.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}safeQuerySelector(t){try{return document.querySelector(t)}catch{return null}}findElement(t,e){try{let n=this.safeQuerySelector(t);if(n)return n;if(e&&(n=document.getElementById(e),n))return n;const i=t.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(i){const[,t,e]=i;if(n=this.safeQuerySelector(`${t}.${e}`),n)return n}return null}catch{return null}}getElementContext(t){const e=t.getBoundingClientRect(),n={};for(const e of t.attributes)e.name.startsWith("data-")||"class"===e.name||"id"===e.name||(n[e.name]=e.value);return{selector:this.generateSelector(t),tag:t.tagName.toLowerCase(),id:t.id||void 0,className:"string"==typeof t.className?t.className:void 0,textContent:t.textContent?.trim().slice(0,200)||void 0,boundingRect:e,attributes:Object.keys(n).length>0?n:void 0}}isValidCssClass(t){return!/[@:/\[\]()!#]/.test(t)&&!!/^[a-zA-Z_-]/.test(t)}generateSelector(t){if(t.id&&this.isValidCssClass(t.id))return`#${t.id}`;const e=[];let n=t;for(;n&&n!==document.body;){let t=n.tagName.toLowerCase();if(n.id&&this.isValidCssClass(n.id)){t=`#${n.id}`,e.unshift(t);break}if(n.className&&"string"==typeof n.className){const e=n.className.trim().split(/\s+/).filter(t=>this.isValidCssClass(t)).slice(0,2);e.length>0&&(t+=`.${e.join(".")}`)}const i=n.parentElement;if(i){const e=Array.from(i.children).filter(t=>t.tagName===n.tagName);if(e.length>1){t+=`:nth-child(${e.indexOf(n)+1})`}}e.unshift(t),n=n.parentElement}return e.join(" > ")}}class Ot{constructor(t,e){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.broadcastChannel=null,this.pollInterval=null,this.token=t,this.apiUrl=e,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(t){this.state={...this.state,...t},this.notify()}subscribe(t){return this.listeners.add(t),t(this.getState()),()=>this.listeners.delete(t)}notify(){const t=this.getState();this.listeners.forEach(e=>e(t))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(t){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(t))}catch{}}loadSession(){try{const t=localStorage.getItem(this.getStorageKey());if(!t)return null;const e=JSON.parse(t);return e.expiresAt&&new Date(e.expiresAt)<new Date?(this.clearSession(),null):e}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const t=this.loadSession();if(!t)return!1;try{const e=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:t.sessionToken})});if(!e.ok)return this.clearSession(),!1;const n=await e.json();return n.valid?(this.setState({isAuthenticated:!0,user:n.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null}),!0}}login(){return new Promise((t,e)=>{this.setState({isAuthenticating:!0,authError:null});const n=Math.random().toString(36).slice(2),i=`eas_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,s=new URL(`${this.apiUrl}/embed/auth`);s.searchParams.set("token",this.token),s.searchParams.set("origin",window.location.origin),s.searchParams.set("state",n),s.searchParams.set("authSession",i);const o=window.screenX+(window.innerWidth-500)/2,r=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(s.toString(),"orquesta_auth",`width=500,height=600,left=${o},top=${r},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void e(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=n=>{if(n.origin!==new URL(this.apiUrl).origin)return;const{type:i,payload:s}=n.data||{};"orquesta_auth_success"===i?(this.handleAuthSuccess(s),t(s),this.cleanup()):"orquesta_auth_error"===i?(this.handleAuthError(s),e(new Error(s.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===i&&(this.setState({isAuthenticating:!1}),e(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=this.apiUrl.replace("://orquesta.live","://ws.orquesta.live").replace("://localhost:3113","://localhost:3200");this.pollInterval=setInterval(async()=>{try{const n=await fetch(`${a}/auth/result/${i}`);if(!n.ok)return;const s=await n.json();if(s.pending)return;const{type:o,payload:r}=s;"orquesta_auth_success"===o?(this.handleAuthSuccess(r),t(r),this.cleanup()):"orquesta_auth_error"===o&&(this.handleAuthError(r),e(new Error(r.message||"Authentication failed")),this.cleanup())}catch{}},1500);const l=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(l),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),e(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(t){const e={user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt};this.saveSession(e),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null})}handleAuthError(t){this.setState({isAuthenticating:!1,authError:t.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const t=this.loadSession();if(t?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:t.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const Tt=!1,At="prompts",Nt="dark";const Bt=new class{constructor(){this.projectId=null}setProjectId(t){this.projectId=t}getKey(t){const e=`orquesta_embed_${t}`;return this.projectId?`${e}_${this.projectId}`:e}get(t){try{const e=localStorage.getItem(this.getKey(t));return e?JSON.parse(e):null}catch{return null}}set(t,e){try{localStorage.setItem(this.getKey(t),JSON.stringify(e))}catch{}}remove(t){try{localStorage.removeItem(this.getKey(t))}catch{}}getState(){return{isOpen:this.get("isOpen")??Tt,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??At,theme:this.get("theme")??Nt}}setState(t){Object.entries(t).forEach(([t,e])=>{void 0!==e&&this.set(t,e)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(t=>this.remove(t))}};class zt{constructor(t){this.socket=null,this.channelName=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...St,...t},this.state=new qt,this.consoleCapture=new Et,this.networkCapture=new _t,this.elementSelector=new Rt,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new Ot(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(t=>{this.state.setState({isAuthenticated:t.isAuthenticated,isAuthenticating:t.isAuthenticating,user:t.user,authError:t.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const t=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!t.ok){const e=await t.json();throw new Error(e.error||"Failed to validate token")}const e=await t.json();if(!e.valid)throw new Error("Invalid embed token");this.projectId=e.projectId,Bt.setProjectId(e.projectId);const n=e.requireAuth||this.config.requireAuth;n&&!this.authManager?(this.state.setRequireAuth(!0),this.authManager=new Ot(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(t=>{this.state.setState({isAuthenticated:t.isAuthenticated,isAuthenticating:t.isAuthenticating,user:t.user,authError:t.authError})}),await this.authManager.checkSession()):n&&this.state.setRequireAuth(!0),this.channelName=e.channelName;const i=kt("https://ws.orquesta.live",{auth:{embedToken:this.config.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,timeout:1e4});this.socket=i,i.on("output",t=>this.handleOutput(t)),i.on("complete",t=>this.handleComplete(t)),i.on("error",t=>this.handleError(t));let s=!1;i.on("connect",()=>{if(i.emit("subscribe",{channel:e.channelName}),this.state.setConnected(e.projectId,e.project?.name||"Project",e.project?.agent_online||!1),s)return;s=!0,this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(t=>{this.state.addConsoleLogs([t])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(t=>{this.state.addNetworkLogs([t])})),this.setupHotkey(),this.loadTimeline();const t=Bt.getState();this.state.setState({isOpen:this.config.defaultOpen??t.isOpen,activeTab:t.activeTab||"prompts"}),this.config.onReady?.()}),i.on("connect_error",t=>{const e=t?.message||"Failed to connect to WS server";this.state.setConnectionError(e)}),i.on("disconnect",()=>{this.state.setState({isConnecting:!1})})}catch(t){const e=t instanceof Error?t.message:"Connection failed";throw this.state.setConnectionError(e),this.config.onError?.(t instanceof Error?t:new Error(e)),t}}disconnect(){if(this.socket){if(this.channelName)try{this.socket.emit("unsubscribe",{channel:this.channelName})}catch{}this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null}this.channelName=null,this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const t=this.config.hotkey.toLowerCase().split("+"),e=t.pop(),n=new Set(t);this.hotkeyHandler=t=>{if(!t.key)return;const i=n.has("ctrl")===(t.ctrlKey||t.metaKey),s=n.has("shift")===t.shiftKey,o=n.has("alt")===t.altKey,r=t.key.toLowerCase()===e;i&&s&&o&&r&&(t.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(t){if(!this.state.getState().currentPrompt)return;let e,n,i,s="stdout",o=t.data;"stderr"===t.type?s="stderr":t.data.includes("Tool:")||t.data.includes("tool_call")?s="tool":(t.data.includes("thinking")||t.data.includes("Thinking"))&&(s="thinking");try{const r=JSON.parse(t.data);if(r.type){switch(r.type){case"thinking":s="thinking",o=r.thinking?.content||t.data;break;case"tool_call":s="tool_call",n=r.tool_call?.name,o=`Using ${n||"tool"}`;break;case"tool_result":s="tool_result",n=r.tool_result?.name,i=r.tool_result?.success,o=i?r.tool_result?.output||"Success":r.tool_result?.error||"Failed";break;case"output":s="output",o=r.output?.content||t.data;break;case"error":s="error",o=r.error?.message||t.data;break;case"system":s="system",o=r.system?.message||r.system?.event||t.data;break;case"progress":s="progress";const e=void 0!==r.progress?.percentage?` (${r.progress.percentage}%)`:"";o=(r.progress?.message||"Processing")+e;break;default:o=r.content||r.message||t.data}e=r}}catch{}this.state.addOutputLine({timestamp:t.timestamp||Date.now(),type:s,content:o,details:e,toolName:n,toolSuccess:i})}handleComplete(t){const e=this.state.getState(),n=0===t.exitCode?"completed":"failed",i=e.currentPrompt?.id;if(e.currentPrompt&&(this.state.storePromptOutput(e.currentPrompt.id),this.state.updatePrompt(e.currentPrompt.id,{status:n,completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),i&&this.config.onPromptComplete&&this.config.onPromptComplete(i,n),this.config.reloadOnComplete&&"completed"===n){const t=this.config.reloadDelay??1500;return console.log(`[Orquesta Embed] Prompt completed. Reloading page in ${t}ms...`),void setTimeout(()=>{window.location.reload()},t)}this.processQueue()}async processQueue(){const t=this.state.getNextFromQueue();if(t){console.log(`[Orquesta Embed] Processing queued prompt. Remaining in queue: ${this.state.getQueueLength()}`);try{await this.submitPrompt(t.content,t.options)}catch(t){console.error("[Orquesta Embed] Failed to process queued prompt:",t),this.processQueue()}}}handleError(t){const e=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${t.error}`}),e.currentPrompt&&(this.state.storePromptOutput(e.currentPrompt.id),this.state.updatePrompt(e.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),this.processQueue()}async submitPrompt(t,e){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const n=this.state.getState();if(n.isSubmitting)return this.state.addToQueue({id:`queue-${Date.now()}`,content:t,options:e,queuedAt:Date.now()}),console.log(`[Orquesta Embed] Prompt queued. Queue length: ${this.state.getQueueLength()}`),`queued-${Date.now()}`;this.state.setState({isSubmitting:!0}),this.state.clearOutput();let i=t;const s=e?.elementContext||n.selectedElement;if(s&&(i+=`\n\n--- Element Context ---\nSelector: ${s.selector}\nTag: <${s.tag}>\n${s.id?`ID: ${s.id}`:""}\n${s.className?`Classes: ${s.className}`:""}\n${s.textContent?`Text: ${s.textContent}`:""}\n${s.attributes?`Attributes: ${JSON.stringify(s.attributes)}`:""}`),e?.includeConsole??n.includeConsole){const t=this.consoleCapture.formatForPrompt();t&&(i+=`\n\n--- Console Logs ---\n${t}`)}if(e?.includeNetwork??n.includeNetwork){const t=this.networkCapture.formatForPrompt();t&&(i+=`\n\n--- Network Errors ---\n${t}`)}if(e?.includeHistory??n.includeHistory){const t=n.promptHistory.filter(t=>"completed"===t.status).slice(0,5).reverse();t.length>0&&(i+="\n\n--- Previous Prompts Context ---",t.forEach((t,e)=>{i+=`\n\n[Prompt ${e+1}]: ${t.content}`;const s=n.promptOutputs[t.id];if(s&&s.length>0){const t=s.slice(-10).map(t=>t.content).join("\n");i+=`\n[Output ${e+1}]:\n${t}`}}))}try{const t={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},e=this.authManager?.getSessionToken();e&&(t["X-Session-Token"]=e);const n=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:t,body:JSON.stringify({projectId:this.projectId,content:i,elementContext:s})});if(!n.ok){const t=await n.json();throw new Error(t.error||"Failed to submit prompt")}const o=(await n.json()).prompt;return this.state.setCurrentPrompt(o),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(o.id),o.id}catch(t){throw this.state.setState({isSubmitting:!1}),t}}async loadTimeline(){if(this.projectId)try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const e=await t.json();this.state.setState({promptHistory:e.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),Bt.set("isOpen",!0)}close(){this.state.setOpen(!1),Bt.set("isOpen",!1)}toggle(){const t=!this.state.getState().isOpen;this.state.setOpen(t),Bt.set("isOpen",t)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(t=>this.state.setSelectedElement(t),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(t){return this.state.subscribe(t)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}setActiveTab(t){this.state.setActiveTab(t)}async loadComments(t){if(this.projectId){this.state.setLoadingComments(!0);try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts/${t}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const n=await e.json();this.state.setCommentsForPrompt(t,n.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(t,e){if(this.projectId)try{const n=await fetch(`${this.config.apiUrl}/api/embed/prompts/${t}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:e})});if(n.ok){const e=await n.json();e.comment&&this.state.addComment(t,e.comment)}}catch(t){throw console.error("Failed to add comment:",t),t}}setOverlayMode(t){if(this.state.setOverlayMode(t),"off"===t)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===t){const t=this.state.getState().promptHistory.filter(t=>t.element_context?.selector).map(t=>({promptId:t.id,selector:t.element_context.selector,rect:null,content:t.content,author:t.author||null,gitCommitSha:t.git_commit_sha||null,commentCount:t.comment_count||0}));this.state.setElementMarkers(t)}else this.state.setElementMarkers([])}highlightPromptElement(t){if(!t.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(t.element_context.selector)?(this.state.setHighlightedPromptId(t.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",t.id)}setupGlobalRightClick(t){return this.elementSelector.setupGlobalRightClick(t)}setupGlobalRightClickWithPosition(t){return this.elementSelector.setupGlobalRightClickWithPosition(t)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const t=await this.authManager.login();return this.config.onLogin?.(t.user),t.user}catch(t){throw t}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}function Lt(t,e,n){const i=document.createElement(t);return e&&Object.entries(e).forEach(([t,e])=>{void 0!==e&&!1!==e&&("className"===t?i.className=e:t.startsWith("on")&&"string"==typeof e||(!0===e?i.setAttribute(t,""):i.setAttribute(t,e)))}),n&&n.forEach(t=>{"string"==typeof t?i.appendChild(document.createTextNode(t)):i.appendChild(t)}),i}function Mt(t,e,n,i){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n,i)}function Ht(t,e){Object.assign(t.style,e)}function Pt(t){t?.parentNode?.removeChild(t)}class It{constructor(t){this.state=null,this.elements={container:document.createElement("div"),panel:null,trigger:null,promptInput:null,logStream:null,statusBar:null,statusBarMinimized:null,contextMenu:null,elementMarkers:null},this.unsubscribe=null,this.cleanupFunctions=[],this.isMinimized=!1,this.showStatusBar=!0,this.statusBarMinimized=!1,this.lastCompletedPrompt=null,this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,this.builderTerminalCollapsed=!1,this.builderMessages=[],this.builderLastOutputCount=0,this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.globalRightClickCleanup=null,this.config=t,this.currentMode=t.mode||"widget",this.client=new zt(t),function(t,e){const n=document.getElementById(e);if(n)return n;const i=document.createElement("style");i.id=e,i.textContent=t,document.head.appendChild(i)}("\n/* Orquesta Embed SDK Styles - Auto-injected */\n/* These styles are scoped to orquesta-* classes to avoid conflicts */\n\n/* Reset for Orquesta elements */\n[class^=\"orquesta-\"],\n[class*=\" orquesta-\"] {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Base colors */\n.orquesta-embed-panel {\n --orq-bg: #18181b;\n --orq-bg-secondary: #27272a;\n --orq-border: #3f3f46;\n --orq-text: #fafafa;\n --orq-text-muted: #a1a1aa;\n --orq-primary: #3b82f6;\n --orq-success: #22c55e;\n --orq-warning: #eab308;\n --orq-error: #ef4444;\n}\n\n/* Scrollbar styling */\n.orquesta-embed-panel ::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb {\n background: #3f3f46;\n border-radius: 3px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb:hover {\n background: #52525b;\n}\n\n/* Animations */\n@keyframes orquesta-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n@keyframes orquesta-pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.5;\n }\n}\n\n.orquesta-embed-panel .animate-spin {\n animation: orquesta-spin 1s linear infinite;\n}\n\n.orquesta-embed-panel .animate-pulse {\n animation: orquesta-pulse 2s ease-in-out infinite;\n}\n\n/* Utility classes */\n.orquesta-embed-panel .line-clamp-1 {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n.orquesta-embed-panel .line-clamp-2 {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n/* Focus visible */\n.orquesta-embed-panel button:focus-visible,\n.orquesta-embed-panel input:focus-visible,\n.orquesta-embed-panel textarea:focus-visible {\n outline: 2px solid var(--orq-primary);\n outline-offset: 2px;\n}\n\n/* Element selector highlight animation */\n#orquesta-element-highlight {\n animation: orquesta-highlight-pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes orquesta-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);\n }\n}\n\n/* Tooltip */\n.orquesta-tooltip {\n position: absolute;\n z-index: 2147483647;\n padding: 4px 8px;\n background: #18181b;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n font-size: 12px;\n color: #fafafa;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* Transitions */\n.orquesta-embed-panel * {\n transition-property: color, background-color, border-color, opacity, transform;\n transition-duration: 150ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n/* Panel entrance animation */\n.orquesta-embed-panel {\n animation: orquesta-panel-enter 0.2s ease-out;\n}\n\n@keyframes orquesta-panel-enter {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n}\n\n/* Trigger button */\n.orquesta-embed-trigger {\n animation: orquesta-trigger-enter 0.3s ease-out;\n}\n\n@keyframes orquesta-trigger-enter {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* Log stream */\n.orquesta-log-stream {\n background: #0a0a0a;\n border: 1px solid #27272a;\n border-radius: 6px;\n padding: 8px;\n}\n\n/* Timeline item hover */\n.orquesta-timeline button:hover {\n transform: translateX(2px);\n}\n\n/* ============================================ */\n/* Tailwind class overrides - CRITICAL STYLES */\n/* These ensure styles work even when purged */\n/* ============================================ */\n\n/* Explicit background colors */\n.orquesta-embed-panel {\n background-color: #18181b !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel .bg-zinc-950 { background-color: #09090b !important; }\n.orquesta-embed-panel .bg-zinc-900 { background-color: #18181b !important; }\n.orquesta-embed-panel .bg-zinc-800 { background-color: #27272a !important; }\n.orquesta-embed-panel .bg-zinc-700 { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .bg-zinc-600 { background-color: #52525b !important; }\n\n/* Text colors */\n.orquesta-embed-panel .text-white { color: #fafafa !important; }\n.orquesta-embed-panel .text-zinc-100 { color: #f4f4f5 !important; }\n.orquesta-embed-panel .text-zinc-200 { color: #e4e4e7 !important; }\n.orquesta-embed-panel .text-zinc-300 { color: #d4d4d8 !important; }\n.orquesta-embed-panel .text-zinc-400 { color: #a1a1aa !important; }\n.orquesta-embed-panel .text-zinc-500 { color: #71717a !important; }\n.orquesta-embed-panel .text-red-400 { color: #f87171 !important; }\n.orquesta-embed-panel .text-red-300 { color: #fca5a5 !important; }\n.orquesta-embed-panel .text-green-400 { color: #4ade80 !important; }\n.orquesta-embed-panel .text-green-500 { color: #22c55e !important; }\n.orquesta-embed-panel .text-blue-400 { color: #60a5fa !important; }\n.orquesta-embed-panel .text-blue-500 { color: #3b82f6 !important; }\n.orquesta-embed-panel .text-yellow-400 { color: #facc15 !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .text-orange-400 { color: #fb923c !important; }\n.orquesta-embed-panel .text-gray-800 { color: #1f2937 !important; }\n\n/* Border colors */\n.orquesta-embed-panel .border-zinc-700 { border-color: #3f3f46 !important; }\n.orquesta-embed-panel .border-zinc-800 { border-color: #27272a !important; }\n.orquesta-embed-panel .border-red-800 { border-color: #991b1b !important; }\n\n/* Background colors for buttons and UI */\n.orquesta-embed-panel .bg-blue-500 { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .bg-blue-600 { background-color: #2563eb !important; }\n.orquesta-embed-panel .bg-green-400 { background-color: #4ade80 !important; }\n.orquesta-embed-panel .bg-green-500 { background-color: #22c55e !important; }\n.orquesta-embed-panel .bg-green-600 { background-color: #16a34a !important; }\n.orquesta-embed-panel .bg-red-500 { background-color: #ef4444 !important; }\n.orquesta-embed-panel .bg-red-600 { background-color: #dc2626 !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-red-900\\/30 { background-color: rgba(127, 29, 29, 0.3) !important; }\n.orquesta-embed-panel .bg-white { background-color: #ffffff !important; }\n\n/* Hover states */\n.orquesta-embed-panel .hover\\:bg-zinc-700:hover { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .hover\\:bg-zinc-800:hover { background-color: #27272a !important; }\n.orquesta-embed-panel .hover\\:bg-blue-500:hover { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .hover\\:bg-blue-700:hover { background-color: #1d4ed8 !important; }\n.orquesta-embed-panel .hover\\:bg-gray-100:hover { background-color: #f3f4f6 !important; }\n.orquesta-embed-panel .hover\\:text-white:hover { color: #fafafa !important; }\n.orquesta-embed-panel .hover\\:text-zinc-300:hover { color: #d4d4d8 !important; }\n\n/* Form inputs */\n.orquesta-embed-panel input,\n.orquesta-embed-panel textarea {\n background-color: #27272a !important;\n border-color: #3f3f46 !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel input::placeholder,\n.orquesta-embed-panel textarea::placeholder {\n color: #71717a !important;\n}\n\n/* Buttons base */\n.orquesta-embed-panel button {\n background-color: transparent;\n}\n\n.orquesta-embed-panel button:hover {\n background-color: #3f3f46;\n}\n\n/* Rounded borders */\n.orquesta-embed-panel .rounded { border-radius: 0.25rem !important; }\n.orquesta-embed-panel .rounded-md { border-radius: 0.375rem !important; }\n.orquesta-embed-panel .rounded-lg { border-radius: 0.5rem !important; }\n.orquesta-embed-panel .rounded-xl { border-radius: 0.75rem !important; }\n.orquesta-embed-panel .rounded-full { border-radius: 9999px !important; }\n\n/* Border widths */\n.orquesta-embed-panel .border { border-width: 1px !important; }\n.orquesta-embed-panel .border-b { border-bottom-width: 1px !important; }\n.orquesta-embed-panel .border-t { border-top-width: 1px !important; }\n\n/* Padding */\n.orquesta-embed-panel .p-1 { padding: 0.25rem !important; }\n.orquesta-embed-panel .p-2 { padding: 0.5rem !important; }\n.orquesta-embed-panel .p-3 { padding: 0.75rem !important; }\n.orquesta-embed-panel .p-4 { padding: 1rem !important; }\n.orquesta-embed-panel .px-2 { padding-left: 0.5rem !important; padding-right: 0.5rem !important; }\n.orquesta-embed-panel .px-3 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }\n.orquesta-embed-panel .px-4 { padding-left: 1rem !important; padding-right: 1rem !important; }\n.orquesta-embed-panel .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }\n.orquesta-embed-panel .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .py-3 { padding-top: 0.75rem !important; padding-bottom: 0.75rem !important; }\n\n/* Margin */\n.orquesta-embed-panel .m-1 { margin: 0.25rem !important; }\n.orquesta-embed-panel .m-2 { margin: 0.5rem !important; }\n.orquesta-embed-panel .mb-1 { margin-bottom: 0.25rem !important; }\n.orquesta-embed-panel .mb-2 { margin-bottom: 0.5rem !important; }\n.orquesta-embed-panel .mb-4 { margin-bottom: 1rem !important; }\n.orquesta-embed-panel .mt-1 { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .mt-2 { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .mt-3 { margin-top: 0.75rem !important; }\n.orquesta-embed-panel .mt-4 { margin-top: 1rem !important; }\n.orquesta-embed-panel .mr-1 { margin-right: 0.25rem !important; }\n.orquesta-embed-panel .mr-2 { margin-right: 0.5rem !important; }\n.orquesta-embed-panel .mx-1 { margin-left: 0.25rem !important; margin-right: 0.25rem !important; }\n\n/* Gap */\n.orquesta-embed-panel .gap-0\\.5 { gap: 0.125rem !important; }\n.orquesta-embed-panel .gap-1 { gap: 0.25rem !important; }\n.orquesta-embed-panel .gap-1\\.5 { gap: 0.375rem !important; }\n.orquesta-embed-panel .gap-2 { gap: 0.5rem !important; }\n.orquesta-embed-panel .gap-3 { gap: 0.75rem !important; }\n.orquesta-embed-panel .gap-4 { gap: 1rem !important; }\n\n/* Flex */\n.orquesta-embed-panel .flex { display: flex !important; }\n.orquesta-embed-panel .flex-col { flex-direction: column !important; }\n.orquesta-embed-panel .flex-1 { flex: 1 1 0% !important; }\n.orquesta-embed-panel .flex-shrink-0 { flex-shrink: 0 !important; }\n.orquesta-embed-panel .items-center { align-items: center !important; }\n.orquesta-embed-panel .items-start { align-items: flex-start !important; }\n.orquesta-embed-panel .justify-center { justify-content: center !important; }\n.orquesta-embed-panel .justify-between { justify-content: space-between !important; }\n\n/* Width/Height */\n.orquesta-embed-panel .w-full { width: 100% !important; }\n.orquesta-embed-panel .w-2 { width: 0.5rem !important; }\n.orquesta-embed-panel .w-3 { width: 0.75rem !important; }\n.orquesta-embed-panel .w-3\\.5 { width: 0.875rem !important; }\n.orquesta-embed-panel .w-4 { width: 1rem !important; }\n.orquesta-embed-panel .w-5 { width: 1.25rem !important; }\n.orquesta-embed-panel .w-6 { width: 1.5rem !important; }\n.orquesta-embed-panel .w-8 { width: 2rem !important; }\n.orquesta-embed-panel .w-16 { width: 4rem !important; }\n.orquesta-embed-panel .h-2 { height: 0.5rem !important; }\n.orquesta-embed-panel .h-3 { height: 0.75rem !important; }\n.orquesta-embed-panel .h-3\\.5 { height: 0.875rem !important; }\n.orquesta-embed-panel .h-4 { height: 1rem !important; }\n.orquesta-embed-panel .h-5 { height: 1.25rem !important; }\n.orquesta-embed-panel .h-6 { height: 1.5rem !important; }\n.orquesta-embed-panel .h-8 { height: 2rem !important; }\n.orquesta-embed-panel .h-16 { height: 4rem !important; }\n.orquesta-embed-panel .h-full { height: 100% !important; }\n.orquesta-embed-panel .max-w-20 { max-width: 5rem !important; }\n\n/* Font */\n.orquesta-embed-panel .text-xs { font-size: 0.75rem !important; line-height: 1rem !important; }\n.orquesta-embed-panel .text-sm { font-size: 0.875rem !important; line-height: 1.25rem !important; }\n.orquesta-embed-panel .text-lg { font-size: 1.125rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-xl { font-size: 1.25rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-2xl { font-size: 1.5rem !important; line-height: 2rem !important; }\n.orquesta-embed-panel .text-4xl { font-size: 2.25rem !important; line-height: 2.5rem !important; }\n.orquesta-embed-panel .font-medium { font-weight: 500 !important; }\n.orquesta-embed-panel .font-semibold { font-weight: 600 !important; }\n.orquesta-embed-panel .font-bold { font-weight: 700 !important; }\n.orquesta-embed-panel .text-center { text-align: center !important; }\n.orquesta-embed-panel .truncate { overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; }\n\n/* Opacity */\n.orquesta-embed-panel .opacity-25 { opacity: 0.25 !important; }\n.orquesta-embed-panel .opacity-50 { opacity: 0.5 !important; }\n.orquesta-embed-panel .opacity-75 { opacity: 0.75 !important; }\n\n/* Overflow */\n.orquesta-embed-panel .overflow-hidden { overflow: hidden !important; }\n.orquesta-embed-panel .overflow-y-auto { overflow-y: auto !important; }\n\n/* Shadow */\n.orquesta-embed-panel .shadow-xl { box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important; }\n.orquesta-embed-panel .shadow-2xl { box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important; }\n.orquesta-embed-panel .shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important; }\n\n/* Position */\n.orquesta-embed-panel .fixed { position: fixed !important; }\n.orquesta-embed-panel .absolute { position: absolute !important; }\n.orquesta-embed-panel .relative { position: relative !important; }\n.orquesta-embed-panel .top-1 { top: 0.25rem !important; }\n.orquesta-embed-panel .right-1 { right: 0.25rem !important; }\n.orquesta-embed-panel .bottom-0 { bottom: 0 !important; }\n.orquesta-embed-panel .right-0 { right: 0 !important; }\n\n/* Z-index */\n.orquesta-embed-panel .z-\\[2147483647\\] { z-index: 2147483647 !important; }\n\n/* Cursor */\n.orquesta-embed-panel .cursor-move { cursor: move !important; }\n.orquesta-embed-panel .cursor-se-resize { cursor: se-resize !important; }\n.orquesta-embed-panel .cursor-not-allowed { cursor: not-allowed !important; }\n\n/* Select */\n.orquesta-embed-panel .select-none { user-select: none !important; }\n\n/* Disabled states */\n.orquesta-embed-panel .disabled\\:opacity-50:disabled { opacity: 0.5 !important; }\n.orquesta-embed-panel .disabled\\:cursor-not-allowed:disabled { cursor: not-allowed !important; }\n.orquesta-embed-panel .disabled\\:bg-blue-800:disabled { background-color: #1e40af !important; }\n.orquesta-embed-panel .disabled\\:bg-gray-300:disabled { background-color: #d1d5db !important; }\n\n/* Transition */\n.orquesta-embed-panel .transition-colors { transition-property: color, background-color, border-color !important; transition-duration: 150ms !important; }\n.orquesta-embed-panel .transition-all { transition-property: all !important; transition-duration: 150ms !important; }\n\n/* ============================================ */\n/* Action buttons & Comments - Timeline styles */\n/* ============================================ */\n\n/* Purple colors for \"Show on page\" button */\n.orquesta-embed-panel .text-purple-300 { color: #d8b4fe !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-purple-600\\/20 { background-color: rgba(147, 51, 234, 0.2) !important; }\n.orquesta-embed-panel .bg-purple-600\\/30 { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .border-purple-500\\/40 { border-color: rgba(168, 85, 247, 0.4) !important; }\n.orquesta-embed-panel .border-purple-500\\/60 { border-color: rgba(168, 85, 247, 0.6) !important; }\n.orquesta-embed-panel .hover\\:bg-purple-600\\/30:hover { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .hover\\:border-purple-500\\/60:hover { border-color: rgba(168, 85, 247, 0.6) !important; }\n\n/* Zinc with opacity for \"View output\" button */\n.orquesta-embed-panel .bg-zinc-700\\/50 { background-color: rgba(63, 63, 70, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600\\/50 { border-color: rgba(82, 82, 91, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600 { border-color: #52525b !important; }\n.orquesta-embed-panel .border-zinc-500 { border-color: #71717a !important; }\n.orquesta-embed-panel .hover\\:border-zinc-500:hover { border-color: #71717a !important; }\n\n/* Blue with opacity */\n.orquesta-embed-panel .bg-blue-500\\/20 { background-color: rgba(59, 130, 246, 0.2) !important; }\n.orquesta-embed-panel .border-blue-500\\/30 { border-color: rgba(59, 130, 246, 0.3) !important; }\n.orquesta-embed-panel .text-blue-300 { color: #93c5fd !important; }\n.orquesta-embed-panel .text-blue-300\\/70 { color: rgba(147, 197, 253, 0.7) !important; }\n\n/* Additional padding */\n.orquesta-embed-panel .py-1\\.5 { padding-top: 0.375rem !important; padding-bottom: 0.375rem !important; }\n.orquesta-embed-panel .py-0\\.5 { padding-top: 0.125rem !important; padding-bottom: 0.125rem !important; }\n.orquesta-embed-panel .px-1\\.5 { padding-left: 0.375rem !important; padding-right: 0.375rem !important; }\n.orquesta-embed-panel .px-2\\.5 { padding-left: 0.625rem !important; padding-right: 0.625rem !important; }\n.orquesta-embed-panel .pb-2 { padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .pb-3 { padding-bottom: 0.75rem !important; }\n.orquesta-embed-panel .pt-1 { padding-top: 0.25rem !important; }\n\n/* Space utilities */\n.orquesta-embed-panel .space-y-0\\.5 > * + * { margin-top: 0.125rem !important; }\n.orquesta-embed-panel .space-y-1 > * + * { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .space-y-2 > * + * { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .space-y-3 > * + * { margin-top: 0.75rem !important; }\n\n/* Focus states */\n.orquesta-embed-panel .focus\\:outline-none:focus { outline: none !important; }\n.orquesta-embed-panel .focus\\:ring-1:focus { box-shadow: 0 0 0 1px var(--orq-primary, #3b82f6) !important; }\n.orquesta-embed-panel .focus\\:ring-blue-500:focus { --tw-ring-color: #3b82f6 !important; }\n\n/* Placeholder colors */\n.orquesta-embed-panel .placeholder\\:text-zinc-500::placeholder { color: #71717a !important; }\n\n/* Text utilities */\n.orquesta-embed-panel .break-words { word-wrap: break-word !important; overflow-wrap: break-word !important; }\n.orquesta-embed-panel .italic { font-style: italic !important; }\n\n/* Negative margins */\n.orquesta-embed-panel .-mt-1 { margin-top: -0.25rem !important; }\n\n/* Max height */\n.orquesta-embed-panel .max-h-\\[400px\\] { max-height: 400px !important; }\n.orquesta-embed-panel .max-h-\\[150px\\] { max-height: 150px !important; }\n\n/* Font mono */\n.orquesta-embed-panel .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }\n\n/* Text sizes */\n.orquesta-embed-panel .text-\\[10px\\] { font-size: 10px !important; line-height: 1.4 !important; }\n.orquesta-embed-panel .text-\\[11px\\] { font-size: 11px !important; line-height: 1.4 !important; }\n\n/* Flex wrap */\n.orquesta-embed-panel .flex-wrap { flex-wrap: wrap !important; }\n\n/* Min width */\n.orquesta-embed-panel .min-w-0 { min-width: 0 !important; }\n\n/* ml-auto for comment button alignment */\n.orquesta-embed-panel .ml-auto { margin-left: auto !important; }\n\n/* Hidden utility */\n.orquesta-embed-panel .hidden { display: none !important; }\n\n/* SVG icon sizing */\n.orquesta-embed-panel svg { flex-shrink: 0; }\n\n/* Mobile responsive */\n@media (max-width: 480px) {\n .orquesta-embed-panel {\n position: fixed !important;\n left: 8px !important;\n right: 8px !important;\n bottom: 8px !important;\n top: auto !important;\n width: auto !important;\n max-height: 70vh !important;\n }\n}\n\n/* Builder Mode */\n.orquesta-builder{display:flex;flex-direction:column;width:100%;height:100vh;background:#0a0a0a;color:#fafafa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;overflow:hidden}\n.orquesta-builder-header{display:flex;align-items:center;justify-content:space-between;height:48px;padding:0 16px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-header-left{display:flex;align-items:center;gap:12px}\n.orquesta-builder-header-right{display:flex;align-items:center;gap:8px}\n.orquesta-builder-logo{font-weight:700;font-size:14px;color:#fafafa;letter-spacing:-0.02em}\n.orquesta-builder-project{font-size:13px;color:#a1a1aa}\n.orquesta-builder-status{display:flex;align-items:center;gap:6px;font-size:12px;color:#a1a1aa}\n.orquesta-builder-status-dot{width:8px;height:8px;border-radius:50%}\n.orquesta-builder-main{display:flex;flex:1;min-height:0}\n.orquesta-builder-chat{display:flex;flex-direction:column;width:380px;min-width:300px;max-width:50%;border-right:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}\n.orquesta-builder-chat-input{padding:12px 16px;border-top:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-input textarea{width:100%;min-height:60px;max-height:200px;padding:10px 12px;background:#27272a;border:1px solid #3f3f46;border-radius:8px;color:#fafafa;font-size:13px;resize:vertical;outline:none;font-family:inherit}\n.orquesta-builder-chat-input textarea:focus{border-color:#3b82f6}\n.orquesta-builder-chat-input-actions{display:flex;justify-content:space-between;align-items:center;margin-top:8px}\n.orquesta-builder-preview{flex:1;display:flex;flex-direction:column;min-width:0}\n.orquesta-builder-preview-bar{display:flex;align-items:center;height:36px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;gap:8px;flex-shrink:0}\n.orquesta-builder-preview-url{flex:1;padding:4px 10px;background:#27272a;border:1px solid #3f3f46;border-radius:6px;color:#a1a1aa;font-size:12px;font-family:'SF Mono','Fira Code',monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.orquesta-builder-preview-iframe{flex:1;width:100%;border:none;background:#fff}\n.orquesta-builder-terminal{height:200px;min-height:100px;max-height:50vh;border-top:1px solid #27272a;background:#0a0a0a;display:flex;flex-direction:column;flex-shrink:0}\n.orquesta-builder-terminal-header{display:flex;align-items:center;justify-content:space-between;height:32px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-terminal-title{font-size:12px;font-weight:600;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.05em}\n.orquesta-builder-terminal-output{flex:1;overflow-y:auto;padding:8px 12px;font-family:'SF Mono','Fira Code','Cascadia Code',monospace;font-size:12px;line-height:1.5}\n.orquesta-builder-terminal.collapsed{height:32px;min-height:32px}\n.orquesta-builder-terminal.collapsed .orquesta-builder-terminal-output{display:none}\n.orquesta-builder-msg{max-width:90%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}\n.orquesta-builder-msg-user{align-self:flex-end;background:#3b82f6;color:#fff;border-bottom-right-radius:4px}\n.orquesta-builder-msg-system{align-self:flex-start;background:#27272a;color:#fafafa;border-bottom-left-radius:4px}\n.orquesta-builder-msg-status{align-self:center;background:transparent;color:#71717a;font-size:12px;padding:4px 0}\n.orquesta-builder-resizer-h{width:4px;cursor:col-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-h:hover{background:#3b82f6}\n.orquesta-builder-resizer-v{height:4px;cursor:row-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-v:hover{background:#3b82f6}\n.orquesta-builder button{background:transparent;border:none;color:#a1a1aa;cursor:pointer;padding:4px 8px;border-radius:4px;font-size:12px}\n.orquesta-builder button:hover{background:#27272a;color:#fafafa}\n.orquesta-builder-btn-primary{background:#3b82f6!important;color:#fff!important;font-weight:500;padding:6px 16px!important;border-radius:6px!important}\n.orquesta-builder-btn-primary:hover{background:#2563eb!important}\n.orquesta-builder-btn-primary:disabled{opacity:0.5;cursor:not-allowed}\n@media(max-width:768px){.orquesta-builder-main{flex-direction:column}.orquesta-builder-chat{width:100%;max-width:100%;height:50%;border-right:none;border-bottom:1px solid #27272a}.orquesta-builder-resizer-h{display:none}}\n","orquesta-embed-styles"),this.elements.container.id="orquesta-widget-container",document.body.appendChild(this.elements.container),!1!==t.enableGlobalRightClick&&this.setupGlobalRightClick()}setupGlobalRightClick(){this.globalRightClickCleanup=this.client.setupGlobalRightClickWithPosition((t,e)=>{this.client.getElementSelector().deactivate(),this.client.getElementSelector().highlightSelectedElement(t.selector),this.contextMenuState={isOpen:!0,position:e,element:t},this.render()})}async init(){console.log("[Orquesta Embed] v0.1.38"),this.unsubscribe=this.client.subscribe(t=>{this.state=t,this.render()});try{await this.client.connect()}catch(t){throw this.renderError(t instanceof Error?t.message:"Connection failed"),t}}render(){this.state&&("builder"!==this.currentMode?(this.elements.container.innerHTML="",this.cleanupFunctions.forEach(t=>t()),this.cleanupFunctions=[],"completed"!==this.state.currentPrompt?.status&&"failed"!==this.state.currentPrompt?.status||(this.lastCompletedPrompt=this.state.currentPrompt),this.showStatusBar&&this.renderStatusBar(),this.state.isOpen&&!this.isMinimized||this.renderTrigger(),this.state.isOpen&&!this.isMinimized&&this.renderPanel(),this.state.isSelectingElement&&this.renderElementInspector(),this.contextMenuState.isOpen&&this.renderContextMenu(),"all"===this.state.overlayMode&&this.state.elementMarkers.length>0&&this.renderElementMarkers()):this.renderBuilder())}renderTrigger(){const t=this.config.position||"bottom-right",[e,n]=t.split("-"),i=Lt("button",{className:"orquesta-embed-trigger"},["⬡"]);if(Ht(i,{position:"fixed",zIndex:"2147483647",padding:"12px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"50%",boxShadow:"0 10px 25px rgba(0,0,0,0.3)",cursor:"pointer",fontSize:"20px",["top"===e?"top":"bottom"]:"20px",["left"===n?"left":"right"]:"20px"}),this.state?.agentOnline){const t=Lt("span");Ht(t,{position:"absolute",top:"4px",right:"4px",width:"8px",height:"8px",background:"#22c55e",borderRadius:"50%"}),i.appendChild(t)}const s=Mt(i,"click",()=>{this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(s),this.elements.container.appendChild(i),this.elements.trigger=i}renderPanel(){if(!this.state)return;const t=Lt("div",{className:"orquesta-embed-panel"});Ht(t,{position:"fixed",zIndex:"2147483647",width:"400px",height:"500px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 25px 50px rgba(0,0,0,0.5)",display:"flex",flexDirection:"column",overflow:"hidden",right:"20px",bottom:"20px"});const e=this.createHeader();t.appendChild(e);const n=this.createTabs();if(t.appendChild(n),this.state?.connectionError){const e=Lt("div");Ht(e,{margin:"8px 12px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid rgba(239, 68, 68, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const n=Lt("span",{},["⚠️"]);Ht(n,{fontSize:"12px"});const i=Lt("span",{},[this.state.connectionError]);Ht(i,{fontSize:"11px",color:"#fca5a5"}),e.appendChild(n),e.appendChild(i),t.appendChild(e)}if(!this.state?.isConnected&&!this.state?.connectionError){const e=Lt("div");Ht(e,{margin:"8px 12px",padding:"8px 12px",background:"rgba(113, 63, 18, 0.3)",border:"1px solid rgba(234, 179, 8, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const n=Lt("span",{},["ℹ️"]);Ht(n,{fontSize:"12px"});const i=Lt("span",{},["Reconnecting to Orquesta..."]);Ht(i,{fontSize:"11px",color:"#fcd34d"}),e.appendChild(n),e.appendChild(i),t.appendChild(e)}const i=Lt("div");if(Ht(i,{flex:"1",overflowY:"auto",padding:"12px"}),this.state?.requireAuth&&!this.state?.isAuthenticated){const t=this.createAuthOverlay();i.appendChild(t)}else{const t=this.createContent();i.appendChild(t)}t.appendChild(i),this.elements.container.appendChild(t),this.elements.panel=t}createAuthOverlay(){const t=Lt("div");Ht(t,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",textAlign:"center",padding:"16px"});const e=Lt("div");Ht(e,{width:"64px",height:"64px",borderRadius:"50%",background:"#27272a",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:"16px"});const n=Lt("span",{},["🔒"]);Ht(n,{fontSize:"28px"}),e.appendChild(n),t.appendChild(e);const i=Lt("h3",{},["Sign in to continue"]);Ht(i,{color:"white",fontWeight:"600",margin:"0 0 8px 0",fontSize:"16px"}),t.appendChild(i);const s=Lt("p",{},["You need to sign in to submit prompts to this project."]);if(Ht(s,{color:"#a1a1aa",fontSize:"13px",margin:"0 0 16px 0"}),t.appendChild(s),this.state?.authError){const e=Lt("div",{},[this.state.authError]);Ht(e,{marginBottom:"16px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid #7f1d1d",borderRadius:"6px",color:"#fca5a5",fontSize:"12px"}),t.appendChild(e)}const o=Lt("button");if(Ht(o,{display:"flex",alignItems:"center",gap:"8px",padding:"10px 20px",background:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"500",fontSize:"14px",color:"#374151"}),this.state?.isAuthenticating){const t=Lt("span",{},["⏳"]),e=Lt("span",{},["Signing in..."]);o.appendChild(t),o.appendChild(e),o.style.opacity="0.7"}else{const t=Lt("span",{},["G"]);Ht(t,{fontWeight:"bold",color:"#4285f4"});const e=Lt("span",{},["Continue with Google"]);o.appendChild(t),o.appendChild(e)}const r=Mt(o,"click",()=>{this.state?.isAuthenticating||this.client.login()});this.cleanupFunctions.push(r),t.appendChild(o);const a=Lt("p",{},["You must be a member of this project's organization."]);return Ht(a,{color:"#71717a",fontSize:"11px",marginTop:"16px"}),t.appendChild(a),t}createHeader(){const t=Lt("div");Ht(t,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",background:"#27272a",borderBottom:"1px solid #3f3f46",cursor:"move"});const e=Lt("div");Ht(e,{display:"flex",alignItems:"center",gap:"8px"});const n=Lt("span",{},["⬡"]);Ht(n,{fontSize:"16px"});const i=Lt("span",{},["Orquesta"]);if(Ht(i,{fontWeight:"600",color:"white",fontSize:"14px"}),e.appendChild(n),e.appendChild(i),this.state?.projectName){const t=Lt("span",{},[`• ${this.state.projectName}`]);Ht(t,{fontSize:"12px",color:"#a1a1aa"}),e.appendChild(t)}const s=Lt("div");if(Ht(s,{display:"flex",alignItems:"center",gap:"4px"}),this.state?.requireAuth)if(this.state.isAuthenticated&&this.state.user){const t=Lt("div");if(Ht(t,{display:"flex",alignItems:"center",gap:"6px",marginRight:"8px"}),this.state.user.avatar_url){const e=Lt("img",{src:this.state.user.avatar_url});Ht(e,{width:"20px",height:"20px",borderRadius:"50%"}),t.appendChild(e)}else{const e=Lt("div",{},[this.state.user.full_name?.[0]?.toUpperCase()||"?"]);Ht(e,{width:"20px",height:"20px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",color:"white"}),t.appendChild(e)}const e=Lt("span",{},[this.state.user.full_name||"User"]);Ht(e,{fontSize:"12px",color:"#d4d4d8",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),t.appendChild(e);const n=Lt("button",{},["↪"]);Ht(n,{padding:"4px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"12px"});const i=Mt(n,"click",()=>this.client.logout());this.cleanupFunctions.push(i),t.appendChild(n),s.appendChild(t)}else{const t=Lt("button",{},[this.state?.isAuthenticating?"...":"Sign in"]);Ht(t,{padding:"4px 8px",marginRight:"8px",background:"#2563eb",border:"none",borderRadius:"4px",color:"white",cursor:"pointer",fontSize:"11px"});const e=Mt(t,"click",()=>this.client.login());this.cleanupFunctions.push(e),s.appendChild(t)}const o=Lt("span");Ht(o,{width:"8px",height:"8px",borderRadius:"50%",marginRight:"4px",background:this.state?.isConnected?this.state?.agentOnline?"#22c55e":"#71717a":"#ef4444"}),o.title=this.state?.isConnected?this.state?.agentOnline?"Agent online":"Agent offline":"Not connected",s.appendChild(o);const r=Lt("button",{},["🎯"]);Ht(r,{padding:"4px",background:this.state?.rightClickEnabled?"#16a34a":"#3f3f46",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px"}),r.title=this.state?.rightClickEnabled?"Right-click enabled":"Right-click disabled";const a=Mt(r,"click",()=>{if(this.state){const t=!this.state.rightClickEnabled;this.state.rightClickEnabled=t,t?this.globalRightClickCleanup||this.setupGlobalRightClick():this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.render()}});this.cleanupFunctions.push(a),s.appendChild(r);const l=Lt("div");Ht(l,{display:"flex",gap:"2px",margin:"0 4px",padding:"2px",background:"#27272a",borderRadius:"4px"});[{mode:"off",icon:"👁️🗨️",title:"Overlay off"},{mode:"single",icon:"👁️",title:"Show selected prompt"},{mode:"all",icon:"📍",title:"Show all prompts"}].forEach(({mode:t,icon:e,title:n})=>{const i=Lt("button",{},[e]),s=this.state?.overlayMode===t;Ht(i,{padding:"4px",background:s?"off"===t?"#3f3f46":"single"===t?"#2563eb":"#7c3aed":"transparent",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"10px",opacity:s?"1":"0.5"}),i.title=n;const o=Mt(i,"click",()=>{this.state&&(this.state.overlayMode=t,"all"===t?this.state.elementMarkers=this.state.promptHistory.filter(t=>t.element_context?.selector).map(t=>{let e=null;try{e=document.querySelector(t.element_context.selector)}catch{}return{promptId:t.id,selector:t.element_context.selector,rect:e?.getBoundingClientRect()||null,content:t.content,author:t.author||null,gitCommitSha:t.git_commit_sha||null,commentCount:t.comment_count||0}}):"off"===t&&(this.state.elementMarkers=[],this.state.highlightedPromptId=null,this.client.getElementSelector().removeHighlight()),this.render())});this.cleanupFunctions.push(o),l.appendChild(i)}),s.appendChild(l);const c=this.createIconButton("⛶",()=>{this.switchMode("builder")});c.title="Expand to builder mode",s.appendChild(c);const p=this.createIconButton("−",()=>{this.isMinimized=!0,this.render()});s.appendChild(p);const d=this.createIconButton("×",()=>{this.client.close()});return s.appendChild(d),t.appendChild(e),t.appendChild(s),t}createIconButton(t,e){const n=Lt("button",{},[t]);Ht(n,{padding:"4px 8px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",borderRadius:"4px",fontSize:"16px"});const i=Mt(n,"click",e);this.cleanupFunctions.push(i);const s=Mt(n,"mouseenter",()=>{Ht(n,{background:"#3f3f46",color:"white"})}),o=Mt(n,"mouseleave",()=>{Ht(n,{background:"transparent",color:"#a1a1aa"})});return this.cleanupFunctions.push(s,o),n}createTabs(){const t=Lt("div");Ht(t,{padding:"8px 12px",borderBottom:"1px solid #27272a"});const e=Lt("div");Ht(e,{display:"flex",gap:"4px",padding:"4px",background:"#27272a",borderRadius:"8px"});return["prompts","timeline","logs"].forEach(t=>{const n=this.state?.activeTab===t,i=Lt("button",{},[t.charAt(0).toUpperCase()+t.slice(1)]);Ht(i,{flex:"1",padding:"6px 12px",background:n?"#3f3f46":"transparent",border:"none",borderRadius:"6px",color:n?"white":"#a1a1aa",cursor:"pointer",fontSize:"13px",fontWeight:"500"});const s=Mt(i,"click",()=>{this.state&&(this.state.activeTab=t,this.render())});this.cleanupFunctions.push(s),e.appendChild(i)}),t.appendChild(e),t}createContent(){const t=Lt("div");switch(this.state?.activeTab){case"prompts":t.appendChild(this.createPromptsTab());break;case"timeline":t.appendChild(this.createTimelineTab());break;case"logs":t.appendChild(this.createLogsTab())}return t}createPromptsTab(){const t=Lt("div"),e=async()=>{const t=this.elements.promptInput?.value.trim();if(t&&this.state?.agentOnline&&!this.state?.isSubmitting)try{const e=this.state?.selectedElement?{elementContext:this.state.selectedElement}:void 0;await this.client.submitPrompt(t,e),this.elements.promptInput&&(this.elements.promptInput.value=""),this.state&&(this.state.selectedElement=null,this.render())}catch(t){console.error("Failed to submit prompt:",t)}},n=Lt("textarea",{placeholder:this.state?.agentOnline?"What would you like to do?":"Agent is offline..."});Ht(n,{width:"100%",minHeight:"80px",padding:"8px 12px",background:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"white",fontSize:"14px",resize:"none",outline:"none"}),n.disabled=!this.state?.agentOnline||this.state?.isSubmitting,this.elements.promptInput=n,t.appendChild(n);const i=Mt(n,"keydown",t=>{const n=t;"Enter"===n.key&&(n.metaKey||n.ctrlKey)&&(n.preventDefault(),e())});this.cleanupFunctions.push(i);const s=Lt("div");if(Ht(s,{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"}),this.state?.selectedElement){const t=this.createContextBadge("🎯",`<${this.state.selectedElement.tag}>${this.state.selectedElement.textContent?": "+this.state.selectedElement.textContent.slice(0,20)+(this.state.selectedElement.textContent.length>20?"...":""):""}`,"#1e3a5f","#3b82f6","#93c5fd",()=>{this.state&&(this.state.selectedElement=null,this.render())});s.appendChild(t)}if(this.state?.includeConsole){const t=this.createContextBadge("📋","Console logs","#422006","#eab308","#fcd34d",()=>{this.state&&(this.state.includeConsole=!1,this.render())});s.appendChild(t)}if(this.state?.includeNetwork){const t=this.createContextBadge("🌐","Network errors","#450a0a","#ef4444","#fca5a5",()=>{this.state&&(this.state.includeNetwork=!1,this.render())});s.appendChild(t)}if(this.state?.includeContext){const t=this.createContextBadge("🔗","Session outputs","#3b0764","#a855f7","#d8b4fe",()=>{this.state&&(this.state.includeContext=!1,this.render())});s.appendChild(t)}s.childNodes.length>0&&t.appendChild(s);const o=Lt("div");Ht(o,{display:"flex",gap:"8px",marginTop:"8px"});const r=this.createContextButton(this.state?.selectedElement?"🎯 Element ✓":"🎯 Element",()=>{this.client.startElementSelection()},!!this.state?.selectedElement),a=this.createContextButton("📋 Logs",()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())},this.state?.includeConsole),l=this.createContextButton("🌐 Network",()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())},this.state?.includeNetwork),c=this.createContextButton("🔗 Context",()=>{this.state&&(this.state.includeContext=!this.state.includeContext,this.render())},this.state?.includeContext);o.appendChild(r),o.appendChild(a),o.appendChild(l),o.appendChild(c),t.appendChild(o);const p=Lt("div");Ht(p,{display:"flex",justifyContent:"flex-end",marginTop:"12px"});const d=Lt("button",{},[this.state?.isSubmitting?"Running...":"Submit (⌘↵)"]);Ht(d,{padding:"8px 16px",background:"#3b82f6",border:"none",borderRadius:"6px",color:"white",cursor:"pointer",fontWeight:"500",opacity:!this.state?.agentOnline||this.state?.isSubmitting?"0.5":"1"});const h=Mt(d,"click",e);if(this.cleanupFunctions.push(h),p.appendChild(d),t.appendChild(p),this.state?.outputLines.length||this.state?.isSubmitting){const e=Lt("div");Ht(e,{marginTop:"16px",paddingTop:"16px",borderTop:"1px solid #27272a"});const n=this.createLogStream(this.state?.outputLines||[]);e.appendChild(n),t.appendChild(e)}return t}createContextButton(t,e,n){const i=Lt("button",{},[t]);Ht(i,{padding:"4px 8px",background:n?"#3f3f46":"transparent",border:"none",borderRadius:"4px",color:n?"white":"#a1a1aa",cursor:"pointer",fontSize:"12px"});const s=Mt(i,"click",e);return this.cleanupFunctions.push(s),i}createContextBadge(t,e,n,i,s,o){const r=Lt("div");Ht(r,{display:"flex",alignItems:"center",gap:"6px",padding:"4px 8px",background:n,border:`1px solid ${i}`,borderRadius:"6px",fontSize:"11px",color:s});const a=Lt("span",{},[t]),l=Lt("span",{},[e]),c=Lt("button",{},["×"]);Ht(c,{marginLeft:"4px",background:"none",border:"none",color:s,cursor:"pointer",fontSize:"14px",padding:"0",lineHeight:"1"});const p=Mt(c,"click",o);return this.cleanupFunctions.push(p),r.appendChild(a),r.appendChild(l),r.appendChild(c),r}createLogStream(t){const e=Lt("div",{className:"orquesta-log-stream"});if(Ht(e,{maxHeight:"200px",overflowY:"auto",background:"#0a0a0a",border:"1px solid #27272a",borderRadius:"6px",padding:"8px",fontFamily:"monospace",fontSize:"11px"}),this.state?.isSubmitting){const t=Lt("div");Ht(t,{color:"#3b82f6",padding:"4px 0",marginBottom:"4px"}),t.textContent="● Running...",e.appendChild(t)}return[...t].reverse().forEach(t=>{const n=Lt("div");Ht(n,{display:"flex",gap:"8px",padding:"2px 0",color:"stderr"===t.type?"#ef4444":"tool"===t.type?"#3b82f6":"#d4d4d8"});const i=Lt("span",{},["stderr"===t.type?"✕":"tool"===t.type?"🔧":"›"]);Ht(i,{opacity:"0.5",width:"16px",textAlign:"center"});const s=Lt("span",{},[t.content]);Ht(s,{flex:"1",wordBreak:"break-all",whiteSpace:"pre-wrap"}),n.appendChild(i),n.appendChild(s),e.appendChild(n)}),this.elements.logStream=e,e}createTimelineTab(){const t=Lt("div");if(Ht(t,{maxHeight:"400px",overflowY:"auto"}),!this.state?.promptHistory.length){const e=Lt("div",{},["No prompts yet. Right-click any element to start!"]);return Ht(e,{textAlign:"center",padding:"32px",color:"#71717a",fontSize:"14px"}),t.appendChild(e),t}return this.state.promptHistory.forEach(e=>{const n=e.id===this.state?.currentPrompt?.id,i=e.id===this.state?.expandedPromptId,s=Lt("div");Ht(s,{marginBottom:"8px",background:n?"#27272a":"#18181b",border:"1px solid "+(n?"#3b82f6":"#3f3f46"),borderRadius:"8px",transition:"border-color 0.2s"});const o=Lt("div");Ht(o,{display:"flex",alignItems:"flex-start",gap:"10px",padding:"12px",cursor:"pointer"});const r=Lt("div"),a=e.author?.full_name||"Unknown",l=a[0]?.toUpperCase()||"?";if(e.author?.avatar_url){const t=Lt("img",{src:e.author.avatar_url});Ht(t,{width:"28px",height:"28px",borderRadius:"50%"}),r.appendChild(t)}else Ht(r,{width:"28px",height:"28px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:"600",color:"white"}),r.textContent=l;const c=Lt("div");Ht(c,{flex:"1",minWidth:"0"});const p=Lt("div");Ht(p,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"});const d=Lt("span",{},[a]);Ht(d,{fontSize:"12px",fontWeight:"500",color:"#d4d4d8"});const h=Lt("span",{},[this.formatDate(e.created_at)]);Ht(h,{fontSize:"10px",color:"#71717a"}),p.appendChild(d),p.appendChild(h);const u=Lt("p",{},[e.content.slice(0,100)+(e.content.length>100?"...":"")]);Ht(u,{color:"#e4e4e7",fontSize:"13px",margin:"0 0 8px 0",lineHeight:"1.4"});const m=Lt("div");if(Ht(m,{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"}),e.git_commit_sha){const t=Lt("span",{},[`🔗 ${e.git_commit_sha.slice(0,7)}`]);Ht(t,{padding:"2px 6px",background:"#1e3a5f",border:"1px solid #3b82f6",borderRadius:"4px",fontSize:"10px",color:"#93c5fd",fontFamily:"monospace"}),m.appendChild(t)}if(e.element_context){const t=Lt("span",{},[`🎯 <${e.element_context.tag}>`]);Ht(t,{padding:"2px 6px",background:"rgba(59, 130, 246, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",borderRadius:"4px",fontSize:"10px",color:"#60a5fa"}),m.appendChild(t)}if((e.comment_count||0)>0){const t=Lt("span",{},[`💬 ${e.comment_count}`]);Ht(t,{padding:"2px 6px",background:"#27272a",borderRadius:"4px",fontSize:"10px",color:"#a1a1aa"}),m.appendChild(t)}c.appendChild(p),c.appendChild(u),c.appendChild(m);const g=Lt("div");Ht(g,{display:"flex",alignItems:"center",gap:"6px",flexShrink:"0"});const f=Lt("span");Ht(f,{width:"8px",height:"8px",borderRadius:"50%",background:"completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"running"===e.status?"#3b82f6":"#71717a"});const b=Lt("span",{},[e.status]);Ht(b,{padding:"2px 8px",background:"completed"===e.status?"#14532d":"failed"===e.status?"#7f1d1d":"running"===e.status?"#1e3a5f":"#27272a",color:"completed"===e.status?"#4ade80":"failed"===e.status?"#f87171":"running"===e.status?"#60a5fa":"#a1a1aa",borderRadius:"9999px",fontSize:"10px",fontWeight:"500"}),g.appendChild(f),g.appendChild(b),o.appendChild(r),o.appendChild(c),o.appendChild(g),s.appendChild(o);const x="completed"===e.status||"failed"===e.status||e.element_context,y=Lt("div");if(Ht(y,{display:x?"flex":"none",alignItems:"center",gap:"8px",padding:"0 12px 10px 50px"}),e.element_context){const t=Lt("button",{},["👁 Show on page"]);Ht(t,{padding:"4px 10px",background:"rgba(124, 58, 237, 0.2)",border:"1px solid rgba(124, 58, 237, 0.4)",borderRadius:"6px",color:"#c4b5fd",fontSize:"11px",cursor:"pointer"});const n=Mt(t,"click",t=>{if(t.stopPropagation(),e.element_context){this.client.getElementSelector().highlightSelectedElement(e.element_context.selector);try{const t=document.querySelector(e.element_context.selector);t?.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}});this.cleanupFunctions.push(n),y.appendChild(t)}if("completed"===e.status||"failed"===e.status){const t=Lt("button",{},[i?"📄 Hide output":"📄 View output"]);Ht(t,{padding:"4px 10px",background:i?"#3f3f46":"rgba(63, 63, 70, 0.5)",border:"1px solid rgba(63, 63, 70, 0.5)",borderRadius:"6px",color:i?"white":"#d4d4d8",fontSize:"11px",cursor:"pointer"});const n=Mt(t,"click",t=>{t.stopPropagation(),this.state&&(this.state.expandedPromptId=i?null:e.id,this.render())});this.cleanupFunctions.push(n),y.appendChild(t)}if(s.appendChild(y),i){const t=Lt("div");Ht(t,{padding:"0 12px 12px 12px",borderTop:"1px solid #27272a",marginTop:"4px"});const n=Lt("div");Ht(n,{marginTop:"8px",background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"});const i=this.state?.promptOutputs?.[e.id]||[];if(i.length>0)i.slice(-20).forEach(t=>{const e=Lt("div",{},[t.content]);Ht(e,{color:"stderr"===t.type?"#ef4444":"tool"===t.type?"#3b82f6":"thinking"===t.type?"#71717a":"#d4d4d8",padding:"1px 0",fontStyle:"thinking"===t.type?"italic":"normal"}),n.appendChild(e)});else{const t=Lt("div",{},["No output recorded for this prompt"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),n.appendChild(t)}t.appendChild(n),s.appendChild(t)}const w=Mt(s,"mouseenter",()=>{n||Ht(s,{borderColor:"#52525b"})}),C=Mt(s,"mouseleave",()=>{n||Ht(s,{borderColor:"#3f3f46"})});this.cleanupFunctions.push(w,C);const v=Mt(o,"click",()=>{this.state&&e.element_context&&this.client.getElementSelector().highlightSelectedElement(e.element_context.selector)});this.cleanupFunctions.push(v),t.appendChild(s)}),t}createLogsTab(){const t=Lt("div"),e=Lt("div");Ht(e,{marginBottom:"16px"});const n=Lt("div");Ht(n,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const i=Lt("h3",{},["Agent Output"]);if(Ht(i,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"}),this.state?.isSubmitting){const t=Lt("span",{},["Running..."]);Ht(t,{fontSize:"11px",color:"#4ade80"}),n.appendChild(i),n.appendChild(t)}else n.appendChild(i);e.appendChild(n);const s=Lt("div");if(Ht(s,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.outputLines.length)this.state.outputLines.slice(-30).forEach(t=>{const e=Lt("div",{},[t.content]);Ht(e,{color:"stderr"===t.type?"#ef4444":"tool"===t.type?"#3b82f6":"#d4d4d8",padding:"1px 0",wordBreak:"break-all"}),s.appendChild(e)});else{const t=Lt("div",{},["No agent output yet"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),s.appendChild(t)}e.appendChild(s),t.appendChild(e);const o=Lt("div");Ht(o,{marginBottom:"16px"});const r=Lt("div");Ht(r,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const a=Lt("h3",{},["Console Logs"]);Ht(a,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const l=Lt("span",{},[`${this.state?.consoleLogs.length||0} entries`]);Ht(l,{fontSize:"11px",color:"#71717a"}),r.appendChild(a),r.appendChild(l),o.appendChild(r);const c=Lt("div");if(Ht(c,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.consoleLogs.length)this.state.consoleLogs.slice(-20).forEach(t=>{const e=Lt("div");Ht(e,{color:"error"===t.level?"#ef4444":"warn"===t.level?"#eab308":"#d4d4d8",padding:"1px 0"}),e.textContent=`[${t.level}] ${t.message}`,c.appendChild(e)});else{const t=Lt("div",{},["No console logs captured"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),c.appendChild(t)}o.appendChild(c),t.appendChild(o);const p=Lt("div"),d=Lt("div");Ht(d,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const h=Lt("h3",{},["Network Requests"]);Ht(h,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const u=Lt("span",{},[`${this.state?.networkLogs.length||0} requests`]);Ht(u,{fontSize:"11px",color:"#71717a"}),d.appendChild(h),d.appendChild(u),p.appendChild(d);const m=Lt("div");if(Ht(m,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.networkLogs.length)this.state.networkLogs.slice(-15).forEach(t=>{const e=Lt("div");Ht(e,{display:"flex",gap:"8px",padding:"2px 0"});const n=Lt("span",{},[String(t.status||"...")]);Ht(n,{color:t.status&&t.status>=400?"#ef4444":t.status&&t.status>=300?"#eab308":"#4ade80"});const i=Lt("span",{},[t.method]);Ht(i,{color:"#a1a1aa"});const s=Lt("span",{},[t.url]);if(Ht(s,{color:"#d4d4d8",flex:"1",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),e.appendChild(n),e.appendChild(i),e.appendChild(s),t.duration){const n=Lt("span",{},[`${t.duration}ms`]);Ht(n,{color:"#71717a"}),e.appendChild(n)}m.appendChild(e)});else{const t=Lt("div",{},["No network requests captured"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),m.appendChild(t)}return p.appendChild(m),t.appendChild(p),t}renderElementInspector(){const t=Lt("div",{className:"orquesta-element-inspector"});Ht(t,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"});const e=Lt("div");Ht(e,{position:"absolute",top:"16px",left:"50%",transform:"translateX(-50%)",pointerEvents:"auto",display:"flex",alignItems:"center",gap:"12px",padding:"8px 16px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 10px 25px rgba(0,0,0,0.3)"});const n=Lt("span",{},["Click on any element to select it, or right-click for options"]);Ht(n,{fontSize:"13px",color:"#d4d4d8"});const i=Lt("button",{},["Cancel (Esc)"]);Ht(i,{padding:"4px 12px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"13px"});const s=Mt(i,"click",()=>{this.client.getElementSelector().deactivate()});this.cleanupFunctions.push(s),e.appendChild(n),e.appendChild(i),t.appendChild(e),this.elements.container.appendChild(t)}renderStatusBar(){if(!this.state)return;let t="idle";this.state.isConnected?this.state.agentOnline?this.state.isSubmitting||"running"===this.state.currentPrompt?.status?t="running":"completed"===this.state.currentPrompt?.status?t="completed":"failed"===this.state.currentPrompt?.status&&(t="failed"):t="offline":t="connecting";const e=(()=>{switch(t){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${this.state?.currentPrompt?.content.slice(0,50)}${(this.state?.currentPrompt?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(this.state?.currentPrompt?.git_commit_sha?` • Commit ${this.state.currentPrompt.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:this.state?.projectName?`${this.state.projectName} • Ready`:"Orquesta Ready",pulse:!1}}})();if(this.statusBarMinimized){const n=Lt("div",{id:"orquesta-status-bar-minimized"});Ht(n,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:e.bg,border:`1px solid ${e.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const i=Lt("span");Ht(i,{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===t?"#22c55e":"failed"===t?"#ef4444":"running"===t?"#3b82f6":"#71717a"});const s=Lt("span",{},["Orquesta"]);Ht(s,{fontSize:"11px",color:"#d4d4d8",fontWeight:"500"}),n.appendChild(i),n.appendChild(s);const o=Mt(n,"click",()=>{this.statusBarMinimized=!1,this.render()});return this.cleanupFunctions.push(o),this.elements.container.appendChild(n),void(this.elements.statusBarMinimized=n)}const n=Lt("div",{id:"orquesta-status-bar"});Ht(n,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:e.bg,border:`1px solid ${e.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)"});const i=Lt("div");Ht(i,{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:e.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:"0"});const s=Lt("span",{},[e.icon]);Ht(s,{fontSize:"14px",color:"#ffffff"}),i.appendChild(s);const o=Lt("div");Ht(o,{flex:"1",minWidth:"0"});const r=Lt("div",{},[e.text]);if(Ht(r,{fontSize:"12px",fontWeight:"500",color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"}),o.appendChild(r),"running"===t){const t=Lt("div");Ht(t,{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"});const e=Lt("div");Ht(e,{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",width:"30%",animation:"orquesta-progress 2s ease-in-out infinite"}),t.appendChild(e),o.appendChild(t)}const a=Lt("button",{},["−"]);Ht(a,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const l=Mt(a,"click",()=>{this.statusBarMinimized=!0,this.render()});this.cleanupFunctions.push(l);const c=Lt("button",{},["×"]);Ht(c,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const p=Mt(c,"click",()=>{this.showStatusBar=!1,this.render()});this.cleanupFunctions.push(p),n.appendChild(i),n.appendChild(o),n.appendChild(a),n.appendChild(c);const d=Lt("style");d.textContent="\n @keyframes orquesta-progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n ",n.appendChild(d),this.elements.container.appendChild(n),this.elements.statusBar=n,"completed"!==t&&"failed"!==t||setTimeout(()=>{this.showStatusBar&&!this.statusBarMinimized&&(this.statusBarMinimized=!0,this.render())},5e3)}renderContextMenu(){if(!this.contextMenuState.isOpen||!this.contextMenuState.element)return;const t=Lt("div",{className:"orquesta-context-menu"});Ht(t,{position:"fixed",zIndex:"2147483648",left:`${this.contextMenuState.position.x}px`,top:`${this.contextMenuState.position.y}px`,width:"320px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"12px",boxShadow:"0 25px 50px rgba(0, 0, 0, 0.5)",overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const e=Lt("div");Ht(e,{padding:"12px",borderBottom:"1px solid #27272a",backgroundColor:"#27272a"});const n=Lt("div");Ht(n,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"});const i=Lt("span",{},["🎯"]),s=Lt("span",{},["Prompt about element"]);Ht(s,{fontWeight:"600",color:"white",fontSize:"14px"}),n.appendChild(i),n.appendChild(s);const o=Lt("div");Ht(o,{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#3f3f46",borderRadius:"4px",fontSize:"11px",fontFamily:"ui-monospace, monospace",color:"#a1a1aa"});const r=Lt("span",{},[`<${this.contextMenuState.element.tag}>`]);if(Ht(r,{color:"#60a5fa"}),o.appendChild(r),this.contextMenuState.element.className){const t=Lt("span",{},[`.${this.contextMenuState.element.className.split(" ")[0]}`]);Ht(t,{color:"#4ade80"}),o.appendChild(t)}e.appendChild(n),e.appendChild(o);const a=Lt("div");Ht(a,{padding:"12px"});const l=Lt("textarea",{placeholder:"What would you like to do with this element?"});Ht(l,{width:"100%",minHeight:"80px",padding:"10px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"8px",color:"white",fontSize:"14px",resize:"none",outline:"none",marginBottom:"12px"});const c=Lt("div");Ht(c,{display:"flex",gap:"8px",marginBottom:"12px"});const p=(t,e,n)=>{const i=Lt("button",{},[t]);Ht(i,{flex:"1",padding:"6px 10px",backgroundColor:e?"#3f3f46":"transparent",border:"1px solid #3f3f46",borderRadius:"6px",color:e?"white":"#a1a1aa",fontSize:"12px",cursor:"pointer"});const s=Mt(i,"click",n);return this.cleanupFunctions.push(s),i},d=p("📋 Logs "+(this.state?.includeConsole?"✓":""),this.state?.includeConsole||!1,()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())}),h=p("🌐 Network "+(this.state?.includeNetwork?"✓":""),this.state?.includeNetwork||!1,()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())});c.appendChild(d),c.appendChild(h);const u=Lt("div");Ht(u,{display:"flex",gap:"8px"});const m=Lt("button",{},["Open Panel"]);Ht(m,{flex:"1",padding:"8px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"#d4d4d8",fontSize:"13px",fontWeight:"500",cursor:"pointer"});const g=Mt(m,"click",()=>{this.state&&this.contextMenuState.element&&(this.state.selectedElement=this.contextMenuState.element,this.state.isOpen=!0,this.state.activeTab="prompts"),this.closeContextMenu(),this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(g);const f=Lt("button",{},["Submit"]);Ht(f,{flex:"1",padding:"8px 12px",backgroundColor:this.state?.agentOnline?"#3b82f6":"#3f3f46",border:"none",borderRadius:"6px",color:"white",fontSize:"13px",fontWeight:"500",cursor:this.state?.agentOnline?"pointer":"not-allowed",opacity:this.state?.agentOnline?"1":"0.5"});const b=Mt(f,"click",async()=>{const t=l.value.trim();if(t&&this.state?.agentOnline&&this.contextMenuState.element)try{await this.client.submitPrompt(t,{elementContext:this.contextMenuState.element}),this.closeContextMenu(),this.isMinimized=!1,this.client.open()}catch(t){console.error("Failed to submit:",t)}});this.cleanupFunctions.push(b),u.appendChild(m),u.appendChild(f),a.appendChild(l),a.appendChild(c),a.appendChild(u),t.appendChild(e),t.appendChild(a);const x=Mt(document,"click",e=>{t&&!t.contains(e.target)&&this.closeContextMenu()});this.cleanupFunctions.push(x);const y=Mt(document,"keydown",t=>{"Escape"===t.key&&this.closeContextMenu()});this.cleanupFunctions.push(y),this.elements.container.appendChild(t),this.elements.contextMenu=t,setTimeout(()=>l.focus(),50)}closeContextMenu(){this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.client.getElementSelector().removeSelectedHighlight(),this.render()}renderElementMarkers(){if(!this.state||"all"!==this.state.overlayMode)return;const t=Lt("div",{className:"orquesta-element-markers"});Ht(t,{position:"fixed",inset:"0",zIndex:"2147483644",pointerEvents:"none"}),this.state.elementMarkers.forEach(e=>{if(!e.rect)return;const n=Lt("div");Ht(n,{position:"fixed",left:`${e.rect.left}px`,top:`${e.rect.top}px`,width:`${e.rect.width}px`,height:`${e.rect.height}px`,border:"2px solid #7c3aed",borderRadius:"4px",backgroundColor:"rgba(124, 58, 237, 0.1)",pointerEvents:"auto",cursor:"pointer"});const i=Lt("div");Ht(i,{position:"absolute",top:"-8px",right:"-8px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"#7c3aed",color:"white",fontSize:"11px",fontWeight:"600",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'}),i.textContent="1",n.appendChild(i);const s=Mt(n,"click",()=>{this.state&&(this.state.activeTab="timeline",this.state.expandedPromptId=e.promptId,this.client.open()),this.render()});this.cleanupFunctions.push(s);const o=Lt("div");Ht(o,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"8px",padding:"8px 12px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"6px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",maxWidth:"250px",display:"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const r=Lt("div",{},[e.content.slice(0,80)+(e.content.length>80?"...":"")]);if(Ht(r,{fontSize:"12px",color:"#d4d4d8"}),o.appendChild(r),e.author){const t=Lt("div",{},[`by ${e.author.full_name}`]);Ht(t,{fontSize:"11px",color:"#71717a",marginTop:"4px"}),o.appendChild(t)}n.appendChild(o);const a=Mt(n,"mouseenter",()=>{Ht(o,{display:"block"})}),l=Mt(n,"mouseleave",()=>{Ht(o,{display:"none"})});this.cleanupFunctions.push(a,l),t.appendChild(n)}),this.elements.container.appendChild(t),this.elements.elementMarkers=t}renderError(t){const e=Lt("div",{className:"orquesta-embed-error"});Ht(e,{position:"fixed",bottom:"16px",right:"16px",zIndex:"2147483647",padding:"16px",background:"#7f1d1d",border:"1px solid #991b1b",borderRadius:"8px",maxWidth:"300px"});const n=Lt("div",{},["Orquesta Error"]);Ht(n,{fontWeight:"600",color:"white",marginBottom:"4px"});const i=Lt("div",{},[t]);Ht(i,{color:"#fecaca",fontSize:"13px"}),e.appendChild(n),e.appendChild(i),this.elements.container.appendChild(e)}formatDate(t){const e=new Date(t),n=(new Date).getTime()-e.getTime(),i=Math.floor(n/6e4);return i<1?"Just now":i<60?`${i}m ago`:i<1440?`${Math.floor(i/60)}h ago`:`${Math.floor(i/1440)}d ago`}open(){this.isMinimized=!1,this.client.open()}close(){this.client.close()}toggle(){this.client.toggle()}startElementSelection(){this.client.startElementSelection()}async submitPrompt(t,e){return this.client.submitPrompt(t,e)}renderBuilder(){if(!this.state)return;this.builderRoot||this.createBuilderDOM();const t=this.builderRoot?.querySelector(".orquesta-builder-status-dot");t&&(t.style.background=this.state.agentOnline?"#22c55e":"#ef4444");const e=this.builderRoot?.querySelector(".orquesta-builder-status-text");if(e&&(e.textContent=this.state.agentOnline?"Agent online":"Agent offline"),this.state.currentPrompt){const t=this.state.currentPrompt;"running"!==t.status||this.builderMessages.some(e=>e.content===`Running: ${t.content.slice(0,80)}`)||this.builderMessages.push({role:"status",content:`Running: ${t.content.slice(0,80)}${t.content.length>80?"...":""}`}),"completed"!==t.status||this.builderMessages.some(t=>t.content.startsWith("Completed"))||(this.builderMessages.push({role:"status",content:"Completed successfully"}),this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)),"failed"!==t.status||this.builderMessages.some(t=>t.content.startsWith("Failed"))||this.builderMessages.push({role:"status",content:"Failed — check terminal for details"})}this.updateBuilderMessages(),this.updateBuilderTerminal();const n=this.builderRoot?.querySelector(".orquesta-builder-submit");n&&(n.disabled=this.state.isSubmitting||!this.state.agentOnline)}createBuilderDOM(){this.config.container&&("string"==typeof this.config.container?document.querySelector(this.config.container)||document.body:this.config.container);const t=this.config.previewUrl||window.location.href,e=this.state?.projectName||"Project",n=Lt("div",{className:"orquesta-builder orquesta-embed-panel"}),i=Lt("div",{className:"orquesta-builder-header"}),s=Lt("div",{className:"orquesta-builder-header-left"});s.innerHTML=`\n <span class="orquesta-builder-logo">⬡ Orquesta</span>\n <span class="orquesta-builder-project">${this.escapeHtml(e)}</span>\n `;const o=Lt("div",{className:"orquesta-builder-header-right"});o.innerHTML=`\n <div class="orquesta-builder-status">\n <span class="orquesta-builder-status-dot" style="background:${this.state?.agentOnline?"#22c55e":"#ef4444"}"></span>\n <span class="orquesta-builder-status-text">${this.state?.agentOnline?"Agent online":"Agent offline"}</span>\n </div>\n `;const r=Lt("button");r.textContent="⊡",r.title="Collapse to widget mode",Ht(r,{padding:"4px 8px",background:"transparent",border:"1px solid #3f3f46",borderRadius:"4px",color:"#a1a1aa",cursor:"pointer",fontSize:"14px",marginLeft:"8px"}),this.cleanupFunctions.push(Mt(r,"click",()=>{this.switchMode("widget")})),this.cleanupFunctions.push(Mt(r,"mouseenter",()=>{Ht(r,{background:"#3f3f46",color:"white"})})),this.cleanupFunctions.push(Mt(r,"mouseleave",()=>{Ht(r,{background:"transparent",color:"#a1a1aa"})})),o.appendChild(r),i.appendChild(s),i.appendChild(o),n.appendChild(i);const a=Lt("div",{className:"orquesta-builder-main"}),l=Lt("div",{className:"orquesta-builder-chat"}),c=Lt("div",{className:"orquesta-builder-chat-messages"});c.innerHTML='\n <div class="orquesta-builder-msg orquesta-builder-msg-system">\n What would you like to build? Describe the feature or change and I\'ll implement it.\n </div>\n ',this.builderMsgContainer=c,l.appendChild(c);const p=Lt("div",{className:"orquesta-builder-chat-input"}),d=Lt("textarea",{placeholder:"Describe what you want to build..."});d.setAttribute("rows","3");const h=Lt("div",{className:"orquesta-builder-chat-input-actions"}),u=Lt("span");Ht(u,{fontSize:"11px",color:"#71717a"}),u.textContent="Enter to send, Shift+Enter for newline";const m=Lt("button",{className:"orquesta-builder-btn-primary orquesta-builder-submit"});m.textContent="Send",m.disabled=!this.state?.agentOnline,h.appendChild(u),h.appendChild(m),p.appendChild(d),p.appendChild(h),l.appendChild(p);const g=()=>{const t=d.value.trim();t&&!this.state?.isSubmitting&&(d.value="",this.builderMessages.push({role:"user",content:t}),this.updateBuilderMessages(),this.client.submitPrompt(t).catch(t=>{this.builderMessages.push({role:"status",content:`Error: ${t.message}`}),this.updateBuilderMessages()}))};this.cleanupFunctions.push(Mt(m,"click",g)),this.cleanupFunctions.push(Mt(d,"keydown",t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),g())})),a.appendChild(l);const f=Lt("div",{className:"orquesta-builder-resizer-h"});let b=!1;this.cleanupFunctions.push(Mt(f,"mousedown",()=>{b=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(Mt(document,"mousemove",t=>{if(!b)return;const e=Math.max(300,Math.min(t.clientX,.5*window.innerWidth));l.style.width=`${e}px`})),this.cleanupFunctions.push(Mt(document,"mouseup",()=>{b&&(b=!1,document.body.style.cursor="",document.body.style.userSelect="")})),a.appendChild(f);const x=Lt("div",{className:"orquesta-builder-preview"}),y=Lt("div",{className:"orquesta-builder-preview-bar"}),w=Lt("div");Ht(w,{display:"flex",gap:"6px"}),w.innerHTML='\n <span style="width:12px;height:12px;border-radius:50%;background:#ef4444"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#eab308"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#22c55e"></span>\n ',y.appendChild(w);const C=Lt("div",{className:"orquesta-builder-preview-url"});C.textContent=t,y.appendChild(C);const v=Lt("button");v.textContent="↻",v.title="Refresh preview",this.cleanupFunctions.push(Mt(v,"click",()=>{this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)})),y.appendChild(v),x.appendChild(y);const k=Lt("iframe",{className:"orquesta-builder-preview-iframe"});k.src=t,k.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.builderPreviewFrame=k,x.appendChild(k),a.appendChild(x),n.appendChild(a);const S=Lt("div",{className:"orquesta-builder-resizer-v"});let q=!1;const E=Lt("div",{className:"orquesta-builder-terminal"+(this.builderTerminalCollapsed?" collapsed":"")});this.cleanupFunctions.push(Mt(S,"mousedown",()=>{q=!0,document.body.style.cursor="row-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(Mt(document,"mousemove",t=>{if(!q)return;const e=Math.max(100,Math.min(window.innerHeight-t.clientY,.5*window.innerHeight));E.style.height=`${e}px`,this.builderTerminalCollapsed=!1,E.classList.remove("collapsed")})),this.cleanupFunctions.push(Mt(document,"mouseup",()=>{q&&(q=!1,document.body.style.cursor="",document.body.style.userSelect="")})),n.appendChild(S);const _=Lt("div",{className:"orquesta-builder-terminal-header"}),R=Lt("span",{className:"orquesta-builder-terminal-title"});R.textContent="Terminal";const O=Lt("button");O.textContent=this.builderTerminalCollapsed?"▲":"▼",O.title="Toggle terminal",this.cleanupFunctions.push(Mt(O,"click",()=>{this.builderTerminalCollapsed=!this.builderTerminalCollapsed,E.classList.toggle("collapsed",this.builderTerminalCollapsed),O.textContent=this.builderTerminalCollapsed?"▲":"▼"})),_.appendChild(R),_.appendChild(O),E.appendChild(_);const T=Lt("div",{className:"orquesta-builder-terminal-output"});this.builderTerminalOutput=T,E.appendChild(T),n.appendChild(E),this.elements.container.innerHTML="",this.elements.container.appendChild(n),this.builderRoot=n,Ht(this.elements.container,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",zIndex:"2147483647"}),d.focus()}updateBuilderMessages(){if(!this.builderMsgContainer)return;const t=this.builderMsgContainer.querySelector(".orquesta-builder-msg-system");this.builderMsgContainer.innerHTML="",t&&this.builderMsgContainer.appendChild(t);for(const t of this.builderMessages){const e=Lt("div",{className:`orquesta-builder-msg orquesta-builder-msg-${t.role}`});e.textContent=t.content,this.builderMsgContainer.appendChild(e)}this.builderMsgContainer.scrollTop=this.builderMsgContainer.scrollHeight}updateBuilderTerminal(){if(!this.builderTerminalOutput||!this.state)return;const t=this.state.outputLines;if(t.length!==this.builderLastOutputCount){for(let e=this.builderLastOutputCount;e<t.length;e++){const n=t[e],i=Lt("div");Ht(i,{color:this.getTerminalColor(n.type),whiteSpace:"pre-wrap",wordBreak:"break-all"}),i.textContent=n.content,this.builderTerminalOutput.appendChild(i)}this.builderLastOutputCount=t.length,this.builderTerminalOutput.scrollTop=this.builderTerminalOutput.scrollHeight}}getTerminalColor(t){switch(t){case"stderr":case"error":return"#ef4444";case"tool":case"tool_call":return"#3b82f6";case"tool_result":return"#22c55e";case"thinking":return"#71717a";case"system":return"#eab308";case"progress":return"#a78bfa";default:return"#d4d4d8"}}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}switchMode(t){this.currentMode!==t&&(this.currentMode=t,this.elements.container.innerHTML="",this.cleanupFunctions.forEach(t=>t()),this.cleanupFunctions=[],"widget"===t&&(this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,Ht(this.elements.container,{position:"",top:"",left:"",right:"",bottom:""}),this.isMinimized=!1,this.client.open()),this.render())}setMode(t){this.switchMode(t)}destroy(){this.unsubscribe?.(),this.cleanupFunctions.forEach(t=>t()),this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.client.disconnect(),this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,Pt(this.elements.container),Pt(function(t,e=document){return e.querySelector(t)}("#orquesta-embed-styles"))}showStatus(){this.showStatusBar=!0,this.statusBarMinimized=!1,this.render()}hideStatus(){this.showStatusBar=!1,this.render()}}const Ft={init(t){const e=new It(t);return e.init().catch(console.error),e},OrquestaWidget:It};return"undefined"!=typeof window&&(window.Orquesta=Ft),t.ConsoleCapture=Et,t.ElementSelector=Rt,t.NetworkCapture=_t,t.OrquestaEmbedClient=zt,t.OrquestaWidget=It,t.default=Ft,Object.defineProperty(t,"__esModule",{value:!0}),t}({});
|
|
1
|
+
var Orquesta=function(t){"use strict";const e=Object.create(null);e.open="0",e.close="1",e.ping="2",e.pong="3",e.message="4",e.upgrade="5",e.noop="6";const n=Object.create(null);Object.keys(e).forEach(t=>{n[e[t]]=t});const i={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,a=({type:t,data:n},i,a)=>s&&n instanceof Blob?i?a(n):l(n,a):o&&(n instanceof ArrayBuffer||r(n))?i?a(n):l(new Blob([n]),a):a(e[t]+(n||"")),l=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let p;const d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)h[d.charCodeAt(t)]=t;const u="function"==typeof ArrayBuffer,m=(t,e)=>{if("string"!=typeof t)return{type:"message",data:f(t,e)};const s=t.charAt(0);if("b"===s)return{type:"message",data:g(t.substring(1),e)};return n[s]?t.length>1?{type:n[s],data:t.substring(1)}:{type:n[s]}:i},g=(t,e)=>{if(u){const n=(t=>{let e,n,i,s,o,r=.75*t.length,a=t.length,l=0;"="===t[t.length-1]&&(r--,"="===t[t.length-2]&&r--);const c=new ArrayBuffer(r),p=new Uint8Array(c);for(e=0;e<a;e+=4)n=h[t.charCodeAt(e)],i=h[t.charCodeAt(e+1)],s=h[t.charCodeAt(e+2)],o=h[t.charCodeAt(e+3)],p[l++]=n<<2|i>>4,p[l++]=(15&i)<<4|s>>2,p[l++]=(3&s)<<6|63&o;return c})(t);return f(n,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,b=String.fromCharCode(30);function x(){return new TransformStream({transform(t,e){!function(t,e){s&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):o&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):a(t,!1,t=>{p||(p=new TextEncoder),e(p.encode(t))})}(t,n=>{const i=n.length;let s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);const t=new DataView(s.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{s=new Uint8Array(9);const t=new DataView(s.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(s[0]|=128),e.enqueue(s),e.enqueue(n)})}})}let y;function w(t){return t.reduce((t,e)=>t+e.length,0)}function C(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let i=0;for(let s=0;s<e;s++)n[s]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),n}function v(t){if(t)return function(t){for(var e in v.prototype)t[e]=v.prototype[e];return t}(t)}v.prototype.on=v.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},v.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},v.prototype.off=v.prototype.removeListener=v.prototype.removeAllListeners=v.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<i.length;s++)if((n=i[s])===e||n.fn===e){i.splice(s,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},v.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(n){i=0;for(var s=(n=n.slice(0)).length;i<s;++i)n[i].apply(this,e)}return this},v.prototype.emitReserved=v.prototype.emit,v.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},v.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),S="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function q(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const E=S.setTimeout,_=S.clearTimeout;function R(t,e){e.useNativeTimers?(t.setTimeoutFn=E.bind(S),t.clearTimeoutFn=_.bind(S)):(t.setTimeoutFn=S.setTimeout.bind(S),t.clearTimeoutFn=S.clearTimeout.bind(S))}function O(t){return"string"==typeof t?function(t){let e=0,n=0;for(let i=0,s=t.length;i<s;i++)e=t.charCodeAt(i),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function T(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class A extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class N extends v{constructor(t){super(),this.writable=!1,R(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new A(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=m(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class B extends N{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const n=t.split(b),i=[];for(let t=0;t<n.length;t++){const s=m(n[t],e);if(i.push(s),"error"===s.type)break}return i})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,i=new Array(n);let s=0;t.forEach((t,o)=>{a(t,!1,t=>{i[o]=t,++s===n&&e(i.join(b))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=T()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let z=!1;try{z="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const L=z;function M(){}class H extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class P extends v{constructor(t,e,n){super(),this.createRequest=t,R(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=q(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=P.requestsCount++,P.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=M,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete P.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(P.requestsCount=0,P.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",I);else if("function"==typeof addEventListener){addEventListener("onpagehide"in S?"pagehide":"unload",I,!1)}function I(){for(let t in P.requests)P.requests.hasOwnProperty(t)&&P.requests[t].abort()}const F=function(){const t=j({xdomain:!1});return t&&null!==t.responseType}();function j(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||L))return new XMLHttpRequest}catch(t){}if(!e)try{return new(S[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const $="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class D extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=$?{}:q(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;a(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=T()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const U=S.WebSocket||S.MozWebSocket;const W={websocket:class extends D{createSocket(t,e,n){return $?new U(t,e,n):e?new U(t,e):new U(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){y||(y=new TextDecoder);const n=[];let s=0,o=-1,r=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(0===s){if(w(n)<1)break;const t=C(n,1);r=!(128&~t[0]),o=127&t[0],s=o<126?3:126===o?1:2}else if(1===s){if(w(n)<2)break;const t=C(n,2);o=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),s=3}else if(2===s){if(w(n)<8)break;const t=C(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){l.enqueue(i);break}o=r*Math.pow(2,32)+e.getUint32(4),s=3}else{if(w(n)<o)break;const t=C(n,o);l.enqueue(m(r?t:y.decode(t),e)),s=0}if(0===o||o>t){l.enqueue(i);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),s=x();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const o=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),o())}).catch(t=>{})};o();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;this._writer.write(n).then(()=>{i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends H{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=F&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new P(j,this.uri(),t)}}},V=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,X=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),i=t.indexOf("]");-1!=n&&-1!=i&&(t=t.substring(0,n)+t.substring(n,i).replace(/:/g,";")+t.substring(i,t.length));let s=V.exec(t||""),o={},r=14;for(;r--;)o[X[r]]=s[r]||"";return-1!=n&&-1!=i&&(o.source=e,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=function(t,e){const n=/\/{2,9}/g,i=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1);"/"==e.slice(-1)&&i.splice(i.length-1,1);return i}(0,o.path),o.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(n[e]=i)}),n}(0,o.query),o}const Q="function"==typeof addEventListener&&"function"==typeof removeEventListener,Y=[];Q&&addEventListener("offline",()=>{Y.forEach(t=>t())},!1);class J extends v{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const n=K(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=K(e.host).host);R(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},n=t.split("&");for(let t=0,i=n.length;t<i;t++){let i=n[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),Q&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Y.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&J.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",J.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=O(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,k(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const s={type:t,data:e,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(J.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Q&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=Y.indexOf(this._offlineEventListener);-1!==t&&Y.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}J.protocol=4;class G extends J{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;J.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;J.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function s(){n||(n=!0,c(),e.close(),e=null)}const o=t=>{const n=new Error("probe error: "+t);n.transport=e.name,s(),this.emitReserved("upgradeError",n)};function r(){o("transport closed")}function a(){o("socket closed")}function l(t){e&&t.name!==e.name&&s()}const c=()=>{e.removeListener("open",i),e.removeListener("error",o),e.removeListener("close",r),this.off("close",a),this.off("upgrading",l)};e.once("open",i),e.once("error",o),e.once("close",r),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let Z=class extends G{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>W[t]).filter(t=>!!t)),super(t,n)}};const tt="function"==typeof ArrayBuffer,et=Object.prototype.toString,nt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===et.call(Blob),it="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===et.call(File);function st(t){return tt&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||nt&&t instanceof Blob||it&&t instanceof File}function ot(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(ot(t[e]))return!0;return!1}if(st(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return ot(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&ot(t[e]))return!0;return!1}function rt(t){const e=[],n=t.data,i=t;return i.data=at(n,e),i.attachments=e.length,{packet:i,buffers:e}}function at(t,e){if(!t)return t;if(st(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=at(t[i],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=at(t[i],e));return n}return t}function lt(t,e){return t.data=ct(t.data,e),delete t.attachments,t}function ct(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=ct(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=ct(t[n],e));return t}const pt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var dt;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(dt||(dt={}));class ht extends v{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===dt.BINARY_EVENT;n||e.type===dt.BINARY_ACK?(e.type=n?dt.EVENT:dt.ACK,this.reconstructor=new ut(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!st(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===dt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===dt.BINARY_EVENT||n.type===dt.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const s=t.substring(i,e);if(s!=Number(s)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const o=Number(s);if(!mt(o)||o<0)throw new Error("Illegal attachments");if(o>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=o}if("/"===t.charAt(e+1)){const i=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(i,e)}else n.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!ht.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case dt.CONNECT:return gt(e);case dt.DISCONNECT:return void 0===e;case dt.CONNECT_ERROR:return"string"==typeof e||gt(e);case dt.EVENT:case dt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===pt.indexOf(e[0]));case dt.ACK:case dt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ut{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=lt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const mt=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function gt(t){return"[object Object]"===Object.prototype.toString.call(t)}var ft=Object.freeze({__proto__:null,Decoder:ht,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==dt.EVENT&&t.type!==dt.ACK||!ot(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===dt.EVENT?dt.BINARY_EVENT:dt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==dt.BINARY_EVENT&&t.type!==dt.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=rt(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}},get PacketType(){return dt},isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||mt(e))&&function(t,e){switch(t){case dt.CONNECT:return void 0===e||gt(e);case dt.DISCONNECT:return void 0===e;case dt.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===pt.indexOf(e[0]));case dt.ACK:return Array.isArray(e);case dt.CONNECT_ERROR:return"string"==typeof e||gt(e);default:return!1}}(t.type,t.data);var e},protocol:5});function bt(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const xt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class yt extends v{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[bt(t,"open",this.onopen.bind(this)),bt(t,"packet",this.onpacket.bind(this)),bt(t,"error",this.onerror.bind(this)),bt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,i,s;if(xt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:dt.EVENT,data:e,options:{}};if(o.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),o.id=t}const r=null===(i=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!r||(a?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const s=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),o=(...t)=>{this.io.clearTimeoutFn(s),e.apply(this,t)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,i)=>{const s=(t,e)=>t?i(t):n(e);s.withError=!0,e.push(s),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>{this._queue[0];return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:dt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case dt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case dt.EVENT:case dt.BINARY_EVENT:this.onevent(t);break;case dt.ACK:case dt.BINARY_ACK:this.onack(t);break;case dt.DISCONNECT:this.ondisconnect();break;case dt.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...i){n||(n=!0,e.packet({type:dt.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:dt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function wt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}wt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},wt.prototype.reset=function(){this.attempts=0},wt.prototype.setMin=function(t){this.ms=t},wt.prototype.setMax=function(t){this.max=t},wt.prototype.setJitter=function(t){this.jitter=t};class Ct extends v{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,R(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||ft;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Z(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=bt(e,"open",function(){n.onopen(),t&&t()}),s=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},o=bt(e,"error",s);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{i(),s(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(i),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(bt(t,"ping",this.onping.bind(this)),bt(t,"data",this.ondata.bind(this)),bt(t,"error",this.onerror.bind(this)),bt(t,"close",this.onclose.bind(this)),bt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new yt(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const vt={};function kt(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let i=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),i=K(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const s=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+e,i.href=i.protocol+"://"+s+(n&&n.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=n.source,s=n.id,o=n.path,r=vt[s]&&o in vt[s].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||r?a=new Ct(i,e):(vt[s]||(vt[s]=new Ct(i,e)),a=vt[s]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(kt,{Manager:Ct,Socket:yt,io:kt,connect:kt});const St={mode:"widget",position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class qt{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[],isSubmitting:!1,promptQueue:[],outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1}}getState(){return{...this.state}}setState(t){this.state={...this.state,...t},this.notify()}subscribe(t){return this.listeners.add(t),t(this.getState()),()=>this.listeners.delete(t)}notify(){const t=this.getState();this.listeners.forEach(e=>e(t))}setConnected(t,e,n){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:t,projectName:e,agentOnline:n})}setConnectionError(t){this.setState({isConnected:!1,isConnecting:!1,connectionError:t})}setOpen(t){this.setState({isOpen:t})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(t){this.setState({activeTab:t})}setCurrentPrompt(t){this.setState({currentPrompt:t}),t&&!this.state.promptHistory.find(e=>e.id===t.id)&&this.setState({promptHistory:[t,...this.state.promptHistory].slice(0,50)})}updatePrompt(t,e){this.state.currentPrompt?.id===t&&this.setState({currentPrompt:{...this.state.currentPrompt,...e}}),this.setState({promptHistory:this.state.promptHistory.map(n=>n.id===t?{...n,...e}:n)})}addOutputLine(t){const e={...t,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,e]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(t){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[t]:[...this.state.outputLines]}})}addToQueue(t){this.setState({promptQueue:[...this.state.promptQueue,t]})}getNextFromQueue(){if(0===this.state.promptQueue.length)return null;const[t,...e]=this.state.promptQueue;return this.setState({promptQueue:e}),t}clearQueue(){this.setState({promptQueue:[]})}getQueueLength(){return this.state.promptQueue.length}setSelectedElement(t){this.setState({selectedElement:t,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(t){this.setState({overlayMode:t}),"off"===t&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(t){this.setState({highlightedPromptId:t})}setElementMarkers(t){this.setState({elementMarkers:t})}setCommentsForPrompt(t,e){this.setState({comments:{...this.state.comments,[t]:e}})}addComment(t,e){const n=this.state.comments[t]||[];this.setState({comments:{...this.state.comments,[t]:[...n,e]}}),this.setState({promptHistory:this.state.promptHistory.map(e=>e.id===t?{...e,comment_count:(e.comment_count||0)+1}:e)})}setExpandedPromptId(t){this.setState({expandedPromptId:t})}setLoadingComments(t){this.setState({isLoadingComments:t})}addConsoleLogs(t){this.setState({consoleLogs:[...this.state.consoleLogs,...t].slice(-100)})}addNetworkLogs(t){this.setState({networkLogs:[...this.state.networkLogs,...t].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}toggleIncludeHistory(){this.setState({includeHistory:!this.state.includeHistory})}toggleIncludeContext(){this.setState({includeContext:!this.state.includeContext})}setAuth(t,e){this.setState({user:t,isAuthenticated:e,isAuthenticating:!1,authError:null})}setAuthenticating(t){this.setState({isAuthenticating:t})}setAuthError(t){this.setState({authError:t,isAuthenticating:!1})}setRequireAuth(t){this.setState({requireAuth:t})}reset(){this.state=this.getInitialState(),this.notify()}}class Et{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const t=t=>(...e)=>{const n=this.createEntry(t,e);this.addEntry(n),this.originalConsole?.[t](...e)};console.log=t("log"),console.info=t("info"),console.warn=t("warn"),console.error=t("error"),this.errorHandler=t=>{const e=this.createEntry("error",[t.message],t.error?.stack);this.addEntry(e)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason),n=t.reason instanceof Error?t.reason.stack:void 0,i=this.createEntry("error",[`Unhandled Promise Rejection: ${e}`],n);this.addEntry(i)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}formatArg(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(null===t)return"null";if(void 0===t)return"undefined";if("object"==typeof t)try{const e=JSON.stringify(t,null,2);if("{}"===e||"[]"===e){const e=Object.prototype.toString.call(t);if("[object Object]"!==e&&"[object Array]"!==e)return e}return e}catch{return Object.prototype.toString.call(t)}return String(t)}createEntry(t,e,n){const i=e.map(t=>this.formatArg(t)).join(" ");return{timestamp:Date.now(),level:t,message:i||"(empty)",args:e,stack:n}}addEntry(t){this.buffer.push(t),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(e=>e(t))}getAll(){return[...this.buffer]}getRecent(t=20){return this.buffer.slice(-t)}getErrors(){return this.buffer.filter(t=>"error"===t.level||"warn"===t.level)}clear(){this.buffer=[]}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}formatForPrompt(t){const e=t||this.getRecent(20);return 0===e.length?"":e.map(t=>`${`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}]`} ${t.message}${t.stack?`\n${t.stack}`:""}`).join("\n")}}class _t{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(t,e)=>{const n="string"==typeof t?t:t instanceof URL?t.href:t.url,i=e?.method||"GET",s=Date.now(),o={timestamp:s,method:i,url:n,requestBody:e?.body};try{const n=await this.originalFetch(t,e);if(o.status=n.status,o.duration=Date.now()-s,!n.ok)try{const t=n.clone();o.responseBody=await t.text()}catch{}return this.addEntry(o),n}catch(t){throw o.duration=Date.now()-s,o.error=t instanceof Error?t.message:String(t),this.addEntry(o),t}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const t=this,e=new WeakMap;XMLHttpRequest.prototype.open=function(n,i,...s){return e.set(this,{method:n,url:"string"==typeof i?i:i.href,startTime:0}),t.originalXHROpen.apply(this,[n,i,...s])},XMLHttpRequest.prototype.send=function(n){const i=e.get(this);return i&&(i.startTime=Date.now(),this.addEventListener("loadend",()=>{const e={timestamp:i.startTime,method:i.method,url:i.url,status:this.status,duration:Date.now()-i.startTime};if(this.status>=400||0===this.status){e.error=this.statusText||"Request failed";try{e.responseBody=this.responseText}catch{}}t.addEntry(e)})),t.originalXHRSend.call(this,n)}}addEntry(t){this.buffer.push(t),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(e=>e(t))}getAll(){return[...this.buffer]}getRecent(t=20){return this.buffer.slice(-t)}getErrors(){return this.buffer.filter(t=>t.status&&t.status>=400||t.error)}clear(){this.buffer=[]}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}formatForPrompt(t){const e=t||this.getErrors();return 0===e.length?"":e.map(t=>{const e=new Date(t.timestamp).toISOString(),n=t.status?`[${t.status}]`:"[FAILED]";return`[${e}] ${t.method} ${t.url} ${n}${t.error?` - ${t.error}`:""}`}).join("\n")}}class Rt{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=t=>{if(!this.isActive||!this.highlight)return;const e=document.elementFromPoint(t.clientX,t.clientY);if(!e||e.id?.startsWith("orquesta-"))return;this.selectedElement=e;const n=e.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${n.top}px`,this.highlight.style.left=`${n.left}px`,this.highlight.style.width=`${n.width}px`,this.highlight.style.height=`${n.height}px`;const i=this.highlight.querySelector("#orquesta-element-label");if(i){const t=e.tagName.toLowerCase(),n=e.id?`#${e.id}`:"",s=e.className&&"string"==typeof e.className?`.${e.className.split(" ").slice(0,2).join(".")}`:"";i.textContent=`<${t}${n}${s}>`}},this.handleClick=t=>{if(!this.isActive)return;const e=t.target;if(!e.id?.startsWith("orquesta-")&&(t.preventDefault(),t.stopPropagation(),this.selectedElement)){const t=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(t)}},this.handleKeyDown=t=>{"Escape"===t.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(t){return this.globalRightClickCallback=t,this.globalRightClickHandler=t=>{const e=t.target;if(e.closest('[id^="orquesta-"]'))return;if(this.isActive)return;t.preventDefault(),t.stopPropagation();const n=this.getElementContext(e);this.globalRightClickCallback?.(n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(t){return this.globalRightClickWithPositionCallback=t,this.globalRightClickHandler=t=>{const e=t.target;if(e.closest('[id^="orquesta-"]'))return;if(this.isActive)return;t.preventDefault(),t.stopPropagation();const n=this.getElementContext(e),i={x:t.clientX,y:t.clientY};this.globalRightClickWithPositionCallback?.(n,i)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(t){try{const e=this.safeQuerySelector(t);if(!e)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const n=document.createElement("div");n.id="orquesta-selected-element-label",n.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const i=e.tagName.toLowerCase(),s=e.id?`#${e.id}`:"",o=e.className&&"string"==typeof e.className?`.${e.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Selected: <${i}${s}${o}>`,this.selectedHighlight.appendChild(n);const r=()=>{if(!this.selectedHighlight)return;const t=e.getBoundingClientRect();this.selectedHighlight.style.top=t.top-3+"px",this.selectedHighlight.style.left=t.left-3+"px",this.selectedHighlight.style.width=`${t.width+6}px`,this.selectedHighlight.style.height=`${t.height+6}px`};return r(),this.selectedElementScrollHandler=r,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),e}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(t,e){this.isActive||(this.isActive=!0,this.onSelect=t,this.onCancel=e||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const t=document.createElement("div");t.id="orquesta-element-label",t.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(t)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(t){try{const e=this.safeQuerySelector(t);if(!e)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let n=document.getElementById("orquesta-prompt-highlight");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight",n.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(n));let i=n.querySelector("#orquesta-prompt-highlight-label");i||(i=document.createElement("div"),i.id="orquesta-prompt-highlight-label",i.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',n.appendChild(i));const s=e.tagName.toLowerCase(),o=e.id?`#${e.id}`:"",r=e.className&&"string"==typeof e.className?`.${e.className.split(" ").slice(0,2).join(".")}`:"";i.textContent=`Highlighted: <${s}${o}${r}>`;const a=()=>{const t=e.getBoundingClientRect();n.style.display="block",n.style.top=t.top-3+"px",n.style.left=t.left-3+"px",n.style.width=`${t.width+6}px`,n.style.height=`${t.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=e.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&e.scrollIntoView({behavior:"smooth",block:"center"}),e}catch{return null}}removeHighlight(){const t=document.getElementById("orquesta-prompt-highlight");t&&(t.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}safeQuerySelector(t){try{return document.querySelector(t)}catch{return null}}findElement(t,e){try{let n=this.safeQuerySelector(t);if(n)return n;if(e&&(n=document.getElementById(e),n))return n;const i=t.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(i){const[,t,e]=i;if(n=this.safeQuerySelector(`${t}.${e}`),n)return n}return null}catch{return null}}getElementContext(t){const e=t.getBoundingClientRect(),n={};for(const e of t.attributes)e.name.startsWith("data-")||"class"===e.name||"id"===e.name||(n[e.name]=e.value);return{selector:this.generateSelector(t),tag:t.tagName.toLowerCase(),id:t.id||void 0,className:"string"==typeof t.className?t.className:void 0,textContent:t.textContent?.trim().slice(0,200)||void 0,boundingRect:e,attributes:Object.keys(n).length>0?n:void 0}}isValidCssClass(t){return!/[@:/\[\]()!#]/.test(t)&&!!/^[a-zA-Z_-]/.test(t)}generateSelector(t){if(t.id&&this.isValidCssClass(t.id))return`#${t.id}`;const e=[];let n=t;for(;n&&n!==document.body;){let t=n.tagName.toLowerCase();if(n.id&&this.isValidCssClass(n.id)){t=`#${n.id}`,e.unshift(t);break}if(n.className&&"string"==typeof n.className){const e=n.className.trim().split(/\s+/).filter(t=>this.isValidCssClass(t)).slice(0,2);e.length>0&&(t+=`.${e.join(".")}`)}const i=n.parentElement;if(i){const e=Array.from(i.children).filter(t=>t.tagName===n.tagName);if(e.length>1){t+=`:nth-child(${e.indexOf(n)+1})`}}e.unshift(t),n=n.parentElement}return e.join(" > ")}}class Ot{constructor(t,e){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.broadcastChannel=null,this.pollInterval=null,this.token=t,this.apiUrl=e,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(t){this.state={...this.state,...t},this.notify()}subscribe(t){return this.listeners.add(t),t(this.getState()),()=>this.listeners.delete(t)}notify(){const t=this.getState();this.listeners.forEach(e=>e(t))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(t){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(t))}catch{}}loadSession(){try{const t=localStorage.getItem(this.getStorageKey());if(!t)return null;const e=JSON.parse(t);return e.expiresAt&&new Date(e.expiresAt)<new Date?(this.clearSession(),null):e}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const t=this.loadSession();if(!t)return!1;try{const e=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:t.sessionToken})});if(!e.ok)return this.clearSession(),!1;const n=await e.json();return n.valid?(this.setState({isAuthenticated:!0,user:n.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null}),!0}}login(){return new Promise((t,e)=>{this.setState({isAuthenticating:!0,authError:null});const n=Math.random().toString(36).slice(2),i=`eas_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,s=new URL(`${this.apiUrl}/embed/auth`);s.searchParams.set("token",this.token),s.searchParams.set("origin",window.location.origin),s.searchParams.set("state",n),s.searchParams.set("authSession",i);const o=window.screenX+(window.innerWidth-500)/2,r=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(s.toString(),"orquesta_auth",`width=500,height=600,left=${o},top=${r},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void e(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=n=>{if(n.origin!==new URL(this.apiUrl).origin)return;const{type:i,payload:s}=n.data||{};"orquesta_auth_success"===i?(this.handleAuthSuccess(s),t(s),this.cleanup()):"orquesta_auth_error"===i?(this.handleAuthError(s),e(new Error(s.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===i&&(this.setState({isAuthenticating:!1}),e(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=this.apiUrl.replace("://orquesta.live","://ws.orquesta.live").replace("://localhost:3113","://localhost:3200");this.pollInterval=setInterval(async()=>{try{const n=await fetch(`${a}/auth/result/${i}`);if(!n.ok)return;const s=await n.json();if(s.pending)return;const{type:o,payload:r}=s;"orquesta_auth_success"===o?(this.handleAuthSuccess(r),t(r),this.cleanup()):"orquesta_auth_error"===o&&(this.handleAuthError(r),e(new Error(r.message||"Authentication failed")),this.cleanup())}catch{}},1500);const l=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(l),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),e(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(t){const e={user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt};this.saveSession(e),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null})}handleAuthError(t){this.setState({isAuthenticating:!1,authError:t.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const t=this.loadSession();if(t?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:t.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const Tt=!1,At="prompts",Nt="dark";const Bt=new class{constructor(){this.projectId=null}setProjectId(t){this.projectId=t}getKey(t){const e=`orquesta_embed_${t}`;return this.projectId?`${e}_${this.projectId}`:e}get(t){try{const e=localStorage.getItem(this.getKey(t));return e?JSON.parse(e):null}catch{return null}}set(t,e){try{localStorage.setItem(this.getKey(t),JSON.stringify(e))}catch{}}remove(t){try{localStorage.removeItem(this.getKey(t))}catch{}}getState(){return{isOpen:this.get("isOpen")??Tt,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??At,theme:this.get("theme")??Nt}}setState(t){Object.entries(t).forEach(([t,e])=>{void 0!==e&&this.set(t,e)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(t=>this.remove(t))}};class zt{constructor(t){this.socket=null,this.channelName=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...St,...t},this.state=new qt,this.consoleCapture=new Et,this.networkCapture=new _t,this.elementSelector=new Rt,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new Ot(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(t=>{this.state.setState({isAuthenticated:t.isAuthenticated,isAuthenticating:t.isAuthenticating,user:t.user,authError:t.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const t=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!t.ok){const e=await t.json();throw new Error(e.error||"Failed to validate token")}const e=await t.json();if(!e.valid)throw new Error("Invalid embed token");this.projectId=e.projectId,Bt.setProjectId(e.projectId);const n=e.requireAuth||this.config.requireAuth;n&&!this.authManager?(this.state.setRequireAuth(!0),this.authManager=new Ot(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(t=>{this.state.setState({isAuthenticated:t.isAuthenticated,isAuthenticating:t.isAuthenticating,user:t.user,authError:t.authError})}),await this.authManager.checkSession()):n&&this.state.setRequireAuth(!0),this.channelName=e.channelName;const i=kt("https://ws.orquesta.live",{auth:{embedToken:this.config.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,timeout:1e4});this.socket=i,i.on("output",t=>this.handleOutput(t)),i.on("complete",t=>this.handleComplete(t)),i.on("error",t=>this.handleError(t));let s=!1;i.on("connect",()=>{if(i.emit("subscribe",{channel:e.channelName}),this.state.setConnected(e.projectId,e.project?.name||"Project",e.project?.agent_online||!1),s)return;s=!0,this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(t=>{this.state.addConsoleLogs([t])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(t=>{this.state.addNetworkLogs([t])})),this.setupHotkey(),this.loadTimeline();const t=Bt.getState();this.state.setState({isOpen:this.config.defaultOpen??t.isOpen,activeTab:t.activeTab||"prompts"}),this.config.onReady?.()}),i.on("connect_error",t=>{const e=t?.message||"Failed to connect to WS server";this.state.setConnectionError(e)}),i.on("disconnect",()=>{this.state.setState({isConnecting:!1})})}catch(t){const e=t instanceof Error?t.message:"Connection failed";throw this.state.setConnectionError(e),this.config.onError?.(t instanceof Error?t:new Error(e)),t}}disconnect(){if(this.socket){if(this.channelName)try{this.socket.emit("unsubscribe",{channel:this.channelName})}catch{}this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null}this.channelName=null,this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const t=this.config.hotkey.toLowerCase().split("+"),e=t.pop(),n=new Set(t);this.hotkeyHandler=t=>{if(!t.key)return;const i=n.has("ctrl")===(t.ctrlKey||t.metaKey),s=n.has("shift")===t.shiftKey,o=n.has("alt")===t.altKey,r=t.key.toLowerCase()===e;i&&s&&o&&r&&(t.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(t){if(!this.state.getState().currentPrompt)return;let e,n,i,s="stdout",o=t.data;"stderr"===t.type?s="stderr":t.data.includes("Tool:")||t.data.includes("tool_call")?s="tool":(t.data.includes("thinking")||t.data.includes("Thinking"))&&(s="thinking");try{const r=JSON.parse(t.data);if(r.type){switch(r.type){case"thinking":s="thinking",o=r.thinking?.content||t.data;break;case"tool_call":s="tool_call",n=r.tool_call?.name,o=`Using ${n||"tool"}`;break;case"tool_result":s="tool_result",n=r.tool_result?.name,i=r.tool_result?.success,o=i?r.tool_result?.output||"Success":r.tool_result?.error||"Failed";break;case"output":s="output",o=r.output?.content||t.data;break;case"error":s="error",o=r.error?.message||t.data;break;case"system":s="system",o=r.system?.message||r.system?.event||t.data;break;case"progress":s="progress";const e=void 0!==r.progress?.percentage?` (${r.progress.percentage}%)`:"";o=(r.progress?.message||"Processing")+e;break;default:o=r.content||r.message||t.data}e=r}}catch{}this.state.addOutputLine({timestamp:t.timestamp||Date.now(),type:s,content:o,details:e,toolName:n,toolSuccess:i})}handleComplete(t){const e=this.state.getState(),n=0===t.exitCode?"completed":"failed",i=e.currentPrompt?.id;if(e.currentPrompt&&(this.state.storePromptOutput(e.currentPrompt.id),this.state.updatePrompt(e.currentPrompt.id,{status:n,completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),i&&this.config.onPromptComplete&&this.config.onPromptComplete(i,n),this.config.reloadOnComplete&&"completed"===n){const t=this.config.reloadDelay??1500;return console.log(`[Orquesta Embed] Prompt completed. Reloading page in ${t}ms...`),void setTimeout(()=>{window.location.reload()},t)}this.processQueue()}async processQueue(){const t=this.state.getNextFromQueue();if(t){console.log(`[Orquesta Embed] Processing queued prompt. Remaining in queue: ${this.state.getQueueLength()}`);try{await this.submitPrompt(t.content,t.options)}catch(t){console.error("[Orquesta Embed] Failed to process queued prompt:",t),this.processQueue()}}}handleError(t){const e=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${t.error}`}),e.currentPrompt&&(this.state.storePromptOutput(e.currentPrompt.id),this.state.updatePrompt(e.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),this.processQueue()}async submitPrompt(t,e){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const n=this.state.getState();if(n.isSubmitting)return this.state.addToQueue({id:`queue-${Date.now()}`,content:t,options:e,queuedAt:Date.now()}),console.log(`[Orquesta Embed] Prompt queued. Queue length: ${this.state.getQueueLength()}`),`queued-${Date.now()}`;this.state.setState({isSubmitting:!0}),this.state.clearOutput();let i=t;const s=e?.elementContext||n.selectedElement;if(s&&(i+=`\n\n--- Element Context ---\nSelector: ${s.selector}\nTag: <${s.tag}>\n${s.id?`ID: ${s.id}`:""}\n${s.className?`Classes: ${s.className}`:""}\n${s.textContent?`Text: ${s.textContent}`:""}\n${s.attributes?`Attributes: ${JSON.stringify(s.attributes)}`:""}`),e?.includeConsole??n.includeConsole){const t=this.consoleCapture.formatForPrompt();t&&(i+=`\n\n--- Console Logs ---\n${t}`)}if(e?.includeNetwork??n.includeNetwork){const t=this.networkCapture.formatForPrompt();t&&(i+=`\n\n--- Network Errors ---\n${t}`)}if(e?.includeHistory??n.includeHistory){const t=n.promptHistory.filter(t=>"completed"===t.status).slice(0,5).reverse();t.length>0&&(i+="\n\n--- Previous Prompts Context ---",t.forEach((t,e)=>{i+=`\n\n[Prompt ${e+1}]: ${t.content}`;const s=n.promptOutputs[t.id];if(s&&s.length>0){const t=s.slice(-10).map(t=>t.content).join("\n");i+=`\n[Output ${e+1}]:\n${t}`}}))}try{const t={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},e=this.authManager?.getSessionToken();e&&(t["X-Session-Token"]=e);const n=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:t,body:JSON.stringify({projectId:this.projectId,content:i,elementContext:s})});if(!n.ok){const t=await n.json();throw new Error(t.error||"Failed to submit prompt")}const o=(await n.json()).prompt;return this.state.setCurrentPrompt(o),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(o.id),o.id}catch(t){throw this.state.setState({isSubmitting:!1}),t}}async loadTimeline(){if(this.projectId)try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const e=await t.json();this.state.setState({promptHistory:e.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),Bt.set("isOpen",!0)}close(){this.state.setOpen(!1),Bt.set("isOpen",!1)}toggle(){const t=!this.state.getState().isOpen;this.state.setOpen(t),Bt.set("isOpen",t)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(t=>this.state.setSelectedElement(t),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(t){return this.state.subscribe(t)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}setActiveTab(t){this.state.setActiveTab(t)}async loadComments(t){if(this.projectId){this.state.setLoadingComments(!0);try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts/${t}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const n=await e.json();this.state.setCommentsForPrompt(t,n.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(t,e){if(this.projectId)try{const n=await fetch(`${this.config.apiUrl}/api/embed/prompts/${t}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:e})});if(n.ok){const e=await n.json();e.comment&&this.state.addComment(t,e.comment)}}catch(t){throw console.error("Failed to add comment:",t),t}}setOverlayMode(t){if(this.state.setOverlayMode(t),"off"===t)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===t){const t=this.state.getState().promptHistory.filter(t=>t.element_context?.selector).map(t=>({promptId:t.id,selector:t.element_context.selector,rect:null,content:t.content,author:t.author||null,gitCommitSha:t.git_commit_sha||null,commentCount:t.comment_count||0}));this.state.setElementMarkers(t)}else this.state.setElementMarkers([])}highlightPromptElement(t){if(!t.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(t.element_context.selector)?(this.state.setHighlightedPromptId(t.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",t.id)}setupGlobalRightClick(t){return this.elementSelector.setupGlobalRightClick(t)}setupGlobalRightClickWithPosition(t){return this.elementSelector.setupGlobalRightClickWithPosition(t)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const t=await this.authManager.login();return this.config.onLogin?.(t.user),t.user}catch(t){throw t}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}function Lt(t,e,n){const i=document.createElement(t);return e&&Object.entries(e).forEach(([t,e])=>{void 0!==e&&!1!==e&&("className"===t?i.className=e:t.startsWith("on")&&"string"==typeof e||(!0===e?i.setAttribute(t,""):i.setAttribute(t,e)))}),n&&n.forEach(t=>{"string"==typeof t?i.appendChild(document.createTextNode(t)):i.appendChild(t)}),i}function Mt(t,e,n,i){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n,i)}function Ht(t,e){Object.assign(t.style,e)}function Pt(t){t?.parentNode?.removeChild(t)}class It{constructor(t){this.state=null,this.elements={container:document.createElement("div"),panel:null,trigger:null,promptInput:null,logStream:null,statusBar:null,statusBarMinimized:null,contextMenu:null,elementMarkers:null},this.unsubscribe=null,this.cleanupFunctions=[],this.isMinimized=!1,this.showStatusBar=!0,this.statusBarMinimized=!1,this.lastCompletedPrompt=null,this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,this.builderTerminalCollapsed=!1,this.builderMessages=[],this.builderLastOutputCount=0,this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.globalRightClickCleanup=null,this.config=t,this.currentMode=t.mode||"widget",this.client=new zt(t),function(t,e){const n=document.getElementById(e);if(n)return n;const i=document.createElement("style");i.id=e,i.textContent=t,document.head.appendChild(i)}("\n/* Orquesta Embed SDK Styles - Auto-injected */\n/* These styles are scoped to orquesta-* classes to avoid conflicts */\n\n/* Reset for Orquesta elements */\n[class^=\"orquesta-\"],\n[class*=\" orquesta-\"] {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Base colors */\n.orquesta-embed-panel {\n --orq-bg: #18181b;\n --orq-bg-secondary: #27272a;\n --orq-border: #3f3f46;\n --orq-text: #fafafa;\n --orq-text-muted: #a1a1aa;\n --orq-primary: #3b82f6;\n --orq-success: #22c55e;\n --orq-warning: #eab308;\n --orq-error: #ef4444;\n}\n\n/* Scrollbar styling */\n.orquesta-embed-panel ::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb {\n background: #3f3f46;\n border-radius: 3px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb:hover {\n background: #52525b;\n}\n\n/* Animations */\n@keyframes orquesta-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n@keyframes orquesta-pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.5;\n }\n}\n\n.orquesta-embed-panel .animate-spin {\n animation: orquesta-spin 1s linear infinite;\n}\n\n.orquesta-embed-panel .animate-pulse {\n animation: orquesta-pulse 2s ease-in-out infinite;\n}\n\n/* Utility classes */\n.orquesta-embed-panel .line-clamp-1 {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n.orquesta-embed-panel .line-clamp-2 {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n/* Focus visible */\n.orquesta-embed-panel button:focus-visible,\n.orquesta-embed-panel input:focus-visible,\n.orquesta-embed-panel textarea:focus-visible {\n outline: 2px solid var(--orq-primary);\n outline-offset: 2px;\n}\n\n/* Element selector highlight animation */\n#orquesta-element-highlight {\n animation: orquesta-highlight-pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes orquesta-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);\n }\n}\n\n/* Tooltip */\n.orquesta-tooltip {\n position: absolute;\n z-index: 2147483647;\n padding: 4px 8px;\n background: #18181b;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n font-size: 12px;\n color: #fafafa;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* Transitions */\n.orquesta-embed-panel * {\n transition-property: color, background-color, border-color, opacity, transform;\n transition-duration: 150ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n/* Panel entrance animation */\n.orquesta-embed-panel {\n animation: orquesta-panel-enter 0.2s ease-out;\n}\n\n@keyframes orquesta-panel-enter {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n}\n\n/* Trigger button */\n.orquesta-embed-trigger {\n animation: orquesta-trigger-enter 0.3s ease-out;\n}\n\n@keyframes orquesta-trigger-enter {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* Log stream */\n.orquesta-log-stream {\n background: #0a0a0a;\n border: 1px solid #27272a;\n border-radius: 6px;\n padding: 8px;\n}\n\n/* Timeline item hover */\n.orquesta-timeline button:hover {\n transform: translateX(2px);\n}\n\n/* ============================================ */\n/* Tailwind class overrides - CRITICAL STYLES */\n/* These ensure styles work even when purged */\n/* ============================================ */\n\n/* Explicit background colors */\n.orquesta-embed-panel {\n background-color: #18181b !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel .bg-zinc-950 { background-color: #09090b !important; }\n.orquesta-embed-panel .bg-zinc-900 { background-color: #18181b !important; }\n.orquesta-embed-panel .bg-zinc-800 { background-color: #27272a !important; }\n.orquesta-embed-panel .bg-zinc-700 { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .bg-zinc-600 { background-color: #52525b !important; }\n\n/* Text colors */\n.orquesta-embed-panel .text-white { color: #fafafa !important; }\n.orquesta-embed-panel .text-zinc-100 { color: #f4f4f5 !important; }\n.orquesta-embed-panel .text-zinc-200 { color: #e4e4e7 !important; }\n.orquesta-embed-panel .text-zinc-300 { color: #d4d4d8 !important; }\n.orquesta-embed-panel .text-zinc-400 { color: #a1a1aa !important; }\n.orquesta-embed-panel .text-zinc-500 { color: #71717a !important; }\n.orquesta-embed-panel .text-red-400 { color: #f87171 !important; }\n.orquesta-embed-panel .text-red-300 { color: #fca5a5 !important; }\n.orquesta-embed-panel .text-green-400 { color: #4ade80 !important; }\n.orquesta-embed-panel .text-green-500 { color: #22c55e !important; }\n.orquesta-embed-panel .text-blue-400 { color: #60a5fa !important; }\n.orquesta-embed-panel .text-blue-500 { color: #3b82f6 !important; }\n.orquesta-embed-panel .text-yellow-400 { color: #facc15 !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .text-orange-400 { color: #fb923c !important; }\n.orquesta-embed-panel .text-gray-800 { color: #1f2937 !important; }\n\n/* Border colors */\n.orquesta-embed-panel .border-zinc-700 { border-color: #3f3f46 !important; }\n.orquesta-embed-panel .border-zinc-800 { border-color: #27272a !important; }\n.orquesta-embed-panel .border-red-800 { border-color: #991b1b !important; }\n\n/* Background colors for buttons and UI */\n.orquesta-embed-panel .bg-blue-500 { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .bg-blue-600 { background-color: #2563eb !important; }\n.orquesta-embed-panel .bg-green-400 { background-color: #4ade80 !important; }\n.orquesta-embed-panel .bg-green-500 { background-color: #22c55e !important; }\n.orquesta-embed-panel .bg-green-600 { background-color: #16a34a !important; }\n.orquesta-embed-panel .bg-red-500 { background-color: #ef4444 !important; }\n.orquesta-embed-panel .bg-red-600 { background-color: #dc2626 !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-red-900\\/30 { background-color: rgba(127, 29, 29, 0.3) !important; }\n.orquesta-embed-panel .bg-white { background-color: #ffffff !important; }\n\n/* Hover states */\n.orquesta-embed-panel .hover\\:bg-zinc-700:hover { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .hover\\:bg-zinc-800:hover { background-color: #27272a !important; }\n.orquesta-embed-panel .hover\\:bg-blue-500:hover { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .hover\\:bg-blue-700:hover { background-color: #1d4ed8 !important; }\n.orquesta-embed-panel .hover\\:bg-gray-100:hover { background-color: #f3f4f6 !important; }\n.orquesta-embed-panel .hover\\:text-white:hover { color: #fafafa !important; }\n.orquesta-embed-panel .hover\\:text-zinc-300:hover { color: #d4d4d8 !important; }\n\n/* Form inputs */\n.orquesta-embed-panel input,\n.orquesta-embed-panel textarea {\n background-color: #27272a !important;\n border-color: #3f3f46 !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel input::placeholder,\n.orquesta-embed-panel textarea::placeholder {\n color: #71717a !important;\n}\n\n/* Buttons base */\n.orquesta-embed-panel button {\n background-color: transparent;\n}\n\n.orquesta-embed-panel button:hover {\n background-color: #3f3f46;\n}\n\n/* Rounded borders */\n.orquesta-embed-panel .rounded { border-radius: 0.25rem !important; }\n.orquesta-embed-panel .rounded-md { border-radius: 0.375rem !important; }\n.orquesta-embed-panel .rounded-lg { border-radius: 0.5rem !important; }\n.orquesta-embed-panel .rounded-xl { border-radius: 0.75rem !important; }\n.orquesta-embed-panel .rounded-full { border-radius: 9999px !important; }\n\n/* Border widths */\n.orquesta-embed-panel .border { border-width: 1px !important; }\n.orquesta-embed-panel .border-b { border-bottom-width: 1px !important; }\n.orquesta-embed-panel .border-t { border-top-width: 1px !important; }\n\n/* Padding */\n.orquesta-embed-panel .p-1 { padding: 0.25rem !important; }\n.orquesta-embed-panel .p-2 { padding: 0.5rem !important; }\n.orquesta-embed-panel .p-3 { padding: 0.75rem !important; }\n.orquesta-embed-panel .p-4 { padding: 1rem !important; }\n.orquesta-embed-panel .px-2 { padding-left: 0.5rem !important; padding-right: 0.5rem !important; }\n.orquesta-embed-panel .px-3 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }\n.orquesta-embed-panel .px-4 { padding-left: 1rem !important; padding-right: 1rem !important; }\n.orquesta-embed-panel .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }\n.orquesta-embed-panel .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .py-3 { padding-top: 0.75rem !important; padding-bottom: 0.75rem !important; }\n\n/* Margin */\n.orquesta-embed-panel .m-1 { margin: 0.25rem !important; }\n.orquesta-embed-panel .m-2 { margin: 0.5rem !important; }\n.orquesta-embed-panel .mb-1 { margin-bottom: 0.25rem !important; }\n.orquesta-embed-panel .mb-2 { margin-bottom: 0.5rem !important; }\n.orquesta-embed-panel .mb-4 { margin-bottom: 1rem !important; }\n.orquesta-embed-panel .mt-1 { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .mt-2 { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .mt-3 { margin-top: 0.75rem !important; }\n.orquesta-embed-panel .mt-4 { margin-top: 1rem !important; }\n.orquesta-embed-panel .mr-1 { margin-right: 0.25rem !important; }\n.orquesta-embed-panel .mr-2 { margin-right: 0.5rem !important; }\n.orquesta-embed-panel .mx-1 { margin-left: 0.25rem !important; margin-right: 0.25rem !important; }\n\n/* Gap */\n.orquesta-embed-panel .gap-0\\.5 { gap: 0.125rem !important; }\n.orquesta-embed-panel .gap-1 { gap: 0.25rem !important; }\n.orquesta-embed-panel .gap-1\\.5 { gap: 0.375rem !important; }\n.orquesta-embed-panel .gap-2 { gap: 0.5rem !important; }\n.orquesta-embed-panel .gap-3 { gap: 0.75rem !important; }\n.orquesta-embed-panel .gap-4 { gap: 1rem !important; }\n\n/* Flex */\n.orquesta-embed-panel .flex { display: flex !important; }\n.orquesta-embed-panel .flex-col { flex-direction: column !important; }\n.orquesta-embed-panel .flex-1 { flex: 1 1 0% !important; }\n.orquesta-embed-panel .flex-shrink-0 { flex-shrink: 0 !important; }\n.orquesta-embed-panel .items-center { align-items: center !important; }\n.orquesta-embed-panel .items-start { align-items: flex-start !important; }\n.orquesta-embed-panel .justify-center { justify-content: center !important; }\n.orquesta-embed-panel .justify-between { justify-content: space-between !important; }\n\n/* Width/Height */\n.orquesta-embed-panel .w-full { width: 100% !important; }\n.orquesta-embed-panel .w-2 { width: 0.5rem !important; }\n.orquesta-embed-panel .w-3 { width: 0.75rem !important; }\n.orquesta-embed-panel .w-3\\.5 { width: 0.875rem !important; }\n.orquesta-embed-panel .w-4 { width: 1rem !important; }\n.orquesta-embed-panel .w-5 { width: 1.25rem !important; }\n.orquesta-embed-panel .w-6 { width: 1.5rem !important; }\n.orquesta-embed-panel .w-8 { width: 2rem !important; }\n.orquesta-embed-panel .w-16 { width: 4rem !important; }\n.orquesta-embed-panel .h-2 { height: 0.5rem !important; }\n.orquesta-embed-panel .h-3 { height: 0.75rem !important; }\n.orquesta-embed-panel .h-3\\.5 { height: 0.875rem !important; }\n.orquesta-embed-panel .h-4 { height: 1rem !important; }\n.orquesta-embed-panel .h-5 { height: 1.25rem !important; }\n.orquesta-embed-panel .h-6 { height: 1.5rem !important; }\n.orquesta-embed-panel .h-8 { height: 2rem !important; }\n.orquesta-embed-panel .h-16 { height: 4rem !important; }\n.orquesta-embed-panel .h-full { height: 100% !important; }\n.orquesta-embed-panel .max-w-20 { max-width: 5rem !important; }\n\n/* Font */\n.orquesta-embed-panel .text-xs { font-size: 0.75rem !important; line-height: 1rem !important; }\n.orquesta-embed-panel .text-sm { font-size: 0.875rem !important; line-height: 1.25rem !important; }\n.orquesta-embed-panel .text-lg { font-size: 1.125rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-xl { font-size: 1.25rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-2xl { font-size: 1.5rem !important; line-height: 2rem !important; }\n.orquesta-embed-panel .text-4xl { font-size: 2.25rem !important; line-height: 2.5rem !important; }\n.orquesta-embed-panel .font-medium { font-weight: 500 !important; }\n.orquesta-embed-panel .font-semibold { font-weight: 600 !important; }\n.orquesta-embed-panel .font-bold { font-weight: 700 !important; }\n.orquesta-embed-panel .text-center { text-align: center !important; }\n.orquesta-embed-panel .truncate { overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; }\n\n/* Opacity */\n.orquesta-embed-panel .opacity-25 { opacity: 0.25 !important; }\n.orquesta-embed-panel .opacity-50 { opacity: 0.5 !important; }\n.orquesta-embed-panel .opacity-75 { opacity: 0.75 !important; }\n\n/* Overflow */\n.orquesta-embed-panel .overflow-hidden { overflow: hidden !important; }\n.orquesta-embed-panel .overflow-y-auto { overflow-y: auto !important; }\n\n/* Shadow */\n.orquesta-embed-panel .shadow-xl { box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important; }\n.orquesta-embed-panel .shadow-2xl { box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important; }\n.orquesta-embed-panel .shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important; }\n\n/* Position */\n.orquesta-embed-panel .fixed { position: fixed !important; }\n.orquesta-embed-panel .absolute { position: absolute !important; }\n.orquesta-embed-panel .relative { position: relative !important; }\n.orquesta-embed-panel .top-1 { top: 0.25rem !important; }\n.orquesta-embed-panel .right-1 { right: 0.25rem !important; }\n.orquesta-embed-panel .bottom-0 { bottom: 0 !important; }\n.orquesta-embed-panel .right-0 { right: 0 !important; }\n\n/* Z-index */\n.orquesta-embed-panel .z-\\[2147483647\\] { z-index: 2147483647 !important; }\n\n/* Cursor */\n.orquesta-embed-panel .cursor-move { cursor: move !important; }\n.orquesta-embed-panel .cursor-se-resize { cursor: se-resize !important; }\n.orquesta-embed-panel .cursor-not-allowed { cursor: not-allowed !important; }\n\n/* Select */\n.orquesta-embed-panel .select-none { user-select: none !important; }\n\n/* Disabled states */\n.orquesta-embed-panel .disabled\\:opacity-50:disabled { opacity: 0.5 !important; }\n.orquesta-embed-panel .disabled\\:cursor-not-allowed:disabled { cursor: not-allowed !important; }\n.orquesta-embed-panel .disabled\\:bg-blue-800:disabled { background-color: #1e40af !important; }\n.orquesta-embed-panel .disabled\\:bg-gray-300:disabled { background-color: #d1d5db !important; }\n\n/* Transition */\n.orquesta-embed-panel .transition-colors { transition-property: color, background-color, border-color !important; transition-duration: 150ms !important; }\n.orquesta-embed-panel .transition-all { transition-property: all !important; transition-duration: 150ms !important; }\n\n/* ============================================ */\n/* Action buttons & Comments - Timeline styles */\n/* ============================================ */\n\n/* Purple colors for \"Show on page\" button */\n.orquesta-embed-panel .text-purple-300 { color: #d8b4fe !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-purple-600\\/20 { background-color: rgba(147, 51, 234, 0.2) !important; }\n.orquesta-embed-panel .bg-purple-600\\/30 { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .border-purple-500\\/40 { border-color: rgba(168, 85, 247, 0.4) !important; }\n.orquesta-embed-panel .border-purple-500\\/60 { border-color: rgba(168, 85, 247, 0.6) !important; }\n.orquesta-embed-panel .hover\\:bg-purple-600\\/30:hover { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .hover\\:border-purple-500\\/60:hover { border-color: rgba(168, 85, 247, 0.6) !important; }\n\n/* Zinc with opacity for \"View output\" button */\n.orquesta-embed-panel .bg-zinc-700\\/50 { background-color: rgba(63, 63, 70, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600\\/50 { border-color: rgba(82, 82, 91, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600 { border-color: #52525b !important; }\n.orquesta-embed-panel .border-zinc-500 { border-color: #71717a !important; }\n.orquesta-embed-panel .hover\\:border-zinc-500:hover { border-color: #71717a !important; }\n\n/* Blue with opacity */\n.orquesta-embed-panel .bg-blue-500\\/20 { background-color: rgba(59, 130, 246, 0.2) !important; }\n.orquesta-embed-panel .border-blue-500\\/30 { border-color: rgba(59, 130, 246, 0.3) !important; }\n.orquesta-embed-panel .text-blue-300 { color: #93c5fd !important; }\n.orquesta-embed-panel .text-blue-300\\/70 { color: rgba(147, 197, 253, 0.7) !important; }\n\n/* Additional padding */\n.orquesta-embed-panel .py-1\\.5 { padding-top: 0.375rem !important; padding-bottom: 0.375rem !important; }\n.orquesta-embed-panel .py-0\\.5 { padding-top: 0.125rem !important; padding-bottom: 0.125rem !important; }\n.orquesta-embed-panel .px-1\\.5 { padding-left: 0.375rem !important; padding-right: 0.375rem !important; }\n.orquesta-embed-panel .px-2\\.5 { padding-left: 0.625rem !important; padding-right: 0.625rem !important; }\n.orquesta-embed-panel .pb-2 { padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .pb-3 { padding-bottom: 0.75rem !important; }\n.orquesta-embed-panel .pt-1 { padding-top: 0.25rem !important; }\n\n/* Space utilities */\n.orquesta-embed-panel .space-y-0\\.5 > * + * { margin-top: 0.125rem !important; }\n.orquesta-embed-panel .space-y-1 > * + * { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .space-y-2 > * + * { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .space-y-3 > * + * { margin-top: 0.75rem !important; }\n\n/* Focus states */\n.orquesta-embed-panel .focus\\:outline-none:focus { outline: none !important; }\n.orquesta-embed-panel .focus\\:ring-1:focus { box-shadow: 0 0 0 1px var(--orq-primary, #3b82f6) !important; }\n.orquesta-embed-panel .focus\\:ring-blue-500:focus { --tw-ring-color: #3b82f6 !important; }\n\n/* Placeholder colors */\n.orquesta-embed-panel .placeholder\\:text-zinc-500::placeholder { color: #71717a !important; }\n\n/* Text utilities */\n.orquesta-embed-panel .break-words { word-wrap: break-word !important; overflow-wrap: break-word !important; }\n.orquesta-embed-panel .italic { font-style: italic !important; }\n\n/* Negative margins */\n.orquesta-embed-panel .-mt-1 { margin-top: -0.25rem !important; }\n\n/* Max height */\n.orquesta-embed-panel .max-h-\\[400px\\] { max-height: 400px !important; }\n.orquesta-embed-panel .max-h-\\[150px\\] { max-height: 150px !important; }\n\n/* Font mono */\n.orquesta-embed-panel .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }\n\n/* Text sizes */\n.orquesta-embed-panel .text-\\[10px\\] { font-size: 10px !important; line-height: 1.4 !important; }\n.orquesta-embed-panel .text-\\[11px\\] { font-size: 11px !important; line-height: 1.4 !important; }\n\n/* Flex wrap */\n.orquesta-embed-panel .flex-wrap { flex-wrap: wrap !important; }\n\n/* Min width */\n.orquesta-embed-panel .min-w-0 { min-width: 0 !important; }\n\n/* ml-auto for comment button alignment */\n.orquesta-embed-panel .ml-auto { margin-left: auto !important; }\n\n/* Hidden utility */\n.orquesta-embed-panel .hidden { display: none !important; }\n\n/* SVG icon sizing */\n.orquesta-embed-panel svg { flex-shrink: 0; }\n\n/* Mobile responsive */\n@media (max-width: 480px) {\n .orquesta-embed-panel {\n position: fixed !important;\n left: 8px !important;\n right: 8px !important;\n bottom: 8px !important;\n top: auto !important;\n width: auto !important;\n max-height: 70vh !important;\n }\n}\n\n/* Builder Mode */\n.orquesta-builder{display:flex;flex-direction:column;width:100%;height:100vh;background:#0a0a0a;color:#fafafa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;overflow:hidden}\n.orquesta-builder-header{display:flex;align-items:center;justify-content:space-between;height:48px;padding:0 16px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-header-left{display:flex;align-items:center;gap:12px}\n.orquesta-builder-header-right{display:flex;align-items:center;gap:8px}\n.orquesta-builder-logo{font-weight:700;font-size:14px;color:#fafafa;letter-spacing:-0.02em}\n.orquesta-builder-project{font-size:13px;color:#a1a1aa}\n.orquesta-builder-status{display:flex;align-items:center;gap:6px;font-size:12px;color:#a1a1aa}\n.orquesta-builder-status-dot{width:8px;height:8px;border-radius:50%}\n.orquesta-builder-main{display:flex;flex:1;min-height:0}\n.orquesta-builder-chat{display:flex;flex-direction:column;width:380px;min-width:300px;max-width:50%;border-right:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}\n.orquesta-builder-chat-input{padding:12px 16px;border-top:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-input textarea{width:100%;min-height:60px;max-height:200px;padding:10px 12px;background:#27272a;border:1px solid #3f3f46;border-radius:8px;color:#fafafa;font-size:13px;resize:vertical;outline:none;font-family:inherit}\n.orquesta-builder-chat-input textarea:focus{border-color:#3b82f6}\n.orquesta-builder-chat-input-actions{display:flex;justify-content:space-between;align-items:center;margin-top:8px}\n.orquesta-builder-preview{flex:1;display:flex;flex-direction:column;min-width:0}\n.orquesta-builder-preview-bar{display:flex;align-items:center;height:36px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;gap:8px;flex-shrink:0}\n.orquesta-builder-preview-url{flex:1;padding:4px 10px;background:#27272a;border:1px solid #3f3f46;border-radius:6px;color:#a1a1aa;font-size:12px;font-family:'SF Mono','Fira Code',monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.orquesta-builder-preview-iframe{flex:1;width:100%;border:none;background:#fff}\n.orquesta-builder-terminal{height:200px;min-height:100px;max-height:50vh;border-top:1px solid #27272a;background:#0a0a0a;display:flex;flex-direction:column;flex-shrink:0}\n.orquesta-builder-terminal-header{display:flex;align-items:center;justify-content:space-between;height:32px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-terminal-title{font-size:12px;font-weight:600;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.05em}\n.orquesta-builder-terminal-output{flex:1;overflow-y:auto;padding:8px 12px;font-family:'SF Mono','Fira Code','Cascadia Code',monospace;font-size:12px;line-height:1.5}\n.orquesta-builder-terminal.collapsed{height:32px;min-height:32px}\n.orquesta-builder-terminal.collapsed .orquesta-builder-terminal-output{display:none}\n.orquesta-builder-msg{max-width:90%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}\n.orquesta-builder-msg-user{align-self:flex-end;background:#3b82f6;color:#fff;border-bottom-right-radius:4px}\n.orquesta-builder-msg-system{align-self:flex-start;background:#27272a;color:#fafafa;border-bottom-left-radius:4px}\n.orquesta-builder-msg-status{align-self:center;background:transparent;color:#71717a;font-size:12px;padding:4px 0}\n.orquesta-builder-resizer-h{width:4px;cursor:col-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-h:hover{background:#3b82f6}\n.orquesta-builder-resizer-v{height:4px;cursor:row-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-v:hover{background:#3b82f6}\n.orquesta-builder button{background:transparent;border:none;color:#a1a1aa;cursor:pointer;padding:4px 8px;border-radius:4px;font-size:12px}\n.orquesta-builder button:hover{background:#27272a;color:#fafafa}\n.orquesta-builder-btn-primary{background:#3b82f6!important;color:#fff!important;font-weight:500;padding:6px 16px!important;border-radius:6px!important}\n.orquesta-builder-btn-primary:hover{background:#2563eb!important}\n.orquesta-builder-btn-primary:disabled{opacity:0.5;cursor:not-allowed}\n@media(max-width:768px){.orquesta-builder-main{flex-direction:column}.orquesta-builder-chat{width:100%;max-width:100%;height:50%;border-right:none;border-bottom:1px solid #27272a}.orquesta-builder-resizer-h{display:none}}\n","orquesta-embed-styles"),this.elements.container.id="orquesta-widget-container",document.body.appendChild(this.elements.container),!1!==t.enableGlobalRightClick&&this.setupGlobalRightClick()}setupGlobalRightClick(){this.globalRightClickCleanup=this.client.setupGlobalRightClickWithPosition((t,e)=>{this.client.getElementSelector().deactivate(),this.client.getElementSelector().highlightSelectedElement(t.selector),this.contextMenuState={isOpen:!0,position:e,element:t},this.render()})}async init(){console.log("[Orquesta Embed] v0.2.1"),this.unsubscribe=this.client.subscribe(t=>{this.state=t,this.render()});try{await this.client.connect()}catch(t){throw this.renderError(t instanceof Error?t.message:"Connection failed"),t}}render(){this.state&&("builder"!==this.currentMode?(this.elements.container.innerHTML="",this.cleanupFunctions.forEach(t=>t()),this.cleanupFunctions=[],"completed"!==this.state.currentPrompt?.status&&"failed"!==this.state.currentPrompt?.status||(this.lastCompletedPrompt=this.state.currentPrompt),this.showStatusBar&&this.renderStatusBar(),this.state.isOpen&&!this.isMinimized||this.renderTrigger(),this.state.isOpen&&!this.isMinimized&&this.renderPanel(),this.state.isSelectingElement&&this.renderElementInspector(),this.contextMenuState.isOpen&&this.renderContextMenu(),"all"===this.state.overlayMode&&this.state.elementMarkers.length>0&&this.renderElementMarkers()):this.renderBuilder())}renderTrigger(){const t=this.config.position||"bottom-right",[e,n]=t.split("-"),i=Lt("button",{className:"orquesta-embed-trigger"},["⬡"]);if(Ht(i,{position:"fixed",zIndex:"2147483647",padding:"12px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"50%",boxShadow:"0 10px 25px rgba(0,0,0,0.3)",cursor:"pointer",fontSize:"20px",["top"===e?"top":"bottom"]:"20px",["left"===n?"left":"right"]:"20px"}),this.state?.agentOnline){const t=Lt("span");Ht(t,{position:"absolute",top:"4px",right:"4px",width:"8px",height:"8px",background:"#22c55e",borderRadius:"50%"}),i.appendChild(t)}const s=Mt(i,"click",()=>{this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(s),this.elements.container.appendChild(i),this.elements.trigger=i}renderPanel(){if(!this.state)return;const t=Lt("div",{className:"orquesta-embed-panel"});Ht(t,{position:"fixed",zIndex:"2147483647",width:"400px",height:"500px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 25px 50px rgba(0,0,0,0.5)",display:"flex",flexDirection:"column",overflow:"hidden",right:"20px",bottom:"20px"});const e=this.createHeader();t.appendChild(e);const n=this.createTabs();if(t.appendChild(n),this.state?.connectionError){const e=Lt("div");Ht(e,{margin:"8px 12px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid rgba(239, 68, 68, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const n=Lt("span",{},["⚠️"]);Ht(n,{fontSize:"12px"});const i=Lt("span",{},[this.state.connectionError]);Ht(i,{fontSize:"11px",color:"#fca5a5"}),e.appendChild(n),e.appendChild(i),t.appendChild(e)}if(!this.state?.isConnected&&!this.state?.connectionError){const e=Lt("div");Ht(e,{margin:"8px 12px",padding:"8px 12px",background:"rgba(113, 63, 18, 0.3)",border:"1px solid rgba(234, 179, 8, 0.3)",borderRadius:"8px",display:"flex",alignItems:"center",gap:"8px"});const n=Lt("span",{},["ℹ️"]);Ht(n,{fontSize:"12px"});const i=Lt("span",{},["Reconnecting to Orquesta..."]);Ht(i,{fontSize:"11px",color:"#fcd34d"}),e.appendChild(n),e.appendChild(i),t.appendChild(e)}const i=Lt("div");if(Ht(i,{flex:"1",overflowY:"auto",padding:"12px"}),this.state?.requireAuth&&!this.state?.isAuthenticated){const t=this.createAuthOverlay();i.appendChild(t)}else{const t=this.createContent();i.appendChild(t)}t.appendChild(i),this.elements.container.appendChild(t),this.elements.panel=t}createAuthOverlay(){const t=Lt("div");Ht(t,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",textAlign:"center",padding:"16px"});const e=Lt("div");Ht(e,{width:"64px",height:"64px",borderRadius:"50%",background:"#27272a",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:"16px"});const n=Lt("span",{},["🔒"]);Ht(n,{fontSize:"28px"}),e.appendChild(n),t.appendChild(e);const i=Lt("h3",{},["Sign in to continue"]);Ht(i,{color:"white",fontWeight:"600",margin:"0 0 8px 0",fontSize:"16px"}),t.appendChild(i);const s=Lt("p",{},["You need to sign in to submit prompts to this project."]);if(Ht(s,{color:"#a1a1aa",fontSize:"13px",margin:"0 0 16px 0"}),t.appendChild(s),this.state?.authError){const e=Lt("div",{},[this.state.authError]);Ht(e,{marginBottom:"16px",padding:"8px 12px",background:"rgba(127, 29, 29, 0.3)",border:"1px solid #7f1d1d",borderRadius:"6px",color:"#fca5a5",fontSize:"12px"}),t.appendChild(e)}const o=Lt("button");if(Ht(o,{display:"flex",alignItems:"center",gap:"8px",padding:"10px 20px",background:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"500",fontSize:"14px",color:"#374151"}),this.state?.isAuthenticating){const t=Lt("span",{},["⏳"]),e=Lt("span",{},["Signing in..."]);o.appendChild(t),o.appendChild(e),o.style.opacity="0.7"}else{const t=Lt("span",{},["G"]);Ht(t,{fontWeight:"bold",color:"#4285f4"});const e=Lt("span",{},["Continue with Google"]);o.appendChild(t),o.appendChild(e)}const r=Mt(o,"click",()=>{this.state?.isAuthenticating||this.client.login()});this.cleanupFunctions.push(r),t.appendChild(o);const a=Lt("p",{},["You must be a member of this project's organization."]);return Ht(a,{color:"#71717a",fontSize:"11px",marginTop:"16px"}),t.appendChild(a),t}createHeader(){const t=Lt("div");Ht(t,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",background:"#27272a",borderBottom:"1px solid #3f3f46",cursor:"move"});const e=Lt("div");Ht(e,{display:"flex",alignItems:"center",gap:"8px"});const n=Lt("span",{},["⬡"]);Ht(n,{fontSize:"16px"});const i=Lt("span",{},["Orquesta"]);if(Ht(i,{fontWeight:"600",color:"white",fontSize:"14px"}),e.appendChild(n),e.appendChild(i),this.state?.projectName){const t=Lt("span",{},[`• ${this.state.projectName}`]);Ht(t,{fontSize:"12px",color:"#a1a1aa"}),e.appendChild(t)}const s=Lt("div");if(Ht(s,{display:"flex",alignItems:"center",gap:"4px"}),this.state?.requireAuth)if(this.state.isAuthenticated&&this.state.user){const t=Lt("div");if(Ht(t,{display:"flex",alignItems:"center",gap:"6px",marginRight:"8px"}),this.state.user.avatar_url){const e=Lt("img",{src:this.state.user.avatar_url});Ht(e,{width:"20px",height:"20px",borderRadius:"50%"}),t.appendChild(e)}else{const e=Lt("div",{},[this.state.user.full_name?.[0]?.toUpperCase()||"?"]);Ht(e,{width:"20px",height:"20px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",color:"white"}),t.appendChild(e)}const e=Lt("span",{},[this.state.user.full_name||"User"]);Ht(e,{fontSize:"12px",color:"#d4d4d8",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),t.appendChild(e);const n=Lt("button",{},["↪"]);Ht(n,{padding:"4px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"12px"});const i=Mt(n,"click",()=>this.client.logout());this.cleanupFunctions.push(i),t.appendChild(n),s.appendChild(t)}else{const t=Lt("button",{},[this.state?.isAuthenticating?"...":"Sign in"]);Ht(t,{padding:"4px 8px",marginRight:"8px",background:"#2563eb",border:"none",borderRadius:"4px",color:"white",cursor:"pointer",fontSize:"11px"});const e=Mt(t,"click",()=>this.client.login());this.cleanupFunctions.push(e),s.appendChild(t)}const o=Lt("span");Ht(o,{width:"8px",height:"8px",borderRadius:"50%",marginRight:"4px",background:this.state?.isConnected?this.state?.agentOnline?"#22c55e":"#71717a":"#ef4444"}),o.title=this.state?.isConnected?this.state?.agentOnline?"Agent online":"Agent offline":"Not connected",s.appendChild(o);const r=Lt("button",{},["🎯"]);Ht(r,{padding:"4px",background:this.state?.rightClickEnabled?"#16a34a":"#3f3f46",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px"}),r.title=this.state?.rightClickEnabled?"Right-click enabled":"Right-click disabled";const a=Mt(r,"click",()=>{if(this.state){const t=!this.state.rightClickEnabled;this.state.rightClickEnabled=t,t?this.globalRightClickCleanup||this.setupGlobalRightClick():this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.render()}});this.cleanupFunctions.push(a),s.appendChild(r);const l=Lt("div");Ht(l,{display:"flex",gap:"2px",margin:"0 4px",padding:"2px",background:"#27272a",borderRadius:"4px"});[{mode:"off",icon:"👁️🗨️",title:"Overlay off"},{mode:"single",icon:"👁️",title:"Show selected prompt"},{mode:"all",icon:"📍",title:"Show all prompts"}].forEach(({mode:t,icon:e,title:n})=>{const i=Lt("button",{},[e]),s=this.state?.overlayMode===t;Ht(i,{padding:"4px",background:s?"off"===t?"#3f3f46":"single"===t?"#2563eb":"#7c3aed":"transparent",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"10px",opacity:s?"1":"0.5"}),i.title=n;const o=Mt(i,"click",()=>{this.state&&(this.state.overlayMode=t,"all"===t?this.state.elementMarkers=this.state.promptHistory.filter(t=>t.element_context?.selector).map(t=>{let e=null;try{e=document.querySelector(t.element_context.selector)}catch{}return{promptId:t.id,selector:t.element_context.selector,rect:e?.getBoundingClientRect()||null,content:t.content,author:t.author||null,gitCommitSha:t.git_commit_sha||null,commentCount:t.comment_count||0}}):"off"===t&&(this.state.elementMarkers=[],this.state.highlightedPromptId=null,this.client.getElementSelector().removeHighlight()),this.render())});this.cleanupFunctions.push(o),l.appendChild(i)}),s.appendChild(l);const c=this.createIconButton("⛶",()=>{this.switchMode("builder")});c.title="Expand to builder mode",s.appendChild(c);const p=this.createIconButton("−",()=>{this.isMinimized=!0,this.render()});s.appendChild(p);const d=this.createIconButton("×",()=>{this.client.close()});return s.appendChild(d),t.appendChild(e),t.appendChild(s),t}createIconButton(t,e){const n=Lt("button",{},[t]);Ht(n,{padding:"4px 8px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",borderRadius:"4px",fontSize:"16px"});const i=Mt(n,"click",e);this.cleanupFunctions.push(i);const s=Mt(n,"mouseenter",()=>{Ht(n,{background:"#3f3f46",color:"white"})}),o=Mt(n,"mouseleave",()=>{Ht(n,{background:"transparent",color:"#a1a1aa"})});return this.cleanupFunctions.push(s,o),n}createTabs(){const t=Lt("div");Ht(t,{padding:"8px 12px",borderBottom:"1px solid #27272a"});const e=Lt("div");Ht(e,{display:"flex",gap:"4px",padding:"4px",background:"#27272a",borderRadius:"8px"});return["prompts","timeline","logs"].forEach(t=>{const n=this.state?.activeTab===t,i=Lt("button",{},[t.charAt(0).toUpperCase()+t.slice(1)]);Ht(i,{flex:"1",padding:"6px 12px",background:n?"#3f3f46":"transparent",border:"none",borderRadius:"6px",color:n?"white":"#a1a1aa",cursor:"pointer",fontSize:"13px",fontWeight:"500"});const s=Mt(i,"click",()=>{this.state&&(this.state.activeTab=t,this.render())});this.cleanupFunctions.push(s),e.appendChild(i)}),t.appendChild(e),t}createContent(){const t=Lt("div");switch(this.state?.activeTab){case"prompts":t.appendChild(this.createPromptsTab());break;case"timeline":t.appendChild(this.createTimelineTab());break;case"logs":t.appendChild(this.createLogsTab())}return t}createPromptsTab(){const t=Lt("div"),e=async()=>{const t=this.elements.promptInput?.value.trim();if(t&&this.state?.agentOnline&&!this.state?.isSubmitting)try{const e=this.state?.selectedElement?{elementContext:this.state.selectedElement}:void 0;await this.client.submitPrompt(t,e),this.elements.promptInput&&(this.elements.promptInput.value=""),this.state&&(this.state.selectedElement=null,this.render())}catch(t){console.error("Failed to submit prompt:",t)}},n=Lt("textarea",{placeholder:this.state?.agentOnline?"What would you like to do?":"Agent is offline..."});Ht(n,{width:"100%",minHeight:"80px",padding:"8px 12px",background:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"white",fontSize:"14px",resize:"none",outline:"none"}),n.disabled=!this.state?.agentOnline||this.state?.isSubmitting,this.elements.promptInput=n,t.appendChild(n);const i=Mt(n,"keydown",t=>{const n=t;"Enter"===n.key&&(n.metaKey||n.ctrlKey)&&(n.preventDefault(),e())});this.cleanupFunctions.push(i);const s=Lt("div");if(Ht(s,{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"}),this.state?.selectedElement){const t=this.createContextBadge("🎯",`<${this.state.selectedElement.tag}>${this.state.selectedElement.textContent?": "+this.state.selectedElement.textContent.slice(0,20)+(this.state.selectedElement.textContent.length>20?"...":""):""}`,"#1e3a5f","#3b82f6","#93c5fd",()=>{this.state&&(this.state.selectedElement=null,this.render())});s.appendChild(t)}if(this.state?.includeConsole){const t=this.createContextBadge("📋","Console logs","#422006","#eab308","#fcd34d",()=>{this.state&&(this.state.includeConsole=!1,this.render())});s.appendChild(t)}if(this.state?.includeNetwork){const t=this.createContextBadge("🌐","Network errors","#450a0a","#ef4444","#fca5a5",()=>{this.state&&(this.state.includeNetwork=!1,this.render())});s.appendChild(t)}if(this.state?.includeContext){const t=this.createContextBadge("🔗","Session outputs","#3b0764","#a855f7","#d8b4fe",()=>{this.state&&(this.state.includeContext=!1,this.render())});s.appendChild(t)}s.childNodes.length>0&&t.appendChild(s);const o=Lt("div");Ht(o,{display:"flex",gap:"8px",marginTop:"8px"});const r=this.createContextButton(this.state?.selectedElement?"🎯 Element ✓":"🎯 Element",()=>{this.client.startElementSelection()},!!this.state?.selectedElement),a=this.createContextButton("📋 Logs",()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())},this.state?.includeConsole),l=this.createContextButton("🌐 Network",()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())},this.state?.includeNetwork),c=this.createContextButton("🔗 Context",()=>{this.state&&(this.state.includeContext=!this.state.includeContext,this.render())},this.state?.includeContext);o.appendChild(r),o.appendChild(a),o.appendChild(l),o.appendChild(c),t.appendChild(o);const p=Lt("div");Ht(p,{display:"flex",justifyContent:"flex-end",marginTop:"12px"});const d=Lt("button",{},[this.state?.isSubmitting?"Running...":"Submit (⌘↵)"]);Ht(d,{padding:"8px 16px",background:"#3b82f6",border:"none",borderRadius:"6px",color:"white",cursor:"pointer",fontWeight:"500",opacity:!this.state?.agentOnline||this.state?.isSubmitting?"0.5":"1"});const h=Mt(d,"click",e);if(this.cleanupFunctions.push(h),p.appendChild(d),t.appendChild(p),this.state?.outputLines.length||this.state?.isSubmitting){const e=Lt("div");Ht(e,{marginTop:"16px",paddingTop:"16px",borderTop:"1px solid #27272a"});const n=this.createLogStream(this.state?.outputLines||[]);e.appendChild(n),t.appendChild(e)}return t}createContextButton(t,e,n){const i=Lt("button",{},[t]);Ht(i,{padding:"4px 8px",background:n?"#3f3f46":"transparent",border:"none",borderRadius:"4px",color:n?"white":"#a1a1aa",cursor:"pointer",fontSize:"12px"});const s=Mt(i,"click",e);return this.cleanupFunctions.push(s),i}createContextBadge(t,e,n,i,s,o){const r=Lt("div");Ht(r,{display:"flex",alignItems:"center",gap:"6px",padding:"4px 8px",background:n,border:`1px solid ${i}`,borderRadius:"6px",fontSize:"11px",color:s});const a=Lt("span",{},[t]),l=Lt("span",{},[e]),c=Lt("button",{},["×"]);Ht(c,{marginLeft:"4px",background:"none",border:"none",color:s,cursor:"pointer",fontSize:"14px",padding:"0",lineHeight:"1"});const p=Mt(c,"click",o);return this.cleanupFunctions.push(p),r.appendChild(a),r.appendChild(l),r.appendChild(c),r}createLogStream(t){const e=Lt("div",{className:"orquesta-log-stream"});if(Ht(e,{maxHeight:"200px",overflowY:"auto",background:"#0a0a0a",border:"1px solid #27272a",borderRadius:"6px",padding:"8px",fontFamily:"monospace",fontSize:"11px"}),this.state?.isSubmitting){const t=Lt("div");Ht(t,{color:"#3b82f6",padding:"4px 0",marginBottom:"4px"}),t.textContent="● Running...",e.appendChild(t)}return[...t].reverse().forEach(t=>{const n=Lt("div");Ht(n,{display:"flex",gap:"8px",padding:"2px 0",color:"stderr"===t.type?"#ef4444":"tool"===t.type?"#3b82f6":"#d4d4d8"});const i=Lt("span",{},["stderr"===t.type?"✕":"tool"===t.type?"🔧":"›"]);Ht(i,{opacity:"0.5",width:"16px",textAlign:"center"});const s=Lt("span",{},[t.content]);Ht(s,{flex:"1",wordBreak:"break-all",whiteSpace:"pre-wrap"}),n.appendChild(i),n.appendChild(s),e.appendChild(n)}),this.elements.logStream=e,e}createTimelineTab(){const t=Lt("div");if(Ht(t,{maxHeight:"400px",overflowY:"auto"}),!this.state?.promptHistory.length){const e=Lt("div",{},["No prompts yet. Right-click any element to start!"]);return Ht(e,{textAlign:"center",padding:"32px",color:"#71717a",fontSize:"14px"}),t.appendChild(e),t}return this.state.promptHistory.forEach(e=>{const n=e.id===this.state?.currentPrompt?.id,i=e.id===this.state?.expandedPromptId,s=Lt("div");Ht(s,{marginBottom:"8px",background:n?"#27272a":"#18181b",border:"1px solid "+(n?"#3b82f6":"#3f3f46"),borderRadius:"8px",transition:"border-color 0.2s"});const o=Lt("div");Ht(o,{display:"flex",alignItems:"flex-start",gap:"10px",padding:"12px",cursor:"pointer"});const r=Lt("div"),a=e.author?.full_name||"Unknown",l=a[0]?.toUpperCase()||"?";if(e.author?.avatar_url){const t=Lt("img",{src:e.author.avatar_url});Ht(t,{width:"28px",height:"28px",borderRadius:"50%"}),r.appendChild(t)}else Ht(r,{width:"28px",height:"28px",borderRadius:"50%",background:"#52525b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:"600",color:"white"}),r.textContent=l;const c=Lt("div");Ht(c,{flex:"1",minWidth:"0"});const p=Lt("div");Ht(p,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"});const d=Lt("span",{},[a]);Ht(d,{fontSize:"12px",fontWeight:"500",color:"#d4d4d8"});const h=Lt("span",{},[this.formatDate(e.created_at)]);Ht(h,{fontSize:"10px",color:"#71717a"}),p.appendChild(d),p.appendChild(h);const u=Lt("p",{},[e.content.slice(0,100)+(e.content.length>100?"...":"")]);Ht(u,{color:"#e4e4e7",fontSize:"13px",margin:"0 0 8px 0",lineHeight:"1.4"});const m=Lt("div");if(Ht(m,{display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"}),e.git_commit_sha){const t=Lt("span",{},[`🔗 ${e.git_commit_sha.slice(0,7)}`]);Ht(t,{padding:"2px 6px",background:"#1e3a5f",border:"1px solid #3b82f6",borderRadius:"4px",fontSize:"10px",color:"#93c5fd",fontFamily:"monospace"}),m.appendChild(t)}if(e.element_context){const t=Lt("span",{},[`🎯 <${e.element_context.tag}>`]);Ht(t,{padding:"2px 6px",background:"rgba(59, 130, 246, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",borderRadius:"4px",fontSize:"10px",color:"#60a5fa"}),m.appendChild(t)}if((e.comment_count||0)>0){const t=Lt("span",{},[`💬 ${e.comment_count}`]);Ht(t,{padding:"2px 6px",background:"#27272a",borderRadius:"4px",fontSize:"10px",color:"#a1a1aa"}),m.appendChild(t)}c.appendChild(p),c.appendChild(u),c.appendChild(m);const g=Lt("div");Ht(g,{display:"flex",alignItems:"center",gap:"6px",flexShrink:"0"});const f=Lt("span");Ht(f,{width:"8px",height:"8px",borderRadius:"50%",background:"completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"running"===e.status?"#3b82f6":"#71717a"});const b=Lt("span",{},[e.status]);Ht(b,{padding:"2px 8px",background:"completed"===e.status?"#14532d":"failed"===e.status?"#7f1d1d":"running"===e.status?"#1e3a5f":"#27272a",color:"completed"===e.status?"#4ade80":"failed"===e.status?"#f87171":"running"===e.status?"#60a5fa":"#a1a1aa",borderRadius:"9999px",fontSize:"10px",fontWeight:"500"}),g.appendChild(f),g.appendChild(b),o.appendChild(r),o.appendChild(c),o.appendChild(g),s.appendChild(o);const x="completed"===e.status||"failed"===e.status||e.element_context,y=Lt("div");if(Ht(y,{display:x?"flex":"none",alignItems:"center",gap:"8px",padding:"0 12px 10px 50px"}),e.element_context){const t=Lt("button",{},["👁 Show on page"]);Ht(t,{padding:"4px 10px",background:"rgba(124, 58, 237, 0.2)",border:"1px solid rgba(124, 58, 237, 0.4)",borderRadius:"6px",color:"#c4b5fd",fontSize:"11px",cursor:"pointer"});const n=Mt(t,"click",t=>{if(t.stopPropagation(),e.element_context){this.client.getElementSelector().highlightSelectedElement(e.element_context.selector);try{const t=document.querySelector(e.element_context.selector);t?.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}});this.cleanupFunctions.push(n),y.appendChild(t)}if("completed"===e.status||"failed"===e.status){const t=Lt("button",{},[i?"📄 Hide output":"📄 View output"]);Ht(t,{padding:"4px 10px",background:i?"#3f3f46":"rgba(63, 63, 70, 0.5)",border:"1px solid rgba(63, 63, 70, 0.5)",borderRadius:"6px",color:i?"white":"#d4d4d8",fontSize:"11px",cursor:"pointer"});const n=Mt(t,"click",t=>{t.stopPropagation(),this.state&&(this.state.expandedPromptId=i?null:e.id,this.render())});this.cleanupFunctions.push(n),y.appendChild(t)}if(s.appendChild(y),i){const t=Lt("div");Ht(t,{padding:"0 12px 12px 12px",borderTop:"1px solid #27272a",marginTop:"4px"});const n=Lt("div");Ht(n,{marginTop:"8px",background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"});const i=this.state?.promptOutputs?.[e.id]||[];if(i.length>0)i.slice(-20).forEach(t=>{const e=Lt("div",{},[t.content]);Ht(e,{color:"stderr"===t.type?"#ef4444":"tool"===t.type?"#3b82f6":"thinking"===t.type?"#71717a":"#d4d4d8",padding:"1px 0",fontStyle:"thinking"===t.type?"italic":"normal"}),n.appendChild(e)});else{const t=Lt("div",{},["No output recorded for this prompt"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),n.appendChild(t)}t.appendChild(n),s.appendChild(t)}const w=Mt(s,"mouseenter",()=>{n||Ht(s,{borderColor:"#52525b"})}),C=Mt(s,"mouseleave",()=>{n||Ht(s,{borderColor:"#3f3f46"})});this.cleanupFunctions.push(w,C);const v=Mt(o,"click",()=>{this.state&&e.element_context&&this.client.getElementSelector().highlightSelectedElement(e.element_context.selector)});this.cleanupFunctions.push(v),t.appendChild(s)}),t}createLogsTab(){const t=Lt("div"),e=Lt("div");Ht(e,{marginBottom:"16px"});const n=Lt("div");Ht(n,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const i=Lt("h3",{},["Agent Output"]);if(Ht(i,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"}),this.state?.isSubmitting){const t=Lt("span",{},["Running..."]);Ht(t,{fontSize:"11px",color:"#4ade80"}),n.appendChild(i),n.appendChild(t)}else n.appendChild(i);e.appendChild(n);const s=Lt("div");if(Ht(s,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"150px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.outputLines.length)this.state.outputLines.slice(-30).forEach(t=>{const e=Lt("div",{},[t.content]);Ht(e,{color:"stderr"===t.type?"#ef4444":"tool"===t.type?"#3b82f6":"#d4d4d8",padding:"1px 0",wordBreak:"break-all"}),s.appendChild(e)});else{const t=Lt("div",{},["No agent output yet"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),s.appendChild(t)}e.appendChild(s),t.appendChild(e);const o=Lt("div");Ht(o,{marginBottom:"16px"});const r=Lt("div");Ht(r,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const a=Lt("h3",{},["Console Logs"]);Ht(a,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const l=Lt("span",{},[`${this.state?.consoleLogs.length||0} entries`]);Ht(l,{fontSize:"11px",color:"#71717a"}),r.appendChild(a),r.appendChild(l),o.appendChild(r);const c=Lt("div");if(Ht(c,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.consoleLogs.length)this.state.consoleLogs.slice(-20).forEach(t=>{const e=Lt("div");Ht(e,{color:"error"===t.level?"#ef4444":"warn"===t.level?"#eab308":"#d4d4d8",padding:"1px 0"}),e.textContent=`[${t.level}] ${t.message}`,c.appendChild(e)});else{const t=Lt("div",{},["No console logs captured"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),c.appendChild(t)}o.appendChild(c),t.appendChild(o);const p=Lt("div"),d=Lt("div");Ht(d,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"});const h=Lt("h3",{},["Network Requests"]);Ht(h,{fontSize:"13px",fontWeight:"500",color:"#d4d4d8",margin:"0"});const u=Lt("span",{},[`${this.state?.networkLogs.length||0} requests`]);Ht(u,{fontSize:"11px",color:"#71717a"}),d.appendChild(h),d.appendChild(u),p.appendChild(d);const m=Lt("div");if(Ht(m,{background:"#0a0a0a",borderRadius:"6px",padding:"8px",maxHeight:"120px",overflowY:"auto",fontFamily:"monospace",fontSize:"11px"}),this.state?.networkLogs.length)this.state.networkLogs.slice(-15).forEach(t=>{const e=Lt("div");Ht(e,{display:"flex",gap:"8px",padding:"2px 0"});const n=Lt("span",{},[String(t.status||"...")]);Ht(n,{color:t.status&&t.status>=400?"#ef4444":t.status&&t.status>=300?"#eab308":"#4ade80"});const i=Lt("span",{},[t.method]);Ht(i,{color:"#a1a1aa"});const s=Lt("span",{},[t.url]);if(Ht(s,{color:"#d4d4d8",flex:"1",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),e.appendChild(n),e.appendChild(i),e.appendChild(s),t.duration){const n=Lt("span",{},[`${t.duration}ms`]);Ht(n,{color:"#71717a"}),e.appendChild(n)}m.appendChild(e)});else{const t=Lt("div",{},["No network requests captured"]);Ht(t,{color:"#71717a",textAlign:"center",padding:"8px"}),m.appendChild(t)}return p.appendChild(m),t.appendChild(p),t}renderElementInspector(){const t=Lt("div",{className:"orquesta-element-inspector"});Ht(t,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"});const e=Lt("div");Ht(e,{position:"absolute",top:"16px",left:"50%",transform:"translateX(-50%)",pointerEvents:"auto",display:"flex",alignItems:"center",gap:"12px",padding:"8px 16px",background:"#18181b",border:"1px solid #3f3f46",borderRadius:"8px",boxShadow:"0 10px 25px rgba(0,0,0,0.3)"});const n=Lt("span",{},["Click on any element to select it, or right-click for options"]);Ht(n,{fontSize:"13px",color:"#d4d4d8"});const i=Lt("button",{},["Cancel (Esc)"]);Ht(i,{padding:"4px 12px",background:"transparent",border:"none",color:"#a1a1aa",cursor:"pointer",fontSize:"13px"});const s=Mt(i,"click",()=>{this.client.getElementSelector().deactivate()});this.cleanupFunctions.push(s),e.appendChild(n),e.appendChild(i),t.appendChild(e),this.elements.container.appendChild(t)}renderStatusBar(){if(!this.state)return;let t="idle";this.state.isConnected?this.state.agentOnline?this.state.isSubmitting||"running"===this.state.currentPrompt?.status?t="running":"completed"===this.state.currentPrompt?.status?t="completed":"failed"===this.state.currentPrompt?.status&&(t="failed"):t="offline":t="connecting";const e=(()=>{switch(t){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${this.state?.currentPrompt?.content.slice(0,50)}${(this.state?.currentPrompt?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(this.state?.currentPrompt?.git_commit_sha?` • Commit ${this.state.currentPrompt.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:this.state?.projectName?`${this.state.projectName} • Ready`:"Orquesta Ready",pulse:!1}}})();if(this.statusBarMinimized){const n=Lt("div",{id:"orquesta-status-bar-minimized"});Ht(n,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:e.bg,border:`1px solid ${e.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const i=Lt("span");Ht(i,{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===t?"#22c55e":"failed"===t?"#ef4444":"running"===t?"#3b82f6":"#71717a"});const s=Lt("span",{},["Orquesta"]);Ht(s,{fontSize:"11px",color:"#d4d4d8",fontWeight:"500"}),n.appendChild(i),n.appendChild(s);const o=Mt(n,"click",()=>{this.statusBarMinimized=!1,this.render()});return this.cleanupFunctions.push(o),this.elements.container.appendChild(n),void(this.elements.statusBarMinimized=n)}const n=Lt("div",{id:"orquesta-status-bar"});Ht(n,{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483646",display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:e.bg,border:`1px solid ${e.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)"});const i=Lt("div");Ht(i,{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:e.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:"0"});const s=Lt("span",{},[e.icon]);Ht(s,{fontSize:"14px",color:"#ffffff"}),i.appendChild(s);const o=Lt("div");Ht(o,{flex:"1",minWidth:"0"});const r=Lt("div",{},[e.text]);if(Ht(r,{fontSize:"12px",fontWeight:"500",color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"}),o.appendChild(r),"running"===t){const t=Lt("div");Ht(t,{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"});const e=Lt("div");Ht(e,{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",width:"30%",animation:"orquesta-progress 2s ease-in-out infinite"}),t.appendChild(e),o.appendChild(t)}const a=Lt("button",{},["−"]);Ht(a,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const l=Mt(a,"click",()=>{this.statusBarMinimized=!0,this.render()});this.cleanupFunctions.push(l);const c=Lt("button",{},["×"]);Ht(c,{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",fontSize:"16px",flexShrink:"0"});const p=Mt(c,"click",()=>{this.showStatusBar=!1,this.render()});this.cleanupFunctions.push(p),n.appendChild(i),n.appendChild(o),n.appendChild(a),n.appendChild(c);const d=Lt("style");d.textContent="\n @keyframes orquesta-progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n ",n.appendChild(d),this.elements.container.appendChild(n),this.elements.statusBar=n,"completed"!==t&&"failed"!==t||setTimeout(()=>{this.showStatusBar&&!this.statusBarMinimized&&(this.statusBarMinimized=!0,this.render())},5e3)}renderContextMenu(){if(!this.contextMenuState.isOpen||!this.contextMenuState.element)return;const t=Lt("div",{className:"orquesta-context-menu"});Ht(t,{position:"fixed",zIndex:"2147483648",left:`${this.contextMenuState.position.x}px`,top:`${this.contextMenuState.position.y}px`,width:"320px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"12px",boxShadow:"0 25px 50px rgba(0, 0, 0, 0.5)",overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const e=Lt("div");Ht(e,{padding:"12px",borderBottom:"1px solid #27272a",backgroundColor:"#27272a"});const n=Lt("div");Ht(n,{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"});const i=Lt("span",{},["🎯"]),s=Lt("span",{},["Prompt about element"]);Ht(s,{fontWeight:"600",color:"white",fontSize:"14px"}),n.appendChild(i),n.appendChild(s);const o=Lt("div");Ht(o,{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#3f3f46",borderRadius:"4px",fontSize:"11px",fontFamily:"ui-monospace, monospace",color:"#a1a1aa"});const r=Lt("span",{},[`<${this.contextMenuState.element.tag}>`]);if(Ht(r,{color:"#60a5fa"}),o.appendChild(r),this.contextMenuState.element.className){const t=Lt("span",{},[`.${this.contextMenuState.element.className.split(" ")[0]}`]);Ht(t,{color:"#4ade80"}),o.appendChild(t)}e.appendChild(n),e.appendChild(o);const a=Lt("div");Ht(a,{padding:"12px"});const l=Lt("textarea",{placeholder:"What would you like to do with this element?"});Ht(l,{width:"100%",minHeight:"80px",padding:"10px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"8px",color:"white",fontSize:"14px",resize:"none",outline:"none",marginBottom:"12px"});const c=Lt("div");Ht(c,{display:"flex",gap:"8px",marginBottom:"12px"});const p=(t,e,n)=>{const i=Lt("button",{},[t]);Ht(i,{flex:"1",padding:"6px 10px",backgroundColor:e?"#3f3f46":"transparent",border:"1px solid #3f3f46",borderRadius:"6px",color:e?"white":"#a1a1aa",fontSize:"12px",cursor:"pointer"});const s=Mt(i,"click",n);return this.cleanupFunctions.push(s),i},d=p("📋 Logs "+(this.state?.includeConsole?"✓":""),this.state?.includeConsole||!1,()=>{this.state&&(this.state.includeConsole=!this.state.includeConsole,this.render())}),h=p("🌐 Network "+(this.state?.includeNetwork?"✓":""),this.state?.includeNetwork||!1,()=>{this.state&&(this.state.includeNetwork=!this.state.includeNetwork,this.render())});c.appendChild(d),c.appendChild(h);const u=Lt("div");Ht(u,{display:"flex",gap:"8px"});const m=Lt("button",{},["Open Panel"]);Ht(m,{flex:"1",padding:"8px 12px",backgroundColor:"#27272a",border:"1px solid #3f3f46",borderRadius:"6px",color:"#d4d4d8",fontSize:"13px",fontWeight:"500",cursor:"pointer"});const g=Mt(m,"click",()=>{this.state&&this.contextMenuState.element&&(this.state.selectedElement=this.contextMenuState.element,this.state.isOpen=!0,this.state.activeTab="prompts"),this.closeContextMenu(),this.isMinimized=!1,this.client.open()});this.cleanupFunctions.push(g);const f=Lt("button",{},["Submit"]);Ht(f,{flex:"1",padding:"8px 12px",backgroundColor:this.state?.agentOnline?"#3b82f6":"#3f3f46",border:"none",borderRadius:"6px",color:"white",fontSize:"13px",fontWeight:"500",cursor:this.state?.agentOnline?"pointer":"not-allowed",opacity:this.state?.agentOnline?"1":"0.5"});const b=Mt(f,"click",async()=>{const t=l.value.trim();if(t&&this.state?.agentOnline&&this.contextMenuState.element)try{await this.client.submitPrompt(t,{elementContext:this.contextMenuState.element}),this.closeContextMenu(),this.isMinimized=!1,this.client.open()}catch(t){console.error("Failed to submit:",t)}});this.cleanupFunctions.push(b),u.appendChild(m),u.appendChild(f),a.appendChild(l),a.appendChild(c),a.appendChild(u),t.appendChild(e),t.appendChild(a);const x=Mt(document,"click",e=>{t&&!t.contains(e.target)&&this.closeContextMenu()});this.cleanupFunctions.push(x);const y=Mt(document,"keydown",t=>{"Escape"===t.key&&this.closeContextMenu()});this.cleanupFunctions.push(y),this.elements.container.appendChild(t),this.elements.contextMenu=t,setTimeout(()=>l.focus(),50)}closeContextMenu(){this.contextMenuState={isOpen:!1,position:{x:0,y:0},element:null},this.client.getElementSelector().removeSelectedHighlight(),this.render()}renderElementMarkers(){if(!this.state||"all"!==this.state.overlayMode)return;const t=Lt("div",{className:"orquesta-element-markers"});Ht(t,{position:"fixed",inset:"0",zIndex:"2147483644",pointerEvents:"none"}),this.state.elementMarkers.forEach(e=>{if(!e.rect)return;const n=Lt("div");Ht(n,{position:"fixed",left:`${e.rect.left}px`,top:`${e.rect.top}px`,width:`${e.rect.width}px`,height:`${e.rect.height}px`,border:"2px solid #7c3aed",borderRadius:"4px",backgroundColor:"rgba(124, 58, 237, 0.1)",pointerEvents:"auto",cursor:"pointer"});const i=Lt("div");Ht(i,{position:"absolute",top:"-8px",right:"-8px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"#7c3aed",color:"white",fontSize:"11px",fontWeight:"600",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'}),i.textContent="1",n.appendChild(i);const s=Mt(n,"click",()=>{this.state&&(this.state.activeTab="timeline",this.state.expandedPromptId=e.promptId,this.client.open()),this.render()});this.cleanupFunctions.push(s);const o=Lt("div");Ht(o,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"8px",padding:"8px 12px",backgroundColor:"#18181b",border:"1px solid #3f3f46",borderRadius:"6px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",maxWidth:"250px",display:"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'});const r=Lt("div",{},[e.content.slice(0,80)+(e.content.length>80?"...":"")]);if(Ht(r,{fontSize:"12px",color:"#d4d4d8"}),o.appendChild(r),e.author){const t=Lt("div",{},[`by ${e.author.full_name}`]);Ht(t,{fontSize:"11px",color:"#71717a",marginTop:"4px"}),o.appendChild(t)}n.appendChild(o);const a=Mt(n,"mouseenter",()=>{Ht(o,{display:"block"})}),l=Mt(n,"mouseleave",()=>{Ht(o,{display:"none"})});this.cleanupFunctions.push(a,l),t.appendChild(n)}),this.elements.container.appendChild(t),this.elements.elementMarkers=t}renderError(t){const e=Lt("div",{className:"orquesta-embed-error"});Ht(e,{position:"fixed",bottom:"16px",right:"16px",zIndex:"2147483647",padding:"16px",background:"#7f1d1d",border:"1px solid #991b1b",borderRadius:"8px",maxWidth:"300px"});const n=Lt("div",{},["Orquesta Error"]);Ht(n,{fontWeight:"600",color:"white",marginBottom:"4px"});const i=Lt("div",{},[t]);Ht(i,{color:"#fecaca",fontSize:"13px"}),e.appendChild(n),e.appendChild(i),this.elements.container.appendChild(e)}formatDate(t){const e=new Date(t),n=(new Date).getTime()-e.getTime(),i=Math.floor(n/6e4);return i<1?"Just now":i<60?`${i}m ago`:i<1440?`${Math.floor(i/60)}h ago`:`${Math.floor(i/1440)}d ago`}open(){this.isMinimized=!1,this.client.open()}close(){this.client.close()}toggle(){this.client.toggle()}startElementSelection(){this.client.startElementSelection()}async submitPrompt(t,e){return this.client.submitPrompt(t,e)}renderBuilder(){if(!this.state)return;this.builderRoot||this.createBuilderDOM();const t=this.builderRoot?.querySelector(".orquesta-builder-status-dot");t&&(t.style.background=this.state.agentOnline?"#22c55e":"#ef4444");const e=this.builderRoot?.querySelector(".orquesta-builder-status-text");if(e&&(e.textContent=this.state.agentOnline?"Agent online":"Agent offline"),this.state.currentPrompt){const t=this.state.currentPrompt;"running"!==t.status||this.builderMessages.some(e=>e.content===`Running: ${t.content.slice(0,80)}`)||this.builderMessages.push({role:"status",content:`Running: ${t.content.slice(0,80)}${t.content.length>80?"...":""}`}),"completed"!==t.status||this.builderMessages.some(t=>t.content.startsWith("Completed"))||(this.builderMessages.push({role:"status",content:"Completed successfully"}),this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)),"failed"!==t.status||this.builderMessages.some(t=>t.content.startsWith("Failed"))||this.builderMessages.push({role:"status",content:"Failed — check terminal for details"})}this.updateBuilderMessages(),this.updateBuilderTerminal();const n=this.builderRoot?.querySelector(".orquesta-builder-submit");n&&(n.disabled=this.state.isSubmitting||!this.state.agentOnline)}createBuilderDOM(){this.config.container&&("string"==typeof this.config.container?document.querySelector(this.config.container)||document.body:this.config.container);const t=this.config.previewUrl||window.location.href,e=this.state?.projectName||"Project",n=Lt("div",{className:"orquesta-builder orquesta-embed-panel"}),i=Lt("div",{className:"orquesta-builder-header"}),s=Lt("div",{className:"orquesta-builder-header-left"});s.innerHTML=`\n <span class="orquesta-builder-logo">⬡ Orquesta</span>\n <span class="orquesta-builder-project">${this.escapeHtml(e)}</span>\n `;const o=Lt("div",{className:"orquesta-builder-header-right"});o.innerHTML=`\n <div class="orquesta-builder-status">\n <span class="orquesta-builder-status-dot" style="background:${this.state?.agentOnline?"#22c55e":"#ef4444"}"></span>\n <span class="orquesta-builder-status-text">${this.state?.agentOnline?"Agent online":"Agent offline"}</span>\n </div>\n `;const r=Lt("button");r.textContent="⊡",r.title="Collapse to widget mode",Ht(r,{padding:"4px 8px",background:"transparent",border:"1px solid #3f3f46",borderRadius:"4px",color:"#a1a1aa",cursor:"pointer",fontSize:"14px",marginLeft:"8px"}),this.cleanupFunctions.push(Mt(r,"click",()=>{this.switchMode("widget")})),this.cleanupFunctions.push(Mt(r,"mouseenter",()=>{Ht(r,{background:"#3f3f46",color:"white"})})),this.cleanupFunctions.push(Mt(r,"mouseleave",()=>{Ht(r,{background:"transparent",color:"#a1a1aa"})})),o.appendChild(r),i.appendChild(s),i.appendChild(o),n.appendChild(i);const a=Lt("div",{className:"orquesta-builder-main"}),l=Lt("div",{className:"orquesta-builder-chat"}),c=Lt("div",{className:"orquesta-builder-chat-messages"});c.innerHTML='\n <div class="orquesta-builder-msg orquesta-builder-msg-system">\n What would you like to build? Describe the feature or change and I\'ll implement it.\n </div>\n ',this.builderMsgContainer=c,l.appendChild(c);const p=Lt("div",{className:"orquesta-builder-chat-input"}),d=Lt("textarea",{placeholder:"Describe what you want to build..."});d.setAttribute("rows","3");const h=Lt("div",{className:"orquesta-builder-chat-input-actions"}),u=Lt("span");Ht(u,{fontSize:"11px",color:"#71717a"}),u.textContent="Enter to send, Shift+Enter for newline";const m=Lt("button",{className:"orquesta-builder-btn-primary orquesta-builder-submit"});m.textContent="Send",m.disabled=!this.state?.agentOnline,h.appendChild(u),h.appendChild(m),p.appendChild(d),p.appendChild(h),l.appendChild(p);const g=()=>{const t=d.value.trim();t&&!this.state?.isSubmitting&&(d.value="",this.builderMessages.push({role:"user",content:t}),this.updateBuilderMessages(),this.client.submitPrompt(t).catch(t=>{this.builderMessages.push({role:"status",content:`Error: ${t.message}`}),this.updateBuilderMessages()}))};this.cleanupFunctions.push(Mt(m,"click",g)),this.cleanupFunctions.push(Mt(d,"keydown",t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),g())})),a.appendChild(l);const f=Lt("div",{className:"orquesta-builder-resizer-h"});let b=!1;this.cleanupFunctions.push(Mt(f,"mousedown",()=>{b=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(Mt(document,"mousemove",t=>{if(!b)return;const e=Math.max(300,Math.min(t.clientX,.5*window.innerWidth));l.style.width=`${e}px`})),this.cleanupFunctions.push(Mt(document,"mouseup",()=>{b&&(b=!1,document.body.style.cursor="",document.body.style.userSelect="")})),a.appendChild(f);const x=Lt("div",{className:"orquesta-builder-preview"}),y=Lt("div",{className:"orquesta-builder-preview-bar"}),w=Lt("div");Ht(w,{display:"flex",gap:"6px"}),w.innerHTML='\n <span style="width:12px;height:12px;border-radius:50%;background:#ef4444"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#eab308"></span>\n <span style="width:12px;height:12px;border-radius:50%;background:#22c55e"></span>\n ',y.appendChild(w);const C=Lt("div",{className:"orquesta-builder-preview-url"});C.textContent=t,y.appendChild(C);const v=Lt("button");v.textContent="↻",v.title="Refresh preview",this.cleanupFunctions.push(Mt(v,"click",()=>{this.builderPreviewFrame&&(this.builderPreviewFrame.src=this.builderPreviewFrame.src)})),y.appendChild(v),x.appendChild(y);const k=Lt("iframe",{className:"orquesta-builder-preview-iframe"});k.src=t,k.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.builderPreviewFrame=k,x.appendChild(k),a.appendChild(x),n.appendChild(a);const S=Lt("div",{className:"orquesta-builder-resizer-v"});let q=!1;const E=Lt("div",{className:"orquesta-builder-terminal"+(this.builderTerminalCollapsed?" collapsed":"")});this.cleanupFunctions.push(Mt(S,"mousedown",()=>{q=!0,document.body.style.cursor="row-resize",document.body.style.userSelect="none"})),this.cleanupFunctions.push(Mt(document,"mousemove",t=>{if(!q)return;const e=Math.max(100,Math.min(window.innerHeight-t.clientY,.5*window.innerHeight));E.style.height=`${e}px`,this.builderTerminalCollapsed=!1,E.classList.remove("collapsed")})),this.cleanupFunctions.push(Mt(document,"mouseup",()=>{q&&(q=!1,document.body.style.cursor="",document.body.style.userSelect="")})),n.appendChild(S);const _=Lt("div",{className:"orquesta-builder-terminal-header"}),R=Lt("span",{className:"orquesta-builder-terminal-title"});R.textContent="Terminal";const O=Lt("button");O.textContent=this.builderTerminalCollapsed?"▲":"▼",O.title="Toggle terminal",this.cleanupFunctions.push(Mt(O,"click",()=>{this.builderTerminalCollapsed=!this.builderTerminalCollapsed,E.classList.toggle("collapsed",this.builderTerminalCollapsed),O.textContent=this.builderTerminalCollapsed?"▲":"▼"})),_.appendChild(R),_.appendChild(O),E.appendChild(_);const T=Lt("div",{className:"orquesta-builder-terminal-output"});this.builderTerminalOutput=T,E.appendChild(T),n.appendChild(E),this.elements.container.innerHTML="",this.elements.container.appendChild(n),this.builderRoot=n,Ht(this.elements.container,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",zIndex:"2147483647"}),d.focus()}updateBuilderMessages(){if(!this.builderMsgContainer)return;const t=this.builderMsgContainer.querySelector(".orquesta-builder-msg-system");this.builderMsgContainer.innerHTML="",t&&this.builderMsgContainer.appendChild(t);for(const t of this.builderMessages){const e=Lt("div",{className:`orquesta-builder-msg orquesta-builder-msg-${t.role}`});e.textContent=t.content,this.builderMsgContainer.appendChild(e)}this.builderMsgContainer.scrollTop=this.builderMsgContainer.scrollHeight}updateBuilderTerminal(){if(!this.builderTerminalOutput||!this.state)return;const t=this.state.outputLines;if(t.length!==this.builderLastOutputCount){for(let e=this.builderLastOutputCount;e<t.length;e++){const n=t[e],i=Lt("div");Ht(i,{color:this.getTerminalColor(n.type),whiteSpace:"pre-wrap",wordBreak:"break-all"}),i.textContent=n.content,this.builderTerminalOutput.appendChild(i)}this.builderLastOutputCount=t.length,this.builderTerminalOutput.scrollTop=this.builderTerminalOutput.scrollHeight}}getTerminalColor(t){switch(t){case"stderr":case"error":return"#ef4444";case"tool":case"tool_call":return"#3b82f6";case"tool_result":return"#22c55e";case"thinking":return"#71717a";case"system":return"#eab308";case"progress":return"#a78bfa";default:return"#d4d4d8"}}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}switchMode(t){this.currentMode!==t&&(this.currentMode=t,this.elements.container.innerHTML="",this.cleanupFunctions.forEach(t=>t()),this.cleanupFunctions=[],"widget"===t&&(this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,Ht(this.elements.container,{position:"",top:"",left:"",right:"",bottom:""}),this.isMinimized=!1,this.client.open()),this.render())}setMode(t){this.switchMode(t)}destroy(){this.unsubscribe?.(),this.cleanupFunctions.forEach(t=>t()),this.globalRightClickCleanup&&(this.globalRightClickCleanup(),this.globalRightClickCleanup=null),this.client.disconnect(),this.builderRoot=null,this.builderMsgContainer=null,this.builderTerminalOutput=null,this.builderPreviewFrame=null,Pt(this.elements.container),Pt(function(t,e=document){return e.querySelector(t)}("#orquesta-embed-styles"))}showStatus(){this.showStatusBar=!0,this.statusBarMinimized=!1,this.render()}hideStatus(){this.showStatusBar=!1,this.render()}}const Ft={init(t){const e=new It(t);return e.init().catch(console.error),e},OrquestaWidget:It};return"undefined"!=typeof window&&(window.Orquesta=Ft),t.ConsoleCapture=Et,t.ElementSelector=Rt,t.NetworkCapture=_t,t.OrquestaEmbedClient=zt,t.OrquestaWidget=It,t.default=Ft,Object.defineProperty(t,"__esModule",{value:!0}),t}({});
|