@phpsandbox/sdk 0.0.36 → 0.0.37

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.
@@ -1,5 +1,5 @@
1
- var Tt=Object.create;var Xe=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var _t=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty;var Je=n=>{throw TypeError(n)};var oe=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Dt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ct(e))!Pt.call(n,r)&&r!==t&&Xe(n,r,{get:()=>e[r],enumerable:!(i=It(e,r))||i.enumerable});return n};var Ye=(n,e,t)=>(t=n!=null?Tt(_t(n)):{},Dt(e||!n||!n.__esModule?Xe(t,"default",{value:n,enumerable:!0}):t,n));var we=(n,e,t)=>e.has(n)||Je("Cannot "+t);var se=(n,e,t)=>(we(n,e,"read from private field"),t?t.call(n):e.get(n)),O=(n,e,t)=>e.has(n)?Je("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),xe=(n,e,t,i)=>(we(n,e,"write to private field"),i?i.call(n,t):e.set(n,t),t),k=(n,e,t)=>(we(n,e,"access private method"),t);var ut=oe((Pr,lt)=>{function b(n,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}lt.exports=b;b.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};b.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};b.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var e=new Date().getTime();if(n&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},t),this._options.unref&&this._timer.unref(),!0};b.prototype.attempt=function(n,e){this._fn=n,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};b.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};b.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};b.prototype.start=b.prototype.try;b.prototype.errors=function(){return this._errors};b.prototype.attempts=function(){return this._attempts};b.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},e=null,t=0,i=0;i<this._errors.length;i++){var r=this._errors[i],o=r.message,s=(n[o]||0)+1;n[o]=s,s>=t&&(e=r,t=s)}return e}});var ht=oe(D=>{var si=ut();D.operation=function(n){var e=D.timeouts(n);return new si(e,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};D.timeouts=function(n){if(n instanceof Array)return[].concat(n);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in n)e[t]=n[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],r=0;r<e.retries;r++)i.push(this.createTimeout(r,e));return n&&n.forever&&!i.length&&i.push(this.createTimeout(r,e)),i.sort(function(o,s){return o-s}),i};D.createTimeout=function(n,e){var t=e.randomize?Math.random()+1:1,i=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,n));return i=Math.min(i,e.maxTimeout),i};D.wrap=function(n,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var i in n)typeof n[i]=="function"&&t.push(i)}for(var r=0;r<t.length;r++){var o=t[r],s=n[o];n[o]=function(c){var h=D.operation(e),u=Array.prototype.slice.call(arguments,1),l=u.pop();u.push(function(d){h.retry(d)||(d&&(arguments[0]=h.mainError()),l.apply(this,arguments))}),h.attempt(function(){c.apply(n,u)})}.bind(n,s),n[o].options=e}}});var dt=oe((Ar,pt)=>{pt.exports=ht()});var Re=oe((Nr,mt)=>{var ai=dt();function ci(n,e){function t(i,r){var o=e||{},s;"randomize"in o||(o.randomize=!0),s=ai.operation(o);function a(u){r(u||new Error("Aborted"))}function c(u,l){if(u.bail){a(u);return}s.retry(u)?o.onRetry&&o.onRetry(u,l):r(s.mainError())}function h(u){var l;try{l=n(a,u)}catch(d){c(d,u);return}Promise.resolve(l).then(i).catch(function(f){c(f,u)})}s.attempt(h)}return new Promise(t)}mt.exports=ci});var y=class extends Error{constructor(t,i,r={}){super(i);this.code=t;this.message=i;this.raw=r}},L=class extends y{constructor(e,t={}){super(429,e,t)}},Ze=class extends y{};var je="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var g=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=je[t[n]&63];return e};var At=(r=>(r[r.Unknown=0]="Unknown",r[r.File=1]="File",r[r.Directory=2]="Directory",r[r.SymbolicLink=64]="SymbolicLink",r))(At||{}),Nt=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(Nt||{}),Rt=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(Rt||{}),ke=class extends y{constructor(t,i){super(t.code,t.message);this.name=i}},Ee=class{constructor(e,t,i){this.path=e;this.okra=t;this.disposable=i}dispose(){this.okra.invoke("fs.unwatch",{path:this.path}),this.disposable.dispose()}},ae=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t,onDidChange:i}of this.watches.values())this.watch(e,t,i)})}info(e){return this.okra.invoke("fs.info",{path:e})}write(e,t){return this.okra.invoke("fs.write",{path:e,contents:t})}find(e,t={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:Object.assign(t,{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1})})}search(e,t,i){e.id||(e.id=g());let r={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,s=async c=>{c===!1&&a.dispose(),i&&await Promise.resolve(i(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...r,...t}}).finally(()=>a.dispose())}mkdir(e){return this.okra.invoke("fs.mkdir",{path:e})}move(e,t){return this.okra.invoke("fs.move",{from:e,to:t})}remove(e,t){return this.okra.invoke("fs.remove",{path:e,type:t})}async readFile(e,t){try{let i=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return i instanceof Uint8Array?i:typeof i=="string"?new TextEncoder().encode(i):i}catch(i){this.handleError(i)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(i=>this.handleError(i))}writeFile(e,t,i){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:i}).catch(r=>this.handleError(r))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,i){return this.okra.invoke("fs.rename",{from:e,to:t,options:i}).catch(r=>this.handleError(r))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(i=>this.handleError(i))}copy(e,t,i){return this.okra.invoke("fs.copy",{source:e,destination:t,options:i}).catch(r=>this.handleError(r))}readDirectory(e,t=[],i=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:i}).catch(r=>this.handleError(r))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,i){let r=this.okra.listen(`fs.watch.${e}`,i),o={dispose:()=>{r.dispose(),this.okra.invoke("fs.unwatch",{path:e})}},s=new Ee(e,this.okra,o);return this.watches.set(e,{options:t,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>s)}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,i){let r=g(),o=!!e,s=[];return this.okra.listen(`fs.download.${r}`,o?e:a=>{s.push(a)}),this.okra.invoke("fs.download",{id:r,exclude:t,include:i}).then(()=>new Blob(s,{type:"application/octet-stream"}))}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof y&&"name"in e.raw?new ke(e,e.raw.name):e}};var _=class extends Error{constructor(t,i){super(t);this.time=i}},F=class n extends _{static fromPromiseTimeoutError(e){return new n(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",i={}){super(t);this.raw=i;this.name="NotebookUnavailableError"}};var ce=(n,e)=>{let t;return Promise.race([n,new Promise((i,r)=>t=setTimeout(r,e,new _("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},le=n=>{let e=null;return()=>e||(e=n())};var W=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}start(){return this.okra.invoke("terminal.start")}create(e){return this.okra.invoke("terminal.create",e)}onStarted(e){this.okra.listen("terminal.started",e)}resize(e,t){return this.okra.invoke("terminal.resize",{id:e,width:t[0],height:t[1]})}onOutput(e,t){this.okra.listen(`terminal.output.${e}`,t)}input(e,t){return this.okra.invoke("terminal.input",{id:e,input:t})}listen(e,t){return this.okra.listen(e,t)}async spawn(e,t,i){let r=i?.id||g(),o=new Set,s=()=>{for(let v of o)v.dispose();o.clear()},a=new WritableStream({write:v=>{this.input(r,v)},close:s}),c=null,h=new ReadableStream({start:v=>{c=v,o.add(this.listen(`terminal.output.${r}`,ye=>{c?.enqueue(ye.output)}))},cancel:()=>{c=null,s()}}),u=new Promise(v=>{o.add(this.listen(`terminal.close.${r}`,ye=>{if(c)try{c.close()}catch{}s(),v(ye.exitCode)}))}),l=le(()=>(s(),this.okra.invoke("terminal.close",{id:r}))),d=v=>{this.okra.invoke("terminal.resize",{id:r,width:v.cols,height:v.rows})},{abortSignal:f,...p}=i??{};f&&f.addEventListener("abort",l);let x=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:r,...p}},{abortSignal:f});return{exit:u,input:a,output:h,kill:l,resize:d,...x}}};var Ut=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(Ut||{}),$=class{constructor(e){this.okra=e}start(){return this.okra.invoke("container.start")}stop(){return this.okra.invoke("container.stop")}state(){return this.okra.invoke("container.state")}openedPorts(){return this.okra.invoke("container.opened-ports")}setPhp(e){return this.okra.invoke("container.set-php",{version:e})}enableTelemetry(e){return this.okra.invoke("container.stream-telemetry",{features:Array.from(e)})}stopTelemetry(){return this.okra.invoke("container.stop-telemetry")}listen(e,t){return this.okra.listen(e,t)}onPort(e){let t=[];return this.listen("container.ports",i=>{for(let r of i)t.some(o=>o.port===r.port)||e(r,"open");for(let r of t)i.some(o=>o.port===r.port)||e(r,"close");t=i})}};var K=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var z=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,i){this.okra.listen(`${t}.${e}`,r=>i(r))}onClose(e,t){this.listen(e,"lsp.closed",i=>t(i.code,i.reason))}onError(e,t){this.listen(e,"lsp.error",i=>t(i.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",i=>t(JSON.stringify(i)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return Se.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},Se=class n{constructor(e,t){this.id=e;this.lsp=t}send(e){return this.lsp.message(this.id,e)}onMessage(e){this.lsp.onResponse(this.id,e)}onError(e){this.lsp.onError(this.id,e)}onClose(e){this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,t){return new n(e,t)}};var H=class{constructor(e){this.okra=e}invoke(e,t={},i={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:i})}dumpAutoload(){return this.okra.invoke("composer.dump-autoload")}install(e={}){return this.invoke("install",{},e)}update(e,t={}){return this.invoke("update",e,t)}require(e,t={}){return this.invoke("require",e,t)}remove(e,t={}){return this.invoke("remove",e,t)}stream(e){return this.okra.listen("composer.log",e)}packages(){return this.okra.invoke("composer.packages")}};var G=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){this.okra.listen(e,t)}};var q=class{constructor(e){this.okra=e}maintenanceInfo(){return this.okra.invoke("laravel.maintenance.info",{})}toggleMaintenance(e){return this.okra.invoke("laravel.maintenance.toggle",e)}};var Q=class{constructor(e){this.okra=e}eval(e,t="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:i})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}start(){return this.okra.invoke("repl.start")}resize(e,t){return this.okra.invoke("repl.resize",{cols:e,rows:t})}listen(e,t){this.okra.listen(e,t)}onOutput(e){this.okra.listen("repl.output",e)}};function et(n,e=[],t){let i=Array.isArray(e)?e:[],r=Array.isArray(e)?t:e;return{command:Array.isArray(n)?n:i.length>0?[n,...i]:n,opts:r}}var Te=class extends Error{constructor(t,i){super(t);this.output=t;this.exitCode=i}},Ie=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new Te(this.output,this.exitCode);return this}},V=class{constructor(e){this.okra=e}onOutput(e,t){this.okra.listen(`shell.output.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}async exec(e,t=[],i){let r=et(e,t,i),{abortSignal:o,...s}=r.opts??{},a=await this.okra.invoke("shell.exec",{command:r.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new Ie(a.output,a.exitCode)}execStream(e,t=[],i){let r=et(e,t,i),o=r.opts?.id||g(),s=new Set,a=null,c=!1,h=()=>{for(let p of s)p.dispose();s.clear()},u=()=>{if(!c&&(c=!0,h(),a))try{a.close()}catch{}},l=p=>{c||(c=!0,h(),a&&a.error(p))},d=new ReadableStream({start:p=>{a=p,s.add(this.listen(`shell.output.${o}`,x=>{a?.enqueue(x.output)}))},cancel:()=>{c=!0,h()}}),f=this.exec(r.command,{...r.opts,id:o}).then(p=>(u(),p)).catch(p=>{throw l(p),p});return{output:d,result:f}}};var Lt=["redis"],qi=["start","nginx",...Lt],X=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,t){return this.okra.invoke("service.run",{name:e,command:t})}stop(e){return this.okra.invoke("service.stop",{name:e})}onLog(e,t){return this.okra.listen(`service.log.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}logs(e,t={}){return t.follow?this.followLogs(e,t):this.okra.invoke("service.logs",{name:e,tail:t.tail}).then(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,t){let i=t.id||g(),r=new Set,o=null,s=!1,a=()=>{for(let d of r)d.dispose();r.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},h=d=>{s||(s=!0,a(),o&&o.error(d))},u=le(()=>(c(),this.okra.invoke("service.stop-logs",{id:i}))),l=new ReadableStream({start:d=>{o=d,r.add(this.onLog(i,f=>{o?.enqueue(f.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:i}).catch(f=>{h(f)})},cancel:()=>{u()}});return{id:i,output:l,stop:u}}};function tt(n){let e=n.length,t=0,i=0;for(;i<e;){let r=n.charCodeAt(i++);if((r&4294967168)===0){t++;continue}else if((r&4294965248)===0)t+=2;else{if(r>=55296&&r<=56319&&i<e){let o=n.charCodeAt(i);(o&64512)===56320&&(++i,r=((r&1023)<<10)+(o&1023)+65536)}(r&4294901760)===0?t+=3:t+=4}}return t}function Bt(n,e,t){let i=n.length,r=t,o=0;for(;o<i;){let s=n.charCodeAt(o++);if((s&4294967168)===0){e[r++]=s;continue}else if((s&4294965248)===0)e[r++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<i){let a=n.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128):(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128)}e[r++]=s&63|128}}var Mt=new TextEncoder,Ot=50;function Ft(n,e,t){Mt.encodeInto(n,e.subarray(t))}function it(n,e,t){n.length>Ot?Ft(n,e,t):Bt(n,e,t)}var Wt=4096;function Ce(n,e,t){let i=e,r=i+t,o=[],s="";for(;i<r;){let a=n[i++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=n[i++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=n[i++]&63,h=n[i++]&63;o.push((a&31)<<12|c<<6|h)}else if((a&248)===240){let c=n[i++]&63,h=n[i++]&63,u=n[i++]&63,l=(a&7)<<18|c<<12|h<<6|u;l>65535&&(l-=65536,o.push(l>>>10&1023|55296),l=56320|l&1023),o.push(l)}else o.push(a);o.length>=Wt&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var $t=new TextDecoder,Kt=200;function zt(n,e,t){let i=n.subarray(e,e+t);return $t.decode(i)}function rt(n,e,t){return t>Kt?zt(n,e,t):Ce(n,e,t)}var P=class{constructor(e,t){this.type=e,this.data=t}};var m=class n extends Error{constructor(e){super(e);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function nt(n,e,t){let i=t/4294967296,r=t;n.setUint32(e,i),n.setUint32(e+4,r)}function ue(n,e,t){let i=Math.floor(t/4294967296),r=t;n.setUint32(e,i),n.setUint32(e+4,r)}function he(n,e){let t=n.getInt32(e),i=n.getUint32(e+4);return t*4294967296+i}function ot(n,e){let t=n.getUint32(e),i=n.getUint32(e+4);return t*4294967296+i}var Ht=-1,Gt=4294967296-1,qt=17179869184-1;function Qt({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=qt)if(e===0&&n<=Gt){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,i=n&4294967295,r=new Uint8Array(8),o=new DataView(r.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,i),r}else{let t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),ue(i,4,n),t}}function Vt(n){let e=n.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,r=Math.floor(i/1e9);return{sec:t+r,nsec:i-r*1e9}}function Xt(n){if(n instanceof Date){let e=Vt(n);return Qt(e)}else return null}function Jt(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),i=e.getUint32(4),r=(t&3)*4294967296+i,o=t>>>2;return{sec:r,nsec:o}}case 12:{let t=he(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new m(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function Yt(n){let e=Jt(n);return new Date(e.sec*1e3+e.nsec/1e6)}var st={type:Ht,encode:Xt,decode:Yt};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(st)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){let r=this.builtInEncoders[i];if(r!=null){let o=r(e,t);if(o!=null){let s=-1-i;return new P(s,o)}}}for(let i=0;i<this.encoders.length;i++){let r=this.encoders[i];if(r!=null){let o=r(e,t);if(o!=null){let s=i;return new P(s,o)}}}return e instanceof P?e:null}decode(e,t,i){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,i):new P(t,e)}};S.defaultCodec=new S;function Zt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function J(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Zt(n)?new Uint8Array(n):Uint8Array.from(n)}var jt=100,ei=2048,pe=class n{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??S.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??jt,this.initialBufferSize=e?.initialBufferSize??ei,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),i=new Uint8Array(t),r=new DataView(t);i.set(this.bytes),this.view=r,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let i=tt(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),it(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let i=J(e);this.writeU8a(i)}encodeArray(e,t){let i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(let r of e)this.doEncode(r,t+1)}countWithoutUndefined(e,t){let i=0;for(let r of t)e[r]!==void 0&&i++;return i}encodeMap(e,t){let i=Object.keys(e);this.sortKeys&&i.sort();let r=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else if(r<4294967296)this.writeU8(223),this.writeU32(r);else throw new Error(`Too large map object: ${r}`);for(let o of i){let s=e[o];this.ignoreUndefined&&s===void 0||(this.encodeString(o),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),r=i.length;if(r>=4294967296)throw new Error(`Too large extension object: ${r}`);this.writeU8(201),this.writeU32(r),this.writeI8(e.type),this.writeU8a(i);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),nt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ue(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function _e(n,e){return new pe(e).encodeSharedRef(n)}function de(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}var ti=16,ii=16,me=class{constructor(e=ti,t=ii){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){let r=this.caches[i-1];e:for(let o of r){let s=o.bytes;for(let a=0;a<i;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let i=this.caches[e.length-1],r={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=r:i.push(r)}decode(e,t,i){let r=this.find(e,t,i);if(r!=null)return this.hit++,r;this.miss++;let o=Ce(e,t,i),s=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(s,o),o}};var Pe="array",j="map_key",ct="map_value",ri=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new m("The type of key must be string or number but "+typeof n)},De=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Pe,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=j,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Pe){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===j||e.type===ct){let i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Z=-1,Ae=new DataView(new ArrayBuffer(0)),ni=new Uint8Array(Ae.buffer);try{Ae.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var at=new RangeError("Insufficient data"),oi=new me,fe=class n{constructor(e){this.totalPos=0,this.pos=0,this.view=Ae,this.bytes=ni,this.headByte=Z,this.stack=new De,this.entered=!1,this.extensionCodec=e?.extensionCodec??S.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:oi,this.mapKeyConverter=e?.mapKeyConverter??ri}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Z,this.stack.reset()}setBuffer(e){let t=J(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Z&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),i=J(e),r=new Uint8Array(t.length+i.length);r.set(t),r.set(i,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,i;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}let{headByte:r,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${de(r)} at ${s} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let i=t,r=-1;for await(let o of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(r=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let r=e-128;if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e<160){let r=e-144;if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else{let r=e-160;t=this.decodeString(r,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let r=this.lookU8();t=this.decodeString(r,1)}else if(e===218){let r=this.lookU16();t=this.decodeString(r,2)}else if(e===219){let r=this.lookU32();t=this.decodeString(r,4)}else if(e===220){let r=this.readU16();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===221){let r=this.readU32();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===222){let r=this.readU16();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===223){let r=this.readU32();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===196){let r=this.lookU8();t=this.decodeBinary(r,1)}else if(e===197){let r=this.lookU16();t=this.decodeBinary(r,2)}else if(e===198){let r=this.lookU32();t=this.decodeBinary(r,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let r=this.lookU8();t=this.decodeExtension(r,1)}else if(e===200){let r=this.lookU16();t=this.decodeExtension(r,2)}else if(e===201){let r=this.lookU32();t=this.decodeExtension(r,4)}else throw new m(`Unrecognized type byte: ${de(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let r=i.top();if(r.type===Pe)if(r.array[r.position]=t,r.position++,r.position===r.size)t=r.array,i.release(r);else continue e;else if(r.type===j){if(t==="__proto__")throw new m("The key __proto__ is not allowed");r.key=this.mapKeyConverter(t),r.type=ct;continue e}else if(r.map[r.key]=t,r.readCount++,r.readCount===r.size)t=r.map,i.release(r);else{r.key=null,r.type=j;continue e}}return t}}readHeadByte(){return this.headByte===Z&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Z}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new m(`Unrecognized array type byte: ${de(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new m(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new m(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new m(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw at;let i=this.pos+t,r;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?r=this.keyDecoder.decode(this.bytes,i,e):r=rt(this.bytes,i,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===j:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new m(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw at;let i=this.pos+t,r=this.bytes.subarray(i,i+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new m(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=ot(this.view,this.pos);return this.pos+=8,e}readI64(){let e=he(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Ne(n,e){return new fe(e).decode(n)}var wt=Ye(Re(),1);var Ue=function(n,e){return Ue=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var r in i)i.hasOwnProperty(r)&&(t[r]=i[r])},Ue(n,e)};function ft(n,e){Ue(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function li(n){var e=typeof Symbol=="function"&&n[Symbol.iterator],t=0;return e?e.call(n):{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}}}function ui(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(s)throw s.error}}return o}function hi(){for(var n=[],e=0;e<arguments.length;e++)n=n.concat(ui(arguments[e]));return n}var gt=(function(){function n(e,t){this.target=t,this.type=e}return n})(),pi=(function(n){ft(e,n);function e(t,i){var r=n.call(this,"error",i)||this;return r.message=t.message,r.error=t,r}return e})(gt),di=(function(n){ft(e,n);function e(t,i,r){t===void 0&&(t=1e3),i===void 0&&(i="");var o=n.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=i,o}return e})(gt);var mi=function(){if(typeof WebSocket<"u")return WebSocket},fi=function(n){return typeof n<"u"&&!!n&&n.CLOSING===2},A={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},gi=(function(){function n(e,t,i){var r=this;i===void 0&&(i={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){r._debug("open event");var s=r._options.minUptime,a=s===void 0?A.minUptime:s;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout(function(){return r._acceptOpen()},a),r._ws.binaryType=r._binaryType,r._messageQueue.forEach(function(c){return r._ws.send(c)}),r._messageQueue=[],r.onopen&&r.onopen(o),r._listeners.open.forEach(function(c){return r._callEventListener(o,c)})},this._handleMessage=function(o){r._debug("message event"),r.onmessage&&r.onmessage(o),r._listeners.message.forEach(function(s){return r._callEventListener(o,s)})},this._handleError=function(o){r._debug("error event",o.message),r._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),r.onerror&&r.onerror(o),r._debug("exec error listeners"),r._listeners.error.forEach(function(s){return r._callEventListener(o,s)}),r._connect()},this._handleClose=function(o){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(o),r._listeners.close.forEach(function(s){return r._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(n,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(n,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(n,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(n,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"CONNECTING",{get:function(){return n.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"OPEN",{get:function(){return n.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"CLOSING",{get:function(){return n.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"CLOSED",{get:function(){return n.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(t,i){return typeof i=="string"?t+=i.length:i instanceof Blob?t+=i.size:t+=i.byteLength,t},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?n.CLOSED:n.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),n.prototype.close=function(e,t){if(e===void 0&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,t)},n.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,t),this._connect())},n.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,i=t===void 0?A.maxEnqueuedMessages:t;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},n.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},n.prototype.dispatchEvent=function(e){var t,i,r=this._listeners[e.type];if(r)try{for(var o=li(r),s=o.next();!s.done;s=o.next()){var a=s.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}return!0},n.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==t}))},n.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,hi(["RWS>"],e))},n.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,i=t===void 0?A.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=r===void 0?A.minReconnectionDelay:r,s=e.maxReconnectionDelay,a=s===void 0?A.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(i,this._retryCount-1),c>a&&(c=a)),this._debug("next delay",c),c},n.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},n.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var t=e();if(typeof t=="string")return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},n.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var t=this._options,i=t.maxRetries,r=i===void 0?A.maxRetries:i,o=t.connectionTimeout,s=o===void 0?A.connectionTimeout:o,a=t.WebSocket,c=a===void 0?mi():a;if(this._retryCount>=r){this._debug("max retries reached",this._retryCount,">=",r);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!fi(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(h){e._closeCalled||(e._debug("connect",{url:h,protocols:e._protocols}),e._ws=e._protocols?new c(h,e._protocols):new c(h),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},s))})}},n.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new pi(Error("TIMEOUT"),this))},n.prototype._disconnect=function(e,t){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new di(e,t,this))}catch{}}},n.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},n.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},n.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},n.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},n.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},n})(),bt=gi;var bi=n=>{if(typeof n=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[n]??`STATE_${n}`},vi=n=>{try{let e=new URL(n);return`${e.origin}${e.pathname}`}catch{return n}},vt=n=>{if(n instanceof Error)return n.message?`${n.name}: ${n.message}`:n.name;if(typeof n=="string")return n;if(!n||typeof n!="object")return;let e=n,t=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!t)return;let i=typeof e.name=="string"&&e.name?e.name:void 0;return i?`${i}: ${t}`:t},ee=n=>{if(n instanceof Error)return n.message?`${n.name}: ${n.message}`:n.name;if(typeof n=="string")return n;if(!n||typeof n!="object")return String(n);let e=n,t=[],i=vt(e);i&&t.push(i);let r=vt(e.error);r&&r!==i&&t.push(`error=${r}`),typeof e.type=="string"&&e.type&&t.push(`type=${e.type}`),typeof e.code=="number"&&t.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==i&&t.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&t.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&t.push(`url=${vi(o.url)}`);let s=bi(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var B=null;typeof WebSocket<"u"?B=WebSocket:typeof MozWebSocket<"u"?B=MozWebSocket:typeof global<"u"?B=global.WebSocket||global.MozWebSocket:typeof window<"u"?B=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(B=self.WebSocket||self.MozWebSocket);var yt=B;var ge=class{constructor(){this.disposables=new Map}add(e,t){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof t=="function"&&(t=t()),this.disposables.set(e,t)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var Le=class extends Error{constructor(e="WebSocket connection timeout"){super(e),this.name="ConnectionTimeoutError"}},be=class extends Error{constructor(t,i){super(t);this.originalError=i;this.name="ConnectionFailedError"}},N=class extends Error{constructor(t,i){super(t);this.data=i;this.name="InvalidMessageError"}},R=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},T,Be,Me,te=class{constructor(e,t,i={}){this.eventEmitter=t;this.options=i;O(this,T);this.clientId="";this.closed=!1;this.disposables=new ge;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.connectionStats={connectTime:0,reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:0};this.messageQueue=[];this.MAX_QUEUE_SIZE=100;this.QUEUE_TIMEOUT=3e4;this.rateLimiter={requests:[],maxRequests:50,windowMs:1e3};this.validateConfiguration(i),this.url=new URL(e),this.PING_INTERVAL=i.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=i.connectWaitTimeout??3e4,this.connectionStats.connectionStartTime=Date.now();let r=i.startClosed!==!1;this.rws=new bt(this.url.toString(),[],{WebSocket:i.webSocket??globalThis.WebSocket??yt,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:r}),this.log("debug","Transport initialized",{url:this.url.toString(),options:i}),this.registerWatchers(),this.setupConnectionHealthMonitoring(),this.startPeriodicMaintenance()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new R("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new R("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new R("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new R("maxRetries must be between 0 and 100")}log(e,t,i){if(this.options.debug){let r=new Date().toISOString(),o=i?JSON.stringify(i,null,2):"";console[e](`[Transport ${r}] ${t}${o?`
2
- `+o:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):k(this,T,Be).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{if(!(t.data instanceof Blob)){let i=new Error("Unexpected message type: "+typeof t.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:i.message,messageType:typeof t.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:i,rawMessage:t.data,timestamp:Date.now()});return}t.data.arrayBuffer().then(i=>{if(i.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}try{this.handleRawMessage(Ne(i)).catch(r=>{this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:r,rawMessage:i,timestamp:Date.now()})})}catch(r){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:r,rawMessage:i,timestamp:Date.now()})}})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:i,as:r}=e;if(!i||typeof i!="string")throw new N("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!t}),i==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let o=new E(t?.message||"Notebook is no longer available",t||{});this.log("error","Boot error received",{data:t}),this.terminate(o,4e3,o.message);return}if(i==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new N("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(i==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new N("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(i,t,r)}catch(t){this.connectionStats.totalErrors++,t instanceof N?this.log("error","Invalid message format",{error:t.message,data:t.data,totalErrors:this.connectionStats.totalErrors}):this.log("error","Failed to parse message",{ev:e,error:t instanceof Error?t.message:String(t),totalErrors:this.connectionStats.totalErrors}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:t,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,t,i){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(i||e,t)}listen(e,t,i){return this.eventEmitter.listen(e,t)}onDidBootError(e){this.eventEmitter.listen("transport.boot_error",t=>{e(t.error)})}removeListener(e,t){this.eventEmitter.removeListener(e,t)}listenOnce(e,t,i){this.eventEmitter.once(e,t,i),this.disposables.add(`once_${e}_${g()}`,{dispose:()=>{this.eventEmitter.removeListener(e,t)}})}emit(e,...t){this.eventEmitter.emit(e,...t)}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,t={},i={}){if(this.terminalError)throw this.terminalError;if(this.isRateLimited())throw new L("Rate limit exceeded - too many requests");this.clearOldQueuedMessages();let r=i.responseEvent||`${e}_${g()}_response`,o=`${r}_error`,s,a=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),this.eventEmitter.removeListener(r),this.eventEmitter.removeListener(o)},c=async(u,l)=>{if(this.terminalError){l(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted&&l(d),i.abortSignal&&i.abortSignal.addEventListener("abort",()=>{l(d)}),!this.isConnected&&!this.isClosed){if(this.log("debug","Connection not available, queuing message",{action:e}),this.messageQueue.length>=this.MAX_QUEUE_SIZE){let p=this.messageQueue.shift();p&&p.reject(new Error("Message queue full, oldest message dropped"))}this.messageQueue.push({action:e,data:t,options:i,resolve:u,reject:l,timestamp:Date.now()});return}let f=Date.now();this.listenOnce(r,p=>{let x=Date.now()-f;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+x)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:x,avgResponseTime:this.connectionStats.avgResponseTime}),u(p)}),this.listenOnce(o,p=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:p}),l(new y(p.code,p.message,p))}),s=p=>{if(p.code===1008&&(p.reason||"").includes("rate limit")){l(new L(p.reason||"Rate limit exceeded",p));return}let x=ee(p);l(this.terminalError||new be(`Connection lost to the notebook during request: ${x}`,p))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:r})),this.log("debug","Message sent",{action:e,data:t})}catch(p){throw this.log("error","Failed to send message",{action:e,error:p}),p}},h=async()=>{await k(this,T,Be).call(this);let u=new Promise(c).finally(a);return i.timeout?ce(u,i.timeout).catch(l=>{throw l instanceof _?F.fromPromiseTimeoutError(l):l}).finally(a):u};return this.sendWithRetry(async()=>await h(),i.retries||10)}pack(e){return new Blob([_e(e)])}sendWithRetry(e,t=10){return(0,wt.default)(async(i,r)=>{try{return await e()}catch(o){if(o instanceof y||o instanceof L||o instanceof R||o instanceof N||o instanceof E||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:r}),i(o);return}throw o instanceof F&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:r,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:r,error:o instanceof Error?o.message:String(o),nextDelay:this.getBackoffDelay(r-1)}),o}},{retries:t,onRetry:(i,r)=>{this.log("warn","Send operation retry",{attempt:r,maxRetries:t,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${g()}`),this.call("invoke",{action:e,data:t},i)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){if(this.closed){console.trace("Transport is already closed, cannot disconnect again");return}this.close()}terminate(e,t=4e3,i=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,i)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let i=this.messageQueue.length,r=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(o=>{o.reject(r)}),this.messageQueue=[],i>0&&this.log("debug",`Rejected ${i} queued messages due to connection close`),this.rateLimiter.requests=[],this.disposables.dispose();try{this.rws.close(e,t)}catch(o){this.log("error","Error closing WebSocket",{error:o instanceof Error?o.message:String(o)})}this.eventEmitter.emit("transport.closed",{code:e,reason:t,metrics:this.getConnectionMetrics(),timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}onDidConnect(e){this.rws.addEventListener("open",e),this.disposables.add("connect",{dispose:()=>{this.rws.removeEventListener("open",e)}})}onDidClose(e){this.rws.addEventListener("close",e),this.disposables.add("close",{dispose:()=>{this.rws.removeEventListener("close",e)}})}setupConnectionHealthMonitoring(){this.rws.addEventListener("open",()=>{this.connectionStats.connectTime=Date.now(),this.connectionStats.reconnectCount++,this.log("info","Connection established",{reconnectCount:this.connectionStats.reconnectCount,timeSinceStart:Date.now()-this.connectionStats.connectionStartTime}),this.processMessageQueue()}),this.rws.addEventListener("close",e=>{this.log("warn","Connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.handleConnectionClose(e.code)}),this.rws.addEventListener("error",e=>{this.connectionStats.totalErrors++;let t=ee(e);this.log("error","Connection error",{error:t,rawError:e,totalErrors:this.connectionStats.totalErrors})})}handleConnectionClose(e){switch(e){case 1e3:return this.log("info","Normal connection closure"),"stop";case 1001:return this.log("info","Connection going away, will reconnect"),"reconnect";case 1006:return this.log("warn","Abnormal connection closure, will retry"),"retry";case 1008:return this.log("error","Connection closed due to policy violation"),this.clearOldQueuedMessages(),"stop";case 4e3:return this.log("info","Connection closed due to terminal notebook error"),"stop";default:return this.log("warn",`Unknown close code: ${e}, will reconnect`),"reconnect"}}processMessageQueue(){if(this.messageQueue.length===0)return;this.log("debug",`Processing ${this.messageQueue.length} queued messages`);let e=[...this.messageQueue];this.messageQueue=[];for(let t of e){if(Date.now()-t.timestamp>this.QUEUE_TIMEOUT){t.reject(new Error("Queued message timed out"));continue}this.call(t.action,t.data,t.options).then(t.resolve).catch(t.reject)}}clearOldQueuedMessages(){let e=Date.now(),t=this.messageQueue.length;this.messageQueue=this.messageQueue.filter(i=>{let r=e-i.timestamp>this.QUEUE_TIMEOUT;return r&&i.reject(new Error("Queued message expired")),!r}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}isRateLimited(){let e=Date.now();return this.rateLimiter.requests=this.rateLimiter.requests.filter(t=>e-t<this.rateLimiter.windowMs),this.rateLimiter.requests.length>=this.rateLimiter.maxRequests?!0:(this.rateLimiter.requests.push(e),!1)}getBackoffDelay(e){return Math.min(1e3*Math.pow(2,e),3e4)+Math.random()*1e3}getConnectionMetrics(){let e=Date.now(),t=this.connectionStats.connectTime>0?e-this.connectionStats.connectTime:0;return{status:this.status,clientId:this.clientId,isConnected:this.isConnected,isConnecting:this.isConnecting,connectionStats:{...this.connectionStats,connectionDuration:t,uptime:e-this.connectionStats.connectionStartTime,messagesPerSecond:t>0?(this.connectionStats.totalMessages/(t/1e3)).toFixed(2):"0",errorRate:this.connectionStats.totalMessages>0?(this.connectionStats.totalErrors/this.connectionStats.totalMessages*100).toFixed(2)+"%":"0%",timeSinceLastPing:this.connectionStats.lastPingTime>0?e-this.connectionStats.lastPingTime:0,timeSinceLastPong:this.connectionStats.lastPongTime>0?e-this.connectionStats.lastPongTime:0},messageQueue:{length:this.messageQueue.length,maxSize:this.MAX_QUEUE_SIZE,oldestMessageAge:this.messageQueue.length>0?e-Math.min(...this.messageQueue.map(i=>i.timestamp)):0},rateLimiter:{currentRequests:this.rateLimiter.requests.length,maxRequests:this.rateLimiter.maxRequests,windowMs:this.rateLimiter.windowMs,isLimited:this.isRateLimited()},config:{pingInterval:this.PING_INTERVAL,queueTimeout:this.QUEUE_TIMEOUT,url:this.url.toString()}}}getHealthStatus(){let t=this.getConnectionMetrics().connectionStats;return!this.isConnected||t.timeSinceLastPong>this.PING_INTERVAL*2||Number.parseFloat(t.errorRate)>50?"unhealthy":t.avgResponseTime>5e3||Number.parseFloat(t.errorRate)>10||t.timeSinceLastPong>this.PING_INTERVAL*1.5?"degraded":"healthy"}resetStats(){this.connectionStats={connectTime:Date.now(),reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:Date.now()},this.log("debug","Connection statistics reset")}async runDiagnostics(){let e=this.getConnectionMetrics(),t=this.getHealthStatus(),i=[],r=[];return this.isConnected||(i.push("Connection is not established"),r.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(i.push("No pong received recently - connection may be stale"),r.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(i.push(`High error rate: ${e.connectionStats.errorRate}`),r.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(i.push("Message queue is nearly full"),r.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(i.push("High average response time"),r.push("Check network latency and server performance")),e.rateLimiter.isLimited&&(i.push("Rate limiting is active"),r.push("Reduce request frequency or increase rate limit")),this.log("info","Connection diagnostics completed",{status:t,issueCount:i.length,recommendationCount:r.length}),{status:t,metrics:e,issues:i,recommendations:r}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{this.clearOldQueuedMessages();let t=Date.now();if(this.rateLimiter.requests=this.rateLimiter.requests.filter(i=>t-i<this.rateLimiter.windowMs),this.options.debug){let i=this.getHealthStatus(),r=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:i,messageCount:r.connectionStats.totalMessages,errorCount:r.connectionStats.totalErrors,queueLength:r.messageQueue.length})}},3e5);return{dispose:()=>{clearInterval(e)}}})}};T=new WeakSet,Be=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,t)=>{if(this.isConnected){e(),k(this,T,Me).call(this);return}let i,r=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(i)},s=()=>{o(),this.connectPromise=null,e(),k(this,T,Me).call(this)},a=h=>{r+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:r,error:ee(h)})},c=h=>{let u=ee(h);if("code"in h&&(h.code===1008||h.code===4e3)){o(),this.connectPromise=null,t(new be(`WebSocket connection failed: ${u}`,h));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:u})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),i=setTimeout(()=>{o(),this.connectPromise=null,t(new Le(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},Me=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.connectionStats.lastPingTime=Date.now(),this.log("debug","Sending periodic ping");let t=Date.now();await this.invoke("ping"),this.connectionStats.lastPongTime=Date.now();let i=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:i})}catch(t){this.log("error","Ping failed",{error:t instanceof Error?t.message:String(t)}),Date.now()-this.connectionStats.lastPongTime>this.PING_INTERVAL*3&&(this.log("warn","Connection appears dead, forcing reconnection"),this.rws.reconnect())}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function xt(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(r){r(t)}),(i=n.get("*"))&&i.slice().map(function(r){r(e,t)})}}}function yi(n){let e=xt(n);return e.once=(t,i)=>{e.on(t,i),e.on(t,e.off.bind(e,t,i))},e}var U=class n{constructor(){this.emitter=yi()}listen(e,t){let i=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:i}}emit(e,t){this.emitter.emit(e,t)}once(e,t){this.emitter.once(e,t)}static make(){return new n}static refresh(){return new n}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new n}inspect(){return this.emitter.all}};var ie=class{constructor(e){this.okra=e}checkpoint(e,t,i="main",r=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:i,allowEmpty:r})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,i="main",r,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:i,token:r,direction:o,force:s})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}};var Oe=Ye(Re(),1);var re=class{constructor(e,t,i){this.onEvent=e;this.onceEvent=t;this.beacon=i;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=i,this.setupUrlChangeListener(),this.urlHistory.push(i.iframe.src),this.updateNavigationState()}visit(e){if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState(),this.emitHistoryChange(e,"push")}setupUrlChangeListener(){this.beacon.on("urlChange",e=>{this.addToHistory(e.newUrl)})}addToHistory(e){this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState()}updateNavigationState(){let e=this._canGoBack,t=this._canGoForward;this._canGoBack=this.currentIndex>0,this._canGoForward=this.currentIndex<this.urlHistory.length-1,(e!==this._canGoBack||t!==this._canGoForward)&&this.emitNavigationStateChange()}emitNavigationStateChange(){this.beacon&&this.beacon.emit&&this.beacon.emit("navigationStateChange",{canGoBack:this._canGoBack,canGoForward:this._canGoForward,currentIndex:this.currentIndex,historyLength:this.urlHistory.length,timestamp:Date.now()})}get canGoBack(){return this._canGoBack}get canGoForward(){return this._canGoForward}async goBack(){if(!this.canGoBack)return{success:!1,error:"Cannot go back - no previous history"};this.currentIndex--,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"back"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async goForward(){if(!this.canGoForward)return{success:!1,error:"Cannot go forward - no forward history"};this.currentIndex++,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"forward"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async reload(){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){let e=this.urlHistory[this.currentIndex];if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"reload")}}getCurrentUrl(){return this.currentIndex>=0&&this.currentIndex<this.urlHistory.length?new URL(this.urlHistory[this.currentIndex]):new URL("about:blank")}getHistory(){return[...this.urlHistory]}getCurrentIndex(){return this.currentIndex}canGoBackSync(){return this.currentIndex>0}canGoForwardSync(){return this.currentIndex<this.urlHistory.length-1}emitHistoryChange(e,t){this.beacon&&this.beacon.emit&&this.beacon.emit("historyChange",{url:e,state:null,direction:t,timestamp:Date.now()})}async pushState(e){this.visit(e)}async replaceState(e){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){if(this.urlHistory[this.currentIndex]=e,!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"replace")}else this.visit(e)}async getHistoryLength(){return this.urlHistory.length}async getHistoryState(){return null}async getHistoryInfo(){return{length:this.urlHistory.length,state:null,url:this.urlHistory[this.currentIndex]||"",canGoBack:this.canGoBack,canGoForward:this.canGoForward}}on(e,t){return this.onEvent(e,t)}once(e,t){this.onceEvent(e,t)}};function kt(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var M=class extends Error{constructor(t,i){super(t);this.code=i;this.name="BeaconError"}},ve=class extends M{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},w=class extends M{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},Fe=class{constructor(e,t={}){this.messageHandlers=new Map;this.isBeaconReady=!1;this.readyPromise=null;this.isStarted=!1;this.disposables=[];this.messageChannel=null;this.port=null;this.channelEstablished=!1;kt(),this.iframe=e;let i={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...i,...t.retry},...t},this.eventEmitter=U.make(),this.setupMessageChannel(),this.navigator=new re(this.eventEmitter.listen.bind(this.eventEmitter),this.eventEmitter.once.bind(this.eventEmitter),this)}setupMessageChannel(){let e=t=>{try{if(t.source!==this.iframe.contentWindow)return;let i=t.data;if(!i||typeof i!="object"||!i.type)return;i.type==="beacon:ready-for-channel"&&this.establishChannel().catch(r=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",r)}),i.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",i.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(i){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",i)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new w("Iframe contentWindow not available");this.messageChannel=new MessageChannel,this.port=this.messageChannel.port1,this.port.onmessage=t=>{this.handleBeaconMessage(t.data)},this.port.onmessageerror=t=>{this.options.debug&&console.error("[Beacon SDK] Port message error:",t)},this.port.start();let e={type:"beacon:establish-channel",timestamp:Date.now(),id:this.generateId()};return this.iframe.contentWindow.postMessage(e,"*",[this.messageChannel.port2]),this.options.debug&&console.log("[Beacon SDK] Channel establishment message sent"),new Promise((t,i)=>{let r=setTimeout(()=>{i(new w("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(r),t()):setTimeout(o,100)};o()})}handleBeaconMessage(e){this.options.debug&&console.log("[Beacon SDK] Received message:",e.type,e.payload);let t=e.type.replace("beacon:","");this.emit(t,e.payload);let i=this.messageHandlers.get(e.type);i&&i.forEach(r=>{try{r(e.payload)}catch(o){this.options.debug&&console.error("[Beacon SDK] Message handler error:",o)}})}waitForBeaconReady(){return(0,Oe.default)(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let i=this.options.timeout,r=setTimeout(()=>{t(new ve("beacon ready",i))},i),o=this.on("ready",()=>{clearTimeout(r),o.dispose(),e()})}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(e,t)=>{if(this.options.debug){let i=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,i)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new w("MessagePort not available - channel not established");let i={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(i),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",i.type,i.payload)}catch(r){throw new w(`Failed to send message via port: ${r instanceof Error?r.message:String(r)}`)}}async sendAndWaitFor(e,t,i={},r){return await this.ready(),(0,Oe.default)(async o=>new Promise((s,a)=>{let c=r||this.options.timeout,h=setTimeout(()=>{u.dispose();let l=new ve(e,c);a(l)},c),u=this.eventEmitter.listen(t,l=>{clearTimeout(h),u.dispose(),s(l)});try{this.sendMessage(e,i)}catch(l){clearTimeout(h),u.dispose(),l instanceof w?a(l):o(l)}}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(o,s)=>{if(this.options.debug){let a=o instanceof Error?o.message:String(o);console.warn(`[Beacon SDK] Retry attempt ${s} for ${e}:`,a)}}})}generateId(){return`sdk_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}emit(e,t){this.eventEmitter.emit(e,t)}start(){return this.isStarted?this.readyPromise||Promise.resolve():(this.isStarted=!0,this.readyPromise=this.waitForBeaconReady(),this.readyPromise)}async ready(){if(!this.isStarted)throw new M("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new M("Beacon ready promise is not available");return ce(this.readyPromise,this.options.timeout)}get isReady(){return this.isBeaconReady}on(e,t){return this.eventEmitter.listen(e,t)}once(e,t){this.eventEmitter.once(e,t)}async ping(){try{return await this.sendAndWaitFor("ping","pong",{timestamp:Date.now()}),!0}catch(e){return this.options.debug&&console.warn("[Beacon SDK] Ping failed:",e),!1}}async getDebugInfo(){return this.sendAndWaitFor("getDebugInfo","debugInfo")}async getConsoleEvents(){return this.sendAndWaitFor("getConsoleEvents","consoleEvents")}async getErrorEvents(){return this.sendAndWaitFor("getErrorEvents","errorEvents")}async clearConsole(){await this.ready(),this.sendMessage("clearConsole")}async clearErrors(){await this.ready(),this.sendMessage("clearErrors")}async executeCode(e){return this.sendAndWaitFor("executeCode","codeExecutionResult",{code:e})}async inspectElement(e){return this.sendAndWaitFor("inspectElement","elementInspectionResult",{selector:e})}async fetch(e){return this.sendAndWaitFor("fetch","fetchResult",e)}async debug(e,t){let i=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==i&&(this.navigator.visit(i),await this.ready()),t&&await this.wait(t);let r=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,r)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new w("Iframe not available");try{let t=new URL(e,this.iframe.src||window.location.origin);this.iframe.src=t.href,this.isBeaconReady=!1,this.channelEstablished=!1,this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.isStarted&&(this.readyPromise=this.waitForBeaconReady())}catch{throw new w(`Invalid URL: ${e}`)}}get url(){return this.iframe.src}get element(){return this.iframe}dispose(){this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.disposables.forEach(e=>e.dispose()),this.disposables=[],this.messageHandlers.clear(),this.isBeaconReady=!1,this.channelEstablished=!1,this.isStarted=!1,this.readyPromise=null}};function Et(n,e){return new Fe(n,e)}function cn(){try{return kt(),!0}catch{return!1}}function wi(n){return Array.isArray(n)?n:Object.entries(n).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var We=class extends Error{constructor(t,i={}){super(t);this.message=t;this.data=i;this.name="NotebookInitError"}},$e=class extends Error{constructor(t,i){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${i}`);this.response=t;this.body=i;this.status=t.status}},Ke=class{constructor(e){this.client=e;this.secrets=new He(e),this.previewAuth=new Ge(e)}async create(e,t={},i=!0){let r=await this.client.post("/notebook",{template:e,...t}),o=new I(r.data,this.client);return i?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new I(t.data,this.client)}async update(e,t={}){let i=await this.client.put(`/notebook/${e}`,t);return new I(i.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e){let t=await this.client.post(`/notebook/${e}/fork`);return this.init(new I(t.data,this.client))}async open(e){let t=await this.client.get(`/notebook/${e}`);return new I(t.data,this.client)}openFromData(e){return this.init(new I(e,this.client))}async init(e){return await e.ready(),e}},ze=class{constructor(e,t="https://api.phpsandbox.io/v1",i={}){this.fetch=globalThis.fetch;this.notebook=new Ke(this),this.options=Object.assign({startClosed:!0},i),this.baseUrl=t,i.fetch&&(this.fetch=i.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t?JSON.stringify(t):void 0})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t?JSON.stringify(t):void 0})}async makeRequest(e,t,i){let r=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...i,headers:this.headers}));if(!r.ok)throw new $e(r,await r.text());if(r.status===204)return{data:void 0};let o=await r.text();return{data:o===""?void 0:JSON.parse(o)}}},St=class extends ze{},He=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,i){let r=typeof i=="string"?{name:t,value:i}:{name:t,...i};return(await this.client.put(`/notebook/${e}/secrets`,r)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:wi(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ge=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview-auth`)).data}async set(e,t){return(await this.client.put(`/notebook/${e}/preview-auth`,t)).data}async delete(e){await this.client.delete(`/notebook/${e}/preview-auth`)}},C,ne,qe,I=class{constructor(e,t){this.data=e;this.client=t;O(this,ne);this.initialized=!1;O(this,C);this.disposables=[];this.emitter=U.createInstance(),this.socket=new te(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),xe(this,C,k(this,ne,qe).call(this)),this.file=new ae(this),this.terminal=new W(this),this.auth=new K(this),this.lsp=new z(this),this.composer=new H(this),this.log=new G(this),this.repl=new Q(this),this.container=new $(this),this.laravel=new q(this),this.shell=new V(this),this.git=new ie(this),this.services=new X(this),this.secrets=new Qe(t,this.data.id),this.previewAuth=new Ve(t,this.data.id)}async ready(){let e=this.socket.getTerminalError();if(e)throw e;return(async()=>(this.client.options.startClosed&&!this.socket.isConnected&&await this.socket.connect(),se(this,C)))()}fork(){return this.client.notebook.fork(this.data.id)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new E("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},i={}){return this.socket.invoke(e,t||{},i)}ping(){return this.invoke("ping")}listen(e,t){let i=this.emitter.listen(e,t);return this.disposables.push(i),i}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>i(new Error("Connection closed"))),this.socket.onDidBootError(r=>i(r))}catch(r){i(r)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(r=>i(r))}catch(r){i(r)}})}watchConnection(){this.socket.onDidConnect(()=>{this.socket.emit("okra.connected"),this.client.options.telemetry&&this.container.enableTelemetry(this.client.options.telemetry)}),this.socket.onDidClose(()=>{this.socket.emit("okra.disconnected"),this.initialized=!1}),this.socket.onDidBootError(e=>{this.socket.emit("okra.boot_error",e),this.socket.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){this.socket.removeListener("okra.connected",e);let t=this.socket.listen("okra.connected",e);return this.disposables.push(t),t}onDidDisconnect(e){let t=this.socket.listen("okra.disconnected",e);return this.disposables.push(t),t}onDidBootError(e){let t=this.socket.listen("okra.boot_error",e);return this.disposables.push(t),t}update(){return this.invoke("notebook.update")}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.whenConnected();return this.socket.reconnect(),this.initialized=!1,await e,k(this,ne,qe).call(this),this.ready().then(()=>this)}async beacon(e,t){let i=await this.ready();return e.src=i.data.previewUrl,Et(e,t)}};C=new WeakMap,ne=new WeakSet,qe=function(){return xe(this,C,new Promise((e,t)=>{let i=this.onDidInitialize(o=>{if(r.dispose(),i.dispose(),this.initialized=o,o.type==="error"){t(new We(o.message,o.data));return}e(o)}),r=this.onDidBootError(o=>{i.dispose(),r.dispose(),t(o)})})),se(this,C).catch(()=>{}),se(this,C)};var Qe=class{constructor(e,t){this.client=e;this.notebookId=t}list(){return this.client.notebook.secrets.list(this.notebookId)}set(e,t){return this.client.notebook.secrets.set(this.notebookId,e,t)}setMany(e){return this.client.notebook.secrets.setMany(this.notebookId,e)}delete(e){return this.client.notebook.secrets.delete(this.notebookId,e)}},Ve=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.previewAuth.get(this.notebookId)}set(e){return this.client.notebook.previewAuth.set(this.notebookId,e)}disable(){return this.client.notebook.previewAuth.delete(this.notebookId)}};export{$e as ApiError,Fe as Beacon,w as BeaconConnectionError,M as BeaconError,ve as BeaconTimeoutError,ze as Client,Te as CommandError,y as ErrorEvent,Nt as FileChangeType,At as FileType,ae as Filesystem,ke as FilesystemError,Rt as FilesystemErrorType,Se as LspConnection,re as Navigator,Ke as NotebookApi,We as NotebookInitError,I as NotebookInstance,Ve as NotebookPreviewAuth,Ge as NotebookPreviewAuthApi,He as NotebookSecretApi,Qe as NotebookSecrets,Ut as NotebookState,E as NotebookUnavailableError,St as PHPSandbox,Ze as PHPSandboxError,_ as PromiseTimeoutError,L as RateLimitError,F as SendTimeoutError,te as Transport,Et as createBeacon,cn as isBeaconSupported,Lt as notebookBuiltinServices,qi as notebookKnownServices,le as once,ce as timeout};
1
+ var Ct=Object.create;var Ye=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Dt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var je=r=>{throw TypeError(r)};var oe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Nt=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pt(e))!At.call(r,n)&&n!==t&&Ye(r,n,{get:()=>e[n],enumerable:!(i=_t(e,n))||i.enumerable});return r};var Ze=(r,e,t)=>(t=r!=null?Ct(Dt(r)):{},Nt(e||!r||!r.__esModule?Ye(t,"default",{value:r,enumerable:!0}):t,r));var we=(r,e,t)=>e.has(r)||je("Cannot "+t);var se=(r,e,t)=>(we(r,e,"read from private field"),t?t.call(r):e.get(r)),O=(r,e,t)=>e.has(r)?je("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),xe=(r,e,t,i)=>(we(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),k=(r,e,t)=>(we(r,e,"access private method"),t);var pt=oe((Rn,ht)=>{function b(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}ht.exports=b;b.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};b.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};b.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},t),this._options.unref&&this._timer.unref(),!0};b.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};b.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};b.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};b.prototype.start=b.prototype.try;b.prototype.errors=function(){return this._errors};b.prototype.attempts=function(){return this._attempts};b.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,i=0;i<this._errors.length;i++){var n=this._errors[i],o=n.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=n,t=s)}return e}});var dt=oe(D=>{var ci=pt();D.operation=function(r){var e=D.timeouts(r);return new ci(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};D.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],n=0;n<e.retries;n++)i.push(this.createTimeout(n,e));return r&&r.forever&&!i.length&&i.push(this.createTimeout(n,e)),i.sort(function(o,s){return o-s}),i};D.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,i=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return i=Math.min(i,e.maxTimeout),i};D.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var i in r)typeof r[i]=="function"&&t.push(i)}for(var n=0;n<t.length;n++){var o=t[n],s=r[o];r[o]=function(c){var h=D.operation(e),u=Array.prototype.slice.call(arguments,1),l=u.pop();u.push(function(d){h.retry(d)||(d&&(arguments[0]=h.mainError()),l.apply(this,arguments))}),h.attempt(function(){c.apply(r,u)})}.bind(r,s),r[o].options=e}}});var ft=oe((Ln,mt)=>{mt.exports=dt()});var Re=oe((Mn,gt)=>{var li=ft();function ui(r,e){function t(i,n){var o=e||{},s;"randomize"in o||(o.randomize=!0),s=li.operation(o);function a(u){n(u||new Error("Aborted"))}function c(u,l){if(u.bail){a(u);return}s.retry(u)?o.onRetry&&o.onRetry(u,l):n(s.mainError())}function h(u){var l;try{l=r(a,u)}catch(d){c(d,u);return}Promise.resolve(l).then(i).catch(function(f){c(f,u)})}s.attempt(h)}return new Promise(t)}gt.exports=ui});var y=class extends Error{constructor(t,i,n={}){super(i);this.code=t;this.message=i;this.raw=n}},L=class extends y{constructor(e,t={}){super(429,e,t)}},et=class extends y{};var tt="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var g=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=tt[t[r]&63];return e};var Rt=(n=>(n[n.Unknown=0]="Unknown",n[n.File=1]="File",n[n.Directory=2]="Directory",n[n.SymbolicLink=64]="SymbolicLink",n))(Rt||{}),Ut=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(Ut||{}),Lt=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(Lt||{}),ke=class extends y{constructor(t,i){super(t.code,t.message);this.name=i}},Ee=class{constructor(e,t,i){this.path=e;this.okra=t;this.disposable=i}dispose(){this.okra.invoke("fs.unwatch",{path:this.path}),this.disposable.dispose()}},ae=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t,onDidChange:i}of this.watches.values())this.watch(e,t,i)})}info(e){return this.okra.invoke("fs.info",{path:e})}write(e,t){return this.okra.invoke("fs.write",{path:e,contents:t})}find(e,t={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:Object.assign(t,{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1})})}search(e,t,i){e.id||(e.id=g());let n={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,s=async c=>{c===!1&&a.dispose(),i&&await Promise.resolve(i(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...n,...t}}).finally(()=>a.dispose())}mkdir(e){return this.okra.invoke("fs.mkdir",{path:e})}move(e,t){return this.okra.invoke("fs.move",{from:e,to:t})}remove(e,t){return this.okra.invoke("fs.remove",{path:e,type:t})}async readFile(e,t){try{let i=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return i instanceof Uint8Array?i:typeof i=="string"?new TextEncoder().encode(i):i}catch(i){this.handleError(i)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(i=>this.handleError(i))}writeFile(e,t,i){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:i}).catch(n=>this.handleError(n))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,i){return this.okra.invoke("fs.rename",{from:e,to:t,options:i}).catch(n=>this.handleError(n))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(i=>this.handleError(i))}copy(e,t,i){return this.okra.invoke("fs.copy",{source:e,destination:t,options:i}).catch(n=>this.handleError(n))}readDirectory(e,t=[],i=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:i}).catch(n=>this.handleError(n))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,i){let n=this.okra.listen(`fs.watch.${e}`,i),o={dispose:()=>{n.dispose(),this.okra.invoke("fs.unwatch",{path:e})}},s=new Ee(e,this.okra,o);return this.watches.set(e,{options:t,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>s)}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,i){let n=g(),o=!!e,s=[];return this.okra.listen(`fs.download.${n}`,o?e:a=>{s.push(a)}),this.okra.invoke("fs.download",{id:n,exclude:t,include:i}).then(()=>new Blob(s,{type:"application/octet-stream"}))}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof y&&"name"in e.raw?new ke(e,e.raw.name):e}};var _=class extends Error{constructor(t,i){super(t);this.time=i}},F=class r extends _{static fromPromiseTimeoutError(e){return new r(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",i={}){super(t);this.raw=i;this.name="NotebookUnavailableError"}};var ce=(r,e)=>{let t;return Promise.race([r,new Promise((i,n)=>t=setTimeout(n,e,new _("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},le=r=>{let e=null;return()=>e||(e=r())};var $=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}start(){return this.okra.invoke("terminal.start")}create(e){return this.okra.invoke("terminal.create",e)}onStarted(e){this.okra.listen("terminal.started",e)}resize(e,t){return this.okra.invoke("terminal.resize",{id:e,width:t[0],height:t[1]})}onOutput(e,t){this.okra.listen(`terminal.output.${e}`,t)}input(e,t){return this.okra.invoke("terminal.input",{id:e,input:t})}listen(e,t){return this.okra.listen(e,t)}async spawn(e,t,i){let n=i?.id||g(),o=new Set,s=()=>{for(let v of o)v.dispose();o.clear()},a=new WritableStream({write:v=>{this.input(n,v)},close:s}),c=null,h=new ReadableStream({start:v=>{c=v,o.add(this.listen(`terminal.output.${n}`,ye=>{c?.enqueue(ye.output)}))},cancel:()=>{c=null,s()}}),u=new Promise(v=>{o.add(this.listen(`terminal.close.${n}`,ye=>{if(c)try{c.close()}catch{}s(),v(ye.exitCode)}))}),l=le(()=>(s(),this.okra.invoke("terminal.close",{id:n}))),d=v=>{this.okra.invoke("terminal.resize",{id:n,width:v.cols,height:v.rows})},{abortSignal:f,...p}=i??{};f&&f.addEventListener("abort",l);let x=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:n,...p}},{abortSignal:f});return{exit:u,input:a,output:h,kill:l,resize:d,...x}}};var Mt=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(Mt||{}),W=class{constructor(e){this.okra=e}start(){return this.okra.invoke("container.start")}stop(){return this.okra.invoke("container.stop")}state(){return this.okra.invoke("container.state")}openedPorts(){return this.okra.invoke("container.opened-ports")}setPhp(e){return this.okra.invoke("container.set-php",{version:e})}enableTelemetry(e){return this.okra.invoke("container.stream-telemetry",{features:Array.from(e)})}stopTelemetry(){return this.okra.invoke("container.stop-telemetry")}listen(e,t){return this.okra.listen(e,t)}onPort(e){let t=[];return this.listen("container.ports",i=>{for(let n of i)t.some(o=>o.port===n.port)||e(n,"open");for(let n of t)i.some(o=>o.port===n.port)||e(n,"close");t=i})}};var K=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var H=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,i){this.okra.listen(`${t}.${e}`,n=>i(n))}onClose(e,t){this.listen(e,"lsp.closed",i=>t(i.code,i.reason))}onError(e,t){this.listen(e,"lsp.error",i=>t(i.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",i=>t(JSON.stringify(i)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return Se.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},Se=class r{constructor(e,t){this.id=e;this.lsp=t}send(e){return this.lsp.message(this.id,e)}onMessage(e){this.lsp.onResponse(this.id,e)}onError(e){this.lsp.onError(this.id,e)}onClose(e){this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,t){return new r(e,t)}};var z=class{constructor(e){this.okra=e}invoke(e,t={},i={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:i})}dumpAutoload(){return this.okra.invoke("composer.dump-autoload")}install(e={}){return this.invoke("install",{},e)}update(e,t={}){return this.invoke("update",e,t)}require(e,t={}){return this.invoke("require",e,t)}remove(e,t={}){return this.invoke("remove",e,t)}stream(e){return this.okra.listen("composer.log",e)}packages(){return this.okra.invoke("composer.packages")}};var G=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){this.okra.listen(e,t)}};var q=class{constructor(e){this.okra=e}maintenanceInfo(){return this.okra.invoke("laravel.maintenance.info",{})}toggleMaintenance(e){return this.okra.invoke("laravel.maintenance.toggle",e)}};var Q=class{constructor(e){this.okra=e}eval(e,t="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:i})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}start(){return this.okra.invoke("repl.start")}resize(e,t){return this.okra.invoke("repl.resize",{cols:e,rows:t})}listen(e,t){this.okra.listen(e,t)}onOutput(e){this.okra.listen("repl.output",e)}};function it(r,e=[],t){let i=Array.isArray(e)?e:[],n=Array.isArray(e)?t:e;return{command:Array.isArray(r)?r:i.length>0?[r,...i]:r,opts:n}}var Te=class extends Error{constructor(t,i){super(t);this.output=t;this.exitCode=i}},Ie=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new Te(this.output,this.exitCode);return this}},V=class{constructor(e){this.okra=e}onOutput(e,t){this.okra.listen(`shell.output.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}async exec(e,t=[],i){let n=it(e,t,i),{abortSignal:o,...s}=n.opts??{},a=await this.okra.invoke("shell.exec",{command:n.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new Ie(a.output,a.exitCode)}execStream(e,t=[],i){let n=it(e,t,i),o=n.opts?.id||g(),s=new Set,a=null,c=!1,h=()=>{for(let p of s)p.dispose();s.clear()},u=()=>{if(!c&&(c=!0,h(),a))try{a.close()}catch{}},l=p=>{c||(c=!0,h(),a&&a.error(p))},d=new ReadableStream({start:p=>{a=p,s.add(this.listen(`shell.output.${o}`,x=>{a?.enqueue(x.output)}))},cancel:()=>{c=!0,h()}}),f=this.exec(n.command,{...n.opts,id:o}).then(p=>(u(),p)).catch(p=>{throw l(p),p});return{output:d,result:f}}};var Bt=["redis"],Xi=["start","nginx",...Bt],X=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,t){return this.okra.invoke("service.run",{name:e,command:t})}stop(e){return this.okra.invoke("service.stop",{name:e})}onLog(e,t){return this.okra.listen(`service.log.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}logs(e,t={}){return t.follow?this.followLogs(e,t):this.okra.invoke("service.logs",{name:e,tail:t.tail}).then(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,t){let i=t.id||g(),n=new Set,o=null,s=!1,a=()=>{for(let d of n)d.dispose();n.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},h=d=>{s||(s=!0,a(),o&&o.error(d))},u=le(()=>(c(),this.okra.invoke("service.stop-logs",{id:i}))),l=new ReadableStream({start:d=>{o=d,n.add(this.onLog(i,f=>{o?.enqueue(f.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:i}).catch(f=>{h(f)})},cancel:()=>{u()}});return{id:i,output:l,stop:u}}};function nt(r){let e=r.length,t=0,i=0;for(;i<e;){let n=r.charCodeAt(i++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&i<e){let o=r.charCodeAt(i);(o&64512)===56320&&(++i,n=((n&1023)<<10)+(o&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function Ot(r,e,t){let i=r.length,n=t,o=0;for(;o<i;){let s=r.charCodeAt(o++);if((s&4294967168)===0){e[n++]=s;continue}else if((s&4294965248)===0)e[n++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<i){let a=r.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[n++]=s>>12&15|224,e[n++]=s>>6&63|128):(e[n++]=s>>18&7|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128)}e[n++]=s&63|128}}var Ft=new TextEncoder,$t=50;function Wt(r,e,t){Ft.encodeInto(r,e.subarray(t))}function rt(r,e,t){r.length>$t?Wt(r,e,t):Ot(r,e,t)}var Kt=4096;function Ce(r,e,t){let i=e,n=i+t,o=[],s="";for(;i<n;){let a=r[i++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=r[i++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=r[i++]&63,h=r[i++]&63;o.push((a&31)<<12|c<<6|h)}else if((a&248)===240){let c=r[i++]&63,h=r[i++]&63,u=r[i++]&63,l=(a&7)<<18|c<<12|h<<6|u;l>65535&&(l-=65536,o.push(l>>>10&1023|55296),l=56320|l&1023),o.push(l)}else o.push(a);o.length>=Kt&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var Ht=new TextDecoder,zt=200;function Gt(r,e,t){let i=r.subarray(e,e+t);return Ht.decode(i)}function ot(r,e,t){return t>zt?Gt(r,e,t):Ce(r,e,t)}var P=class{constructor(e,t){this.type=e,this.data=t}};var m=class r extends Error{constructor(e){super(e);let t=Object.create(r.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:r.name})}};function st(r,e,t){let i=t/4294967296,n=t;r.setUint32(e,i),r.setUint32(e+4,n)}function ue(r,e,t){let i=Math.floor(t/4294967296),n=t;r.setUint32(e,i),r.setUint32(e+4,n)}function he(r,e){let t=r.getInt32(e),i=r.getUint32(e+4);return t*4294967296+i}function at(r,e){let t=r.getUint32(e),i=r.getUint32(e+4);return t*4294967296+i}var qt=-1,Qt=4294967296-1,Vt=17179869184-1;function Xt({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Vt)if(e===0&&r<=Qt){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{let t=r/4294967296,i=r&4294967295,n=new Uint8Array(8),o=new DataView(n.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,i),n}else{let t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),ue(i,4,r),t}}function Jt(r){let e=r.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,n=Math.floor(i/1e9);return{sec:t+n,nsec:i-n*1e9}}function Yt(r){if(r instanceof Date){let e=Jt(r);return Xt(e)}else return null}function jt(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),i=e.getUint32(4),n=(t&3)*4294967296+i,o=t>>>2;return{sec:n,nsec:o}}case 12:{let t=he(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new m(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Zt(r){let e=jt(r);return new Date(e.sec*1e3+e.nsec/1e6)}var ct={type:qt,encode:Yt,decode:Zt};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ct)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){let n=this.builtInEncoders[i];if(n!=null){let o=n(e,t);if(o!=null){let s=-1-i;return new P(s,o)}}}for(let i=0;i<this.encoders.length;i++){let n=this.encoders[i];if(n!=null){let o=n(e,t);if(o!=null){let s=i;return new P(s,o)}}}return e instanceof P?e:null}decode(e,t,i){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,i):new P(t,e)}};S.defaultCodec=new S;function ei(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function J(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):ei(r)?new Uint8Array(r):Uint8Array.from(r)}var ti=100,ii=2048,pe=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??S.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??ti,this.initialBufferSize=e?.initialBufferSize??ii,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),i=new Uint8Array(t),n=new DataView(t);i.set(this.bytes),this.view=n,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let i=nt(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),rt(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let i=J(e);this.writeU8a(i)}encodeArray(e,t){let i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(let n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let i=0;for(let n of t)e[n]!==void 0&&i++;return i}encodeMap(e,t){let i=Object.keys(e);this.sortKeys&&i.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let o of i){let s=e[o];this.ignoreUndefined&&s===void 0||(this.encodeString(o),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),n=i.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(i);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),st(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ue(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function _e(r,e){return new pe(e).encodeSharedRef(r)}function de(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var ni=16,ri=16,me=class{constructor(e=ni,t=ri){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){let n=this.caches[i-1];e:for(let o of n){let s=o.bytes;for(let a=0;a<i;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let i=this.caches[e.length-1],n={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=n:i.push(n)}decode(e,t,i){let n=this.find(e,t,i);if(n!=null)return this.hit++,n;this.miss++;let o=Ce(e,t,i),s=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(s,o),o}};var Pe="array",Z="map_key",ut="map_value",oi=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new m("The type of key must be string or number but "+typeof r)},De=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Pe,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=Z,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Pe){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Z||e.type===ut){let i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},j=-1,Ae=new DataView(new ArrayBuffer(0)),si=new Uint8Array(Ae.buffer);try{Ae.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var lt=new RangeError("Insufficient data"),ai=new me,fe=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Ae,this.bytes=si,this.headByte=j,this.stack=new De,this.entered=!1,this.extensionCodec=e?.extensionCodec??S.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:ai,this.mapKeyConverter=e?.mapKeyConverter??oi}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=j,this.stack.reset()}setBuffer(e){let t=J(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===j&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),i=J(e),n=new Uint8Array(t.length+i.length);n.set(t),n.set(i,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,i;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}let{headByte:n,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${de(n)} at ${s} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let i=t,n=-1;for await(let o of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(n=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new m(`Unrecognized type byte: ${de(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let n=i.top();if(n.type===Pe)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,i.release(n);else continue e;else if(n.type===Z){if(t==="__proto__")throw new m("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=ut;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,i.release(n);else{n.key=null,n.type=Z;continue e}}return t}}readHeadByte(){return this.headByte===j&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=j}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new m(`Unrecognized array type byte: ${de(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new m(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new m(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new m(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw lt;let i=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,i,e):n=ot(this.bytes,i,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Z:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new m(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw lt;let i=this.pos+t,n=this.bytes.subarray(i,i+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new m(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=at(this.view,this.pos);return this.pos+=8,e}readI64(){let e=he(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Ne(r,e){return new fe(e).decode(r)}var kt=Ze(Re(),1);var Ue=function(r,e){return Ue=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])},Ue(r,e)};function bt(r,e){Ue(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function hi(r){var e=typeof Symbol=="function"&&r[Symbol.iterator],t=0;return e?e.call(r):{next:function(){return r&&t>=r.length&&(r=void 0),{value:r&&r[t++],done:!r}}}}function pi(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),n,o=[],s;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)o.push(n.value)}catch(a){s={error:a}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(s)throw s.error}}return o}function di(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(pi(arguments[e]));return r}var vt=(function(){function r(e,t){this.target=t,this.type=e}return r})(),mi=(function(r){bt(e,r);function e(t,i){var n=r.call(this,"error",i)||this;return n.message=t.message,n.error=t,n}return e})(vt),fi=(function(r){bt(e,r);function e(t,i,n){t===void 0&&(t=1e3),i===void 0&&(i="");var o=r.call(this,"close",n)||this;return o.wasClean=!0,o.code=t,o.reason=i,o}return e})(vt);var gi=function(){if(typeof WebSocket<"u")return WebSocket},bi=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},A={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},vi=(function(){function r(e,t,i){var n=this;i===void 0&&(i={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){n._debug("open event");var s=n._options.minUptime,a=s===void 0?A.minUptime:s;clearTimeout(n._connectTimeout),n._uptimeTimeout=setTimeout(function(){return n._acceptOpen()},a),n._ws.binaryType=n._binaryType,n._messageQueue.forEach(function(c){return n._ws.send(c)}),n._messageQueue=[],n.onopen&&n.onopen(o),n._listeners.open.forEach(function(c){return n._callEventListener(o,c)})},this._handleMessage=function(o){n._debug("message event"),n.onmessage&&n.onmessage(o),n._listeners.message.forEach(function(s){return n._callEventListener(o,s)})},this._handleError=function(o){n._debug("error event",o.message),n._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),n.onerror&&n.onerror(o),n._debug("exec error listeners"),n._listeners.error.forEach(function(s){return n._callEventListener(o,s)}),n._connect()},this._handleClose=function(o){n._debug("close event"),n._clearTimeouts(),n._shouldReconnect&&n._connect(),n.onclose&&n.onclose(o),n._listeners.close.forEach(function(s){return n._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(r,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CONNECTING",{get:function(){return r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"OPEN",{get:function(){return r.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSING",{get:function(){return r.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSED",{get:function(){return r.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(t,i){return typeof i=="string"?t+=i.length:i instanceof Blob?t+=i.size:t+=i.byteLength,t},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?r.CLOSED:r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),r.prototype.close=function(e,t){if(e===void 0&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,t)},r.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,t),this._connect())},r.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,i=t===void 0?A.maxEnqueuedMessages:t;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},r.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},r.prototype.dispatchEvent=function(e){var t,i,n=this._listeners[e.type];if(n)try{for(var o=hi(n),s=o.next();!s.done;s=o.next()){var a=s.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}return!0},r.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==t}))},r.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,di(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,i=t===void 0?A.reconnectionDelayGrowFactor:t,n=e.minReconnectionDelay,o=n===void 0?A.minReconnectionDelay:n,s=e.maxReconnectionDelay,a=s===void 0?A.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(i,this._retryCount-1),c>a&&(c=a)),this._debug("next delay",c),c},r.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},r.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var t=e();if(typeof t=="string")return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},r.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var t=this._options,i=t.maxRetries,n=i===void 0?A.maxRetries:i,o=t.connectionTimeout,s=o===void 0?A.connectionTimeout:o,a=t.WebSocket,c=a===void 0?gi():a;if(this._retryCount>=n){this._debug("max retries reached",this._retryCount,">=",n);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!bi(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(h){e._closeCalled||(e._debug("connect",{url:h,protocols:e._protocols}),e._ws=e._protocols?new c(h,e._protocols):new c(h),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},s))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new mi(Error("TIMEOUT"),this))},r.prototype._disconnect=function(e,t){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new fi(e,t,this))}catch{}}},r.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},r.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},r.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},r.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},r.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},r})(),yt=vi;var yi=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},wi=r=>{try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return r}},wt=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return;let e=r,t=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!t)return;let i=typeof e.name=="string"&&e.name?e.name:void 0;return i?`${i}: ${t}`:t},ee=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return String(r);let e=r,t=[],i=wt(e);i&&t.push(i);let n=wt(e.error);n&&n!==i&&t.push(`error=${n}`),typeof e.type=="string"&&e.type&&t.push(`type=${e.type}`),typeof e.code=="number"&&t.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==i&&t.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&t.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&t.push(`url=${wi(o.url)}`);let s=yi(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var M=null;typeof WebSocket<"u"?M=WebSocket:typeof MozWebSocket<"u"?M=MozWebSocket:typeof global<"u"?M=global.WebSocket||global.MozWebSocket:typeof window<"u"?M=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(M=self.WebSocket||self.MozWebSocket);var xt=M;var ge=class{constructor(){this.disposables=new Map}add(e,t){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof t=="function"&&(t=t()),this.disposables.set(e,t)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var Le=class extends Error{constructor(e="WebSocket connection timeout"){super(e),this.name="ConnectionTimeoutError"}},be=class extends Error{constructor(t,i){super(t);this.originalError=i;this.name="ConnectionFailedError"}},N=class extends Error{constructor(t,i){super(t);this.data=i;this.name="InvalidMessageError"}},R=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},T,Me,Be,te=class{constructor(e,t,i={}){this.eventEmitter=t;this.options=i;O(this,T);this.clientId="";this.closed=!1;this.disposables=new ge;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.connectionStats={connectTime:0,reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:0};this.messageQueue=[];this.MAX_QUEUE_SIZE=100;this.QUEUE_TIMEOUT=3e4;this.rateLimiter={requests:[],maxRequests:50,windowMs:1e3};this.validateConfiguration(i),this.url=new URL(e),this.PING_INTERVAL=i.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=i.connectWaitTimeout??3e4,this.connectionStats.connectionStartTime=Date.now();let n=i.startClosed!==!1;this.rws=new yt(this.url.toString(),[],{WebSocket:i.webSocket??globalThis.WebSocket??xt,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:n}),this.log("debug","Transport initialized",{url:this.url.toString(),options:i}),this.registerWatchers(),this.setupConnectionHealthMonitoring(),this.startPeriodicMaintenance()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new R("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new R("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new R("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new R("maxRetries must be between 0 and 100")}log(e,t,i){if(this.options.debug){let n=new Date().toISOString(),o=i?JSON.stringify(i,null,2):"";console[e](`[Transport ${n}] ${t}${o?`
2
+ `+o:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):k(this,T,Me).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{if(!(t.data instanceof Blob)){let i=new Error("Unexpected message type: "+typeof t.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:i.message,messageType:typeof t.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:i,rawMessage:t.data,timestamp:Date.now()});return}t.data.arrayBuffer().then(i=>{if(i.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}try{this.handleRawMessage(Ne(i)).catch(n=>{this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:n instanceof Error?n.message:String(n),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:n,rawMessage:i,timestamp:Date.now()})})}catch(n){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:n instanceof Error?n.message:String(n),byteLength:i.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:n,rawMessage:i,timestamp:Date.now()})}})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:i,as:n}=e;if(!i||typeof i!="string")throw new N("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!t}),i==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let o=new E(t?.message||"Notebook is no longer available",t||{});this.log("error","Boot error received",{data:t}),this.terminate(o,4e3,o.message);return}if(i==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new N("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(i==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new N("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(i,t,n)}catch(t){this.connectionStats.totalErrors++,t instanceof N?this.log("error","Invalid message format",{error:t.message,data:t.data,totalErrors:this.connectionStats.totalErrors}):this.log("error","Failed to parse message",{ev:e,error:t instanceof Error?t.message:String(t),totalErrors:this.connectionStats.totalErrors}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:t,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,t,i){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(i||e,t)}listen(e,t,i){return this.eventEmitter.listen(e,t)}onDidBootError(e){this.eventEmitter.listen("transport.boot_error",t=>{e(t.error)})}removeListener(e,t){this.eventEmitter.removeListener(e,t)}listenOnce(e,t,i){this.eventEmitter.once(e,t,i),this.disposables.add(`once_${e}_${g()}`,{dispose:()=>{this.eventEmitter.removeListener(e,t)}})}emit(e,...t){this.eventEmitter.emit(e,...t)}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,t={},i={}){if(this.terminalError)throw this.terminalError;if(this.isRateLimited())throw new L("Rate limit exceeded - too many requests");this.clearOldQueuedMessages();let n=i.responseEvent||`${e}_${g()}_response`,o=`${n}_error`,s,a=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),this.eventEmitter.removeListener(n),this.eventEmitter.removeListener(o)},c=async(u,l)=>{if(this.terminalError){l(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted&&l(d),i.abortSignal&&i.abortSignal.addEventListener("abort",()=>{l(d)}),!this.isConnected&&!this.isClosed){if(this.log("debug","Connection not available, queuing message",{action:e}),this.messageQueue.length>=this.MAX_QUEUE_SIZE){let p=this.messageQueue.shift();p&&p.reject(new Error("Message queue full, oldest message dropped"))}this.messageQueue.push({action:e,data:t,options:i,resolve:u,reject:l,timestamp:Date.now()});return}let f=Date.now();this.listenOnce(n,p=>{let x=Date.now()-f;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+x)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:x,avgResponseTime:this.connectionStats.avgResponseTime}),u(p)}),this.listenOnce(o,p=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:p}),l(new y(p.code,p.message,p))}),s=p=>{if(p.code===1008&&(p.reason||"").includes("rate limit")){l(new L(p.reason||"Rate limit exceeded",p));return}let x=ee(p);l(this.terminalError||new be(`Connection lost to the notebook during request: ${x}`,p))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:n})),this.log("debug","Message sent",{action:e,data:t})}catch(p){throw this.log("error","Failed to send message",{action:e,error:p}),p}},h=async()=>{await k(this,T,Me).call(this);let u=new Promise(c).finally(a);return i.timeout?ce(u,i.timeout).catch(l=>{throw l instanceof _?F.fromPromiseTimeoutError(l):l}).finally(a):u};return this.sendWithRetry(async()=>await h(),i.retries||10)}pack(e){return new Blob([_e(e)])}sendWithRetry(e,t=10){return(0,kt.default)(async(i,n)=>{try{return await e()}catch(o){if(o instanceof y||o instanceof L||o instanceof R||o instanceof N||o instanceof E||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:n}),i(o);return}throw o instanceof F&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:n,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:n,error:o instanceof Error?o.message:String(o),nextDelay:this.getBackoffDelay(n-1)}),o}},{retries:t,onRetry:(i,n)=>{this.log("warn","Send operation retry",{attempt:n,maxRetries:t,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${g()}`),this.call("invoke",{action:e,data:t},i)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){if(this.closed){console.trace("Transport is already closed, cannot disconnect again");return}this.close()}terminate(e,t=4e3,i=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,i)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let i=this.messageQueue.length,n=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(o=>{o.reject(n)}),this.messageQueue=[],i>0&&this.log("debug",`Rejected ${i} queued messages due to connection close`),this.rateLimiter.requests=[],this.disposables.dispose();try{this.rws.close(e,t)}catch(o){this.log("error","Error closing WebSocket",{error:o instanceof Error?o.message:String(o)})}this.eventEmitter.emit("transport.closed",{code:e,reason:t,metrics:this.getConnectionMetrics(),timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}onDidConnect(e){this.rws.addEventListener("open",e),this.disposables.add("connect",{dispose:()=>{this.rws.removeEventListener("open",e)}})}onDidClose(e){this.rws.addEventListener("close",e),this.disposables.add("close",{dispose:()=>{this.rws.removeEventListener("close",e)}})}setupConnectionHealthMonitoring(){this.rws.addEventListener("open",()=>{this.connectionStats.connectTime=Date.now(),this.connectionStats.reconnectCount++,this.log("info","Connection established",{reconnectCount:this.connectionStats.reconnectCount,timeSinceStart:Date.now()-this.connectionStats.connectionStartTime}),this.processMessageQueue()}),this.rws.addEventListener("close",e=>{this.log("warn","Connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}),this.handleConnectionClose(e.code)}),this.rws.addEventListener("error",e=>{this.connectionStats.totalErrors++;let t=ee(e);this.log("error","Connection error",{error:t,rawError:e,totalErrors:this.connectionStats.totalErrors})})}handleConnectionClose(e){switch(e){case 1e3:return this.log("info","Normal connection closure"),"stop";case 1001:return this.log("info","Connection going away, will reconnect"),"reconnect";case 1006:return this.log("warn","Abnormal connection closure, will retry"),"retry";case 1008:return this.log("error","Connection closed due to policy violation"),this.clearOldQueuedMessages(),"stop";case 4e3:return this.log("info","Connection closed due to terminal notebook error"),"stop";default:return this.log("warn",`Unknown close code: ${e}, will reconnect`),"reconnect"}}processMessageQueue(){if(this.messageQueue.length===0)return;this.log("debug",`Processing ${this.messageQueue.length} queued messages`);let e=[...this.messageQueue];this.messageQueue=[];for(let t of e){if(Date.now()-t.timestamp>this.QUEUE_TIMEOUT){t.reject(new Error("Queued message timed out"));continue}this.call(t.action,t.data,t.options).then(t.resolve).catch(t.reject)}}clearOldQueuedMessages(){let e=Date.now(),t=this.messageQueue.length;this.messageQueue=this.messageQueue.filter(i=>{let n=e-i.timestamp>this.QUEUE_TIMEOUT;return n&&i.reject(new Error("Queued message expired")),!n}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}isRateLimited(){let e=Date.now();return this.rateLimiter.requests=this.rateLimiter.requests.filter(t=>e-t<this.rateLimiter.windowMs),this.rateLimiter.requests.length>=this.rateLimiter.maxRequests?!0:(this.rateLimiter.requests.push(e),!1)}getBackoffDelay(e){return Math.min(1e3*Math.pow(2,e),3e4)+Math.random()*1e3}getConnectionMetrics(){let e=Date.now(),t=this.connectionStats.connectTime>0?e-this.connectionStats.connectTime:0;return{status:this.status,clientId:this.clientId,isConnected:this.isConnected,isConnecting:this.isConnecting,connectionStats:{...this.connectionStats,connectionDuration:t,uptime:e-this.connectionStats.connectionStartTime,messagesPerSecond:t>0?(this.connectionStats.totalMessages/(t/1e3)).toFixed(2):"0",errorRate:this.connectionStats.totalMessages>0?(this.connectionStats.totalErrors/this.connectionStats.totalMessages*100).toFixed(2)+"%":"0%",timeSinceLastPing:this.connectionStats.lastPingTime>0?e-this.connectionStats.lastPingTime:0,timeSinceLastPong:this.connectionStats.lastPongTime>0?e-this.connectionStats.lastPongTime:0},messageQueue:{length:this.messageQueue.length,maxSize:this.MAX_QUEUE_SIZE,oldestMessageAge:this.messageQueue.length>0?e-Math.min(...this.messageQueue.map(i=>i.timestamp)):0},rateLimiter:{currentRequests:this.rateLimiter.requests.length,maxRequests:this.rateLimiter.maxRequests,windowMs:this.rateLimiter.windowMs,isLimited:this.isRateLimited()},config:{pingInterval:this.PING_INTERVAL,queueTimeout:this.QUEUE_TIMEOUT,url:this.url.toString()}}}getHealthStatus(){let t=this.getConnectionMetrics().connectionStats;return!this.isConnected||t.timeSinceLastPong>this.PING_INTERVAL*2||Number.parseFloat(t.errorRate)>50?"unhealthy":t.avgResponseTime>5e3||Number.parseFloat(t.errorRate)>10||t.timeSinceLastPong>this.PING_INTERVAL*1.5?"degraded":"healthy"}resetStats(){this.connectionStats={connectTime:Date.now(),reconnectCount:0,lastPingTime:0,lastPongTime:0,avgResponseTime:0,totalMessages:0,totalErrors:0,connectionStartTime:Date.now()},this.log("debug","Connection statistics reset")}async runDiagnostics(){let e=this.getConnectionMetrics(),t=this.getHealthStatus(),i=[],n=[];return this.isConnected||(i.push("Connection is not established"),n.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(i.push("No pong received recently - connection may be stale"),n.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(i.push(`High error rate: ${e.connectionStats.errorRate}`),n.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(i.push("Message queue is nearly full"),n.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(i.push("High average response time"),n.push("Check network latency and server performance")),e.rateLimiter.isLimited&&(i.push("Rate limiting is active"),n.push("Reduce request frequency or increase rate limit")),this.log("info","Connection diagnostics completed",{status:t,issueCount:i.length,recommendationCount:n.length}),{status:t,metrics:e,issues:i,recommendations:n}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{this.clearOldQueuedMessages();let t=Date.now();if(this.rateLimiter.requests=this.rateLimiter.requests.filter(i=>t-i<this.rateLimiter.windowMs),this.options.debug){let i=this.getHealthStatus(),n=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:i,messageCount:n.connectionStats.totalMessages,errorCount:n.connectionStats.totalErrors,queueLength:n.messageQueue.length})}},3e5);return{dispose:()=>{clearInterval(e)}}})}};T=new WeakSet,Me=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,t)=>{if(this.isConnected){e(),k(this,T,Be).call(this);return}let i,n=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(i)},s=()=>{o(),this.connectPromise=null,e(),k(this,T,Be).call(this)},a=h=>{n+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:n,error:ee(h)})},c=h=>{let u=ee(h);if("code"in h&&(h.code===1008||h.code===4e3)){o(),this.connectPromise=null,t(new be(`WebSocket connection failed: ${u}`,h));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:u})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),i=setTimeout(()=>{o(),this.connectPromise=null,t(new Le(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},Be=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.connectionStats.lastPingTime=Date.now(),this.log("debug","Sending periodic ping");let t=Date.now();await this.invoke("ping"),this.connectionStats.lastPongTime=Date.now();let i=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:i})}catch(t){this.log("error","Ping failed",{error:t instanceof Error?t.message:String(t)}),Date.now()-this.connectionStats.lastPongTime>this.PING_INTERVAL*3&&(this.log("warn","Connection appears dead, forcing reconnection"),this.rws.reconnect())}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function Et(r){return{all:r=r||new Map,on:function(e,t){var i=r.get(e);i?i.push(t):r.set(e,[t])},off:function(e,t){var i=r.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var i=r.get(e);i&&i.slice().map(function(n){n(t)}),(i=r.get("*"))&&i.slice().map(function(n){n(e,t)})}}}function xi(r){let e=Et(r);return e.once=(t,i)=>{e.on(t,i),e.on(t,e.off.bind(e,t,i))},e}var U=class r{constructor(){this.emitter=xi()}listen(e,t){let i=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:i}}emit(e,t){this.emitter.emit(e,t)}once(e,t){this.emitter.once(e,t)}static make(){return new r}static refresh(){return new r}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new r}inspect(){return this.emitter.all}};var ie=class{constructor(e){this.okra=e}checkpoint(e,t,i="main",n=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:i,allowEmpty:n})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,i="main",n,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:i,token:n,direction:o,force:s})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}};var Oe=Ze(Re(),1);var ne=class{constructor(e,t,i){this.onEvent=e;this.onceEvent=t;this.beacon=i;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=i,this.setupUrlChangeListener(),this.urlHistory.push(i.iframe.src),this.updateNavigationState()}visit(e){if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState(),this.emitHistoryChange(e,"push")}setupUrlChangeListener(){this.beacon.on("urlChange",e=>{this.addToHistory(e.newUrl)})}addToHistory(e){this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState()}updateNavigationState(){let e=this._canGoBack,t=this._canGoForward;this._canGoBack=this.currentIndex>0,this._canGoForward=this.currentIndex<this.urlHistory.length-1,(e!==this._canGoBack||t!==this._canGoForward)&&this.emitNavigationStateChange()}emitNavigationStateChange(){this.beacon&&this.beacon.emit&&this.beacon.emit("navigationStateChange",{canGoBack:this._canGoBack,canGoForward:this._canGoForward,currentIndex:this.currentIndex,historyLength:this.urlHistory.length,timestamp:Date.now()})}get canGoBack(){return this._canGoBack}get canGoForward(){return this._canGoForward}async goBack(){if(!this.canGoBack)return{success:!1,error:"Cannot go back - no previous history"};this.currentIndex--,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"back"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async goForward(){if(!this.canGoForward)return{success:!1,error:"Cannot go forward - no forward history"};this.currentIndex++,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"forward"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async reload(){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){let e=this.urlHistory[this.currentIndex];if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"reload")}}getCurrentUrl(){return this.currentIndex>=0&&this.currentIndex<this.urlHistory.length?new URL(this.urlHistory[this.currentIndex]):new URL("about:blank")}getHistory(){return[...this.urlHistory]}getCurrentIndex(){return this.currentIndex}canGoBackSync(){return this.currentIndex>0}canGoForwardSync(){return this.currentIndex<this.urlHistory.length-1}emitHistoryChange(e,t){this.beacon&&this.beacon.emit&&this.beacon.emit("historyChange",{url:e,state:null,direction:t,timestamp:Date.now()})}async pushState(e){this.visit(e)}async replaceState(e){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){if(this.urlHistory[this.currentIndex]=e,!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"replace")}else this.visit(e)}async getHistoryLength(){return this.urlHistory.length}async getHistoryState(){return null}async getHistoryInfo(){return{length:this.urlHistory.length,state:null,url:this.urlHistory[this.currentIndex]||"",canGoBack:this.canGoBack,canGoForward:this.canGoForward}}on(e,t){return this.onEvent(e,t)}once(e,t){this.onceEvent(e,t)}};function St(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var B=class extends Error{constructor(t,i){super(t);this.code=i;this.name="BeaconError"}},ve=class extends B{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},w=class extends B{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},Fe=class{constructor(e,t={}){this.messageHandlers=new Map;this.isBeaconReady=!1;this.readyPromise=null;this.isStarted=!1;this.disposables=[];this.messageChannel=null;this.port=null;this.channelEstablished=!1;St(),this.iframe=e;let i={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...i,...t.retry},...t},this.eventEmitter=U.make(),this.setupMessageChannel(),this.navigator=new ne(this.eventEmitter.listen.bind(this.eventEmitter),this.eventEmitter.once.bind(this.eventEmitter),this)}setupMessageChannel(){let e=t=>{try{if(t.source!==this.iframe.contentWindow)return;let i=t.data;if(!i||typeof i!="object"||!i.type)return;i.type==="beacon:ready-for-channel"&&this.establishChannel().catch(n=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",n)}),i.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",i.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(i){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",i)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new w("Iframe contentWindow not available");this.messageChannel=new MessageChannel,this.port=this.messageChannel.port1,this.port.onmessage=t=>{this.handleBeaconMessage(t.data)},this.port.onmessageerror=t=>{this.options.debug&&console.error("[Beacon SDK] Port message error:",t)},this.port.start();let e={type:"beacon:establish-channel",timestamp:Date.now(),id:this.generateId()};return this.iframe.contentWindow.postMessage(e,"*",[this.messageChannel.port2]),this.options.debug&&console.log("[Beacon SDK] Channel establishment message sent"),new Promise((t,i)=>{let n=setTimeout(()=>{i(new w("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(n),t()):setTimeout(o,100)};o()})}handleBeaconMessage(e){this.options.debug&&console.log("[Beacon SDK] Received message:",e.type,e.payload);let t=e.type.replace("beacon:","");this.emit(t,e.payload);let i=this.messageHandlers.get(e.type);i&&i.forEach(n=>{try{n(e.payload)}catch(o){this.options.debug&&console.error("[Beacon SDK] Message handler error:",o)}})}waitForBeaconReady(){return(0,Oe.default)(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let i=this.options.timeout,n=setTimeout(()=>{t(new ve("beacon ready",i))},i),o=this.on("ready",()=>{clearTimeout(n),o.dispose(),e()})}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(e,t)=>{if(this.options.debug){let i=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,i)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new w("MessagePort not available - channel not established");let i={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(i),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",i.type,i.payload)}catch(n){throw new w(`Failed to send message via port: ${n instanceof Error?n.message:String(n)}`)}}async sendAndWaitFor(e,t,i={},n){return await this.ready(),(0,Oe.default)(async o=>new Promise((s,a)=>{let c=n||this.options.timeout,h=setTimeout(()=>{u.dispose();let l=new ve(e,c);a(l)},c),u=this.eventEmitter.listen(t,l=>{clearTimeout(h),u.dispose(),s(l)});try{this.sendMessage(e,i)}catch(l){clearTimeout(h),u.dispose(),l instanceof w?a(l):o(l)}}),{retries:this.options.retry?.retries||3,minTimeout:this.options.retry?.minTimeout||1e3,maxTimeout:this.options.retry?.maxTimeout||5e3,factor:this.options.retry?.factor||2,randomize:this.options.retry?.randomize||!0,onRetry:(o,s)=>{if(this.options.debug){let a=o instanceof Error?o.message:String(o);console.warn(`[Beacon SDK] Retry attempt ${s} for ${e}:`,a)}}})}generateId(){return`sdk_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}emit(e,t){this.eventEmitter.emit(e,t)}start(){return this.isStarted?this.readyPromise||Promise.resolve():(this.isStarted=!0,this.readyPromise=this.waitForBeaconReady(),this.readyPromise)}async ready(){if(!this.isStarted)throw new B("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new B("Beacon ready promise is not available");return ce(this.readyPromise,this.options.timeout)}get isReady(){return this.isBeaconReady}on(e,t){return this.eventEmitter.listen(e,t)}once(e,t){this.eventEmitter.once(e,t)}async ping(){try{return await this.sendAndWaitFor("ping","pong",{timestamp:Date.now()}),!0}catch(e){return this.options.debug&&console.warn("[Beacon SDK] Ping failed:",e),!1}}async getDebugInfo(){return this.sendAndWaitFor("getDebugInfo","debugInfo")}async getConsoleEvents(){return this.sendAndWaitFor("getConsoleEvents","consoleEvents")}async getErrorEvents(){return this.sendAndWaitFor("getErrorEvents","errorEvents")}async clearConsole(){await this.ready(),this.sendMessage("clearConsole")}async clearErrors(){await this.ready(),this.sendMessage("clearErrors")}async executeCode(e){return this.sendAndWaitFor("executeCode","codeExecutionResult",{code:e})}async inspectElement(e){return this.sendAndWaitFor("inspectElement","elementInspectionResult",{selector:e})}async fetch(e){return this.sendAndWaitFor("fetch","fetchResult",e)}async debug(e,t){let i=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==i&&(this.navigator.visit(i),await this.ready()),t&&await this.wait(t);let n=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,n)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new w("Iframe not available");try{let t=new URL(e,this.iframe.src||window.location.origin);this.iframe.src=t.href,this.isBeaconReady=!1,this.channelEstablished=!1,this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.isStarted&&(this.readyPromise=this.waitForBeaconReady())}catch{throw new w(`Invalid URL: ${e}`)}}get url(){return this.iframe.src}get element(){return this.iframe}dispose(){this.port&&(this.port.close(),this.port=null),this.messageChannel&&(this.messageChannel=null),this.disposables.forEach(e=>e.dispose()),this.disposables=[],this.messageHandlers.clear(),this.isBeaconReady=!1,this.channelEstablished=!1,this.isStarted=!1,this.readyPromise=null}};function Tt(r,e){return new Fe(r,e)}function hr(){try{return St(),!0}catch{return!1}}function ki(r){return Array.isArray(r)?r:Object.entries(r).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var $e=class extends Error{constructor(t,i={}){super(t);this.message=t;this.data=i;this.name="NotebookInitError"}},We=class extends Error{constructor(t,i){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${i}`);this.response=t;this.body=i;this.status=t.status}},Ke=class{constructor(e){this.client=e;this.secrets=new ze(e),this.previewAuth=new Ge(e),this.mail=new qe(e)}async create(e,t={},i=!0){let n=await this.client.post("/notebook",{template:e,...t}),o=new I(n.data,this.client);return i?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new I(t.data,this.client)}async update(e,t={}){let i=await this.client.put(`/notebook/${e}`,t);return new I(i.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e){let t=await this.client.post(`/notebook/${e}/fork`);return this.init(new I(t.data,this.client))}async open(e){let t=await this.client.get(`/notebook/${e}`);return new I(t.data,this.client)}openFromData(e){return this.init(new I(e,this.client))}async init(e){return await e.ready(),e}},He=class{constructor(e,t="https://api.phpsandbox.io/v1",i={}){this.fetch=globalThis.fetch;this.notebook=new Ke(this),this.options=Object.assign({startClosed:!0},i),this.baseUrl=t,i.fetch&&(this.fetch=i.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t?JSON.stringify(t):void 0})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t?JSON.stringify(t):void 0})}async makeRequest(e,t,i){let n=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...i,headers:this.headers}));if(!n.ok)throw new We(n,await n.text());if(n.status===204)return{data:void 0};let o=await n.text();return{data:o===""?void 0:JSON.parse(o)}}},It=class extends He{},ze=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,i){let n=typeof i=="string"?{name:t,value:i}:{name:t,...i};return(await this.client.put(`/notebook/${e}/secrets`,n)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:ki(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ge=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview-auth`)).data}async set(e,t){return(await this.client.put(`/notebook/${e}/preview-auth`,t)).data}async delete(e){await this.client.delete(`/notebook/${e}/preview-auth`)}},qe=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${Ei(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},C,re,Qe,I=class{constructor(e,t){this.data=e;this.client=t;O(this,re);this.initialized=!1;O(this,C);this.disposables=[];this.emitter=U.createInstance(),this.socket=new te(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),xe(this,C,k(this,re,Qe).call(this)),this.file=new ae(this),this.terminal=new $(this),this.auth=new K(this),this.lsp=new H(this),this.composer=new z(this),this.log=new G(this),this.repl=new Q(this),this.container=new W(this),this.laravel=new q(this),this.shell=new V(this),this.git=new ie(this),this.services=new X(this),this.secrets=new Ve(t,this.data.id),this.previewAuth=new Xe(t,this.data.id),this.mail=new Je(t,this.data.id)}async ready(){let e=this.socket.getTerminalError();if(e)throw e;return(async()=>(this.client.options.startClosed&&!this.socket.isConnected&&await this.socket.connect(),se(this,C)))()}fork(){return this.client.notebook.fork(this.data.id)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new E("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},i={}){return this.socket.invoke(e,t||{},i)}ping(){return this.invoke("ping")}listen(e,t){let i=this.emitter.listen(e,t);return this.disposables.push(i),i}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>i(new Error("Connection closed"))),this.socket.onDidBootError(n=>i(n))}catch(n){i(n)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,i)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(n=>i(n))}catch(n){i(n)}})}watchConnection(){this.socket.onDidConnect(()=>{this.socket.emit("okra.connected"),this.client.options.telemetry&&this.container.enableTelemetry(this.client.options.telemetry)}),this.socket.onDidClose(()=>{this.socket.emit("okra.disconnected"),this.initialized=!1}),this.socket.onDidBootError(e=>{this.socket.emit("okra.boot_error",e),this.socket.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){this.socket.removeListener("okra.connected",e);let t=this.socket.listen("okra.connected",e);return this.disposables.push(t),t}onDidDisconnect(e){let t=this.socket.listen("okra.disconnected",e);return this.disposables.push(t),t}onDidBootError(e){let t=this.socket.listen("okra.boot_error",e);return this.disposables.push(t),t}update(){return this.invoke("notebook.update")}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.whenConnected();return this.socket.reconnect(),this.initialized=!1,await e,k(this,re,Qe).call(this),this.ready().then(()=>this)}async beacon(e,t){let i=await this.ready();return e.src=i.data.previewUrl,Tt(e,t)}};C=new WeakMap,re=new WeakSet,Qe=function(){return xe(this,C,new Promise((e,t)=>{let i=this.onDidInitialize(o=>{if(n.dispose(),i.dispose(),this.initialized=o,o.type==="error"){t(new $e(o.message,o.data));return}e(o)}),n=this.onDidBootError(o=>{i.dispose(),n.dispose(),t(o)})})),se(this,C).catch(()=>{}),se(this,C)};var Ve=class{constructor(e,t){this.client=e;this.notebookId=t}list(){return this.client.notebook.secrets.list(this.notebookId)}set(e,t){return this.client.notebook.secrets.set(this.notebookId,e,t)}setMany(e){return this.client.notebook.secrets.setMany(this.notebookId,e)}delete(e){return this.client.notebook.secrets.delete(this.notebookId,e)}},Xe=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.previewAuth.get(this.notebookId)}set(e){return this.client.notebook.previewAuth.set(this.notebookId,e)}disable(){return this.client.notebook.previewAuth.delete(this.notebookId)}},Je=class{constructor(e,t){this.client=e;this.notebookId=t}status(){return this.client.notebook.mail.status(this.notebookId)}enable(){return this.client.notebook.mail.enable(this.notebookId)}disable(){return this.client.notebook.mail.disable(this.notebookId)}list(e={}){return this.client.notebook.mail.list(this.notebookId,e)}get(e){return this.client.notebook.mail.get(this.notebookId,e)}delete(e){return this.client.notebook.mail.delete(this.notebookId,e)}};function Ei(r){let e=new URLSearchParams;for(let[i,n]of Object.entries(r))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&e.set(i,String(n));let t=e.toString();return t===""?"":`?${t}`}export{We as ApiError,Fe as Beacon,w as BeaconConnectionError,B as BeaconError,ve as BeaconTimeoutError,He as Client,Te as CommandError,y as ErrorEvent,Ut as FileChangeType,Rt as FileType,ae as Filesystem,ke as FilesystemError,Lt as FilesystemErrorType,Se as LspConnection,ne as Navigator,Ke as NotebookApi,$e as NotebookInitError,I as NotebookInstance,Je as NotebookMail,qe as NotebookMailApi,Xe as NotebookPreviewAuth,Ge as NotebookPreviewAuthApi,ze as NotebookSecretApi,Ve as NotebookSecrets,Mt as NotebookState,E as NotebookUnavailableError,It as PHPSandbox,et as PHPSandboxError,_ as PromiseTimeoutError,L as RateLimitError,F as SendTimeoutError,te as Transport,Tt as createBeacon,hr as isBeaconSupported,Bt as notebookBuiltinServices,Xi as notebookKnownServices,le as once,ce as timeout};
3
3
  /*! Bundled license information:
4
4
 
5
5
  reconnecting-websocket/dist/reconnecting-websocket-mjs.js: