@phpsandbox/sdk 0.0.41 → 0.0.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/phpsandbox-sdk.esm.js +60 -41
- package/dist/browser/phpsandbox-sdk.esm.js.map +2 -2
- package/dist/browser/phpsandbox-sdk.esm.min.js +2 -2
- package/dist/browser/phpsandbox-sdk.esm.min.js.map +3 -3
- package/dist/browser/phpsandbox-sdk.iife.js +60 -41
- package/dist/browser/phpsandbox-sdk.iife.js.map +2 -2
- package/dist/browser/phpsandbox-sdk.iife.min.js +2 -2
- package/dist/browser/phpsandbox-sdk.iife.min.js.map +3 -3
- package/dist/container.d.ts +2 -0
- package/dist/container.d.ts.map +1 -1
- package/dist/container.js.map +1 -1
- package/dist/socket/index.d.ts +2 -0
- package/dist/socket/index.d.ts.map +1 -1
- package/dist/socket/index.js +64 -41
- package/dist/socket/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Pt=Object.create;var Ye=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Dt=Object.getOwnPropertyNames;var Nt=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 Rt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Dt(e))!At.call(r,i)&&i!==t&&Ye(r,i,{get:()=>e[i],enumerable:!(n=_t(e,i))||n.enumerable});return r};var Ze=(r,e,t)=>(t=r!=null?Pt(Nt(r)):{},Rt(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)),B=(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,n)=>(we(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),k=(r,e,t)=>(we(r,e,"access private method"),t);var pt=oe((Mi,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 n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._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,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=i,t=s)}return e}});var dt=oe(D=>{var pn=pt();D.operation=function(r){var e=D.timeouts(r);return new pn(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 n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(o,s){return o-s}),n};D.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};D.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var o=t[i],s=r[o];r[o]=function(c){var h=D.operation(e),l=Array.prototype.slice.call(arguments,1),u=l.pop();l.push(function(d){h.retry(d)||(d&&(arguments[0]=h.mainError()),u.apply(this,arguments))}),h.attempt(function(){c.apply(r,l)})}.bind(r,s),r[o].options=e}}});var ft=oe((Oi,mt)=>{mt.exports=dt()});var Re=oe((Fi,gt)=>{var dn=ft();function mn(r,e){function t(n,i){var o=e||{},s;"randomize"in o||(o.randomize=!0),s=dn.operation(o);function a(l){i(l||new Error("Aborted"))}function c(l,u){if(l.bail){a(l);return}s.retry(l)?o.onRetry&&o.onRetry(l,u):i(s.mainError())}function h(l){var u;try{u=r(a,l)}catch(d){c(d,l);return}Promise.resolve(u).then(n).catch(function(v){c(v,l)})}s.attempt(h)}return new Promise(t)}gt.exports=mn});var y=class extends Error{constructor(t,n,i={}){super(n);this.code=t;this.message=n;this.raw=i}},O=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 Ut=(i=>(i[i.Unknown=0]="Unknown",i[i.File=1]="File",i[i.Directory=2]="Directory",i[i.SymbolicLink=64]="SymbolicLink",i))(Ut||{}),Lt=(n=>(n[n.UPDATED=1]="UPDATED",n[n.ADDED=2]="ADDED",n[n.DELETED=3]="DELETED",n))(Lt||{}),Mt=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(Mt||{}),ke=class extends y{constructor(t,n){super(t.code,t.message);this.name=n}},Ee=class{constructor(e,t,n){this.path=e;this.okra=t;this.disposable=n}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:n}of this.watches.values())this.watch(e,t,n)})}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,n){e.id||(e.id=g());let i={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(),n&&await Promise.resolve(n(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...i,...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 n=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return n instanceof Uint8Array?n:typeof n=="string"?new TextEncoder().encode(n):n}catch(n){this.handleError(n)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(n=>this.handleError(n))}writeFile(e,t,n){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:n}).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,n){return this.okra.invoke("fs.rename",{from:e,to:t,options:n}).catch(i=>this.handleError(i))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(n=>this.handleError(n))}copy(e,t,n){return this.okra.invoke("fs.copy",{source:e,destination:t,options:n}).catch(i=>this.handleError(i))}readDirectory(e,t=[],n=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:n}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,n){let i=this.okra.listen(`fs.watch.${e}`,n),o={dispose:()=>{i.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:n}),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,n){let i=g(),o=!!e,s=[];return this.okra.listen(`fs.download.${i}`,o?e:a=>{s.push(a)}),this.okra.invoke("fs.download",{id:i,exclude:t,include:n}).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 P=class extends Error{constructor(t,n){super(t);this.time=n}},F=class r extends P{static fromPromiseTimeoutError(e){return new r(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",n={}){super(t);this.raw=n;this.name="NotebookUnavailableError"}};var ce=(r,e)=>{let t;return Promise.race([r,new Promise((n,i)=>t=setTimeout(i,e,new P("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},le=r=>{let e=null;return()=>e||(e=r())};var Bt=8,Ot=/[\x00-\x1f\x7f]/,$=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 Promise.resolve(this.okra.send("terminal.input",{id:e,input:t}))}listen(e,t){return this.okra.listen(e,t)}async attach(e,t){let n=this.processHandle(e,t?.abortSignal),i=await this.okra.invoke("terminal.attach",{id:e,replayHistory:t?.replayHistory},{abortSignal:t?.abortSignal});return i?{...n.process,...i}:(n.dispose(),!1)}async spawn(e,t,n){let i=n?.id||g(),o=this.processHandle(i,n?.abortSignal),{abortSignal:s,...a}=n??{},c=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:i,...a}},{abortSignal:s});return{...o.process,...c}}processHandle(e,t){let n=new Set,i=()=>{for(let f of n)f.dispose();n.clear()},o="",s,a=()=>{if(s&&(clearTimeout(s),s=void 0),o==="")return;let f=o;o="",this.input(e,f)},c=()=>{s||(s=setTimeout(a,Bt))},h=f=>{if(o+=f,Ot.test(f)){a();return}c()},l=()=>{a(),i()},u=new WritableStream({write:h,close:l,abort:l}),d=null,v=new ReadableStream({start:f=>{d=f,n.add(this.listen(`terminal.output.${e}`,ye=>{d?.enqueue(ye.output)}))},cancel:()=>{d=null,l()}}),p=new Promise(f=>{n.add(this.listen(`terminal.close.${e}`,ye=>{if(d)try{d.close()}catch{}l(),f(ye.exitCode)}))}),w=le(()=>(l(),this.okra.invoke("terminal.close",{id:e}))),Ct=f=>{this.okra.invoke("terminal.resize",{id:e,width:f.cols,height:f.rows})};return t&&t.addEventListener("abort",w),{process:{exit:p,input:u,output:v,kill:w,resize:Ct},dispose:l}}};var Ft=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(Ft||{}),H=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",n=>{for(let i of n)t.some(o=>o.port===i.port)||e(i,"open");for(let i of t)n.some(o=>o.port===i.port)||e(i,"close");t=n})}};var W=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var K=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,n){this.okra.listen(`${t}.${e}`,i=>n(i))}onClose(e,t){this.listen(e,"lsp.closed",n=>t(n.code,n.reason))}onError(e,t){this.listen(e,"lsp.error",n=>t(n.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",n=>t(JSON.stringify(n)))}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={},n={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:n})}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="",n={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:n})}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 nt(r,e=[],t){let n=Array.isArray(e)?e:[],i=Array.isArray(e)?t:e;return{command:Array.isArray(r)?r:n.length>0?[r,...n]:r,opts:i}}var Te=class extends Error{constructor(t,n){super(t);this.output=t;this.exitCode=n}},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=[],n){let i=nt(e,t,n),{abortSignal:o,...s}=i.opts??{},a=await this.okra.invoke("shell.exec",{command:i.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new Ie(a.output,a.exitCode)}execStream(e,t=[],n){let i=nt(e,t,n),o=i.opts?.id||g(),s=new Set,a=null,c=!1,h=()=>{for(let p of s)p.dispose();s.clear()},l=()=>{if(!c&&(c=!0,h(),a))try{a.close()}catch{}},u=p=>{c||(c=!0,h(),a&&a.error(p))},d=new ReadableStream({start:p=>{a=p,s.add(this.listen(`shell.output.${o}`,w=>{a?.enqueue(w.output)}))},cancel:()=>{c=!0,h()}}),v=this.exec(i.command,{...i.opts,id:o}).then(p=>(l(),p)).catch(p=>{throw u(p),p});return{output:d,result:v}}};var $t=["redis"],Zn=["start","nginx",...$t],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(n=>{if(!("output"in n))throw new Error(`Unexpected service.logs response for ${e}`);return n.output})}followLogs(e,t){let n=t.id||g(),i=new Set,o=null,s=!1,a=()=>{for(let d of i)d.dispose();i.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},h=d=>{s||(s=!0,a(),o&&o.error(d))},l=le(()=>(c(),this.okra.invoke("service.stop-logs",{id:n}))),u=new ReadableStream({start:d=>{o=d,i.add(this.onLog(n,v=>{o?.enqueue(v.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:n}).catch(v=>{h(v)})},cancel:()=>{l()}});return{id:n,output:u,stop:l}}};function it(r){let e=r.length,t=0,n=0;for(;n<e;){let i=r.charCodeAt(n++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&n<e){let o=r.charCodeAt(n);(o&64512)===56320&&(++n,i=((i&1023)<<10)+(o&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function Ht(r,e,t){let n=r.length,i=t,o=0;for(;o<n;){let s=r.charCodeAt(o++);if((s&4294967168)===0){e[i++]=s;continue}else if((s&4294965248)===0)e[i++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){let a=r.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[i++]=s>>12&15|224,e[i++]=s>>6&63|128):(e[i++]=s>>18&7|240,e[i++]=s>>12&63|128,e[i++]=s>>6&63|128)}e[i++]=s&63|128}}var Wt=new TextEncoder,Kt=50;function zt(r,e,t){Wt.encodeInto(r,e.subarray(t))}function rt(r,e,t){r.length>Kt?zt(r,e,t):Ht(r,e,t)}var Gt=4096;function Ce(r,e,t){let n=e,i=n+t,o=[],s="";for(;n<i;){let a=r[n++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=r[n++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=r[n++]&63,h=r[n++]&63;o.push((a&31)<<12|c<<6|h)}else if((a&248)===240){let c=r[n++]&63,h=r[n++]&63,l=r[n++]&63,u=(a&7)<<18|c<<12|h<<6|l;u>65535&&(u-=65536,o.push(u>>>10&1023|55296),u=56320|u&1023),o.push(u)}else o.push(a);o.length>=Gt&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var Qt=new TextDecoder,qt=200;function Vt(r,e,t){let n=r.subarray(e,e+t);return Qt.decode(n)}function ot(r,e,t){return t>qt?Vt(r,e,t):Ce(r,e,t)}var _=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 n=t/4294967296,i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function ue(r,e,t){let n=Math.floor(t/4294967296),i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function he(r,e){let t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function at(r,e){let t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}var Xt=-1,Jt=4294967296-1,Yt=17179869184-1;function jt({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Yt)if(e===0&&r<=Jt){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{let t=r/4294967296,n=r&4294967295,i=new Uint8Array(8),o=new DataView(i.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,n),i}else{let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),ue(n,4,r),t}}function Zt(r){let e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,i=Math.floor(n/1e9);return{sec:t+i,nsec:n-i*1e9}}function en(r){if(r instanceof Date){let e=Zt(r);return jt(e)}else return null}function tn(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),n=e.getUint32(4),i=(t&3)*4294967296+n,o=t>>>2;return{sec:i,nsec:o}}case 12:{let t=he(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new m(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function nn(r){let e=tn(r);return new Date(e.sec*1e3+e.nsec/1e6)}var ct={type:Xt,encode:en,decode:nn};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ct)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let i=this.builtInEncoders[n];if(i!=null){let o=i(e,t);if(o!=null){let s=-1-n;return new _(s,o)}}}for(let n=0;n<this.encoders.length;n++){let i=this.encoders[n];if(i!=null){let o=i(e,t);if(o!=null){let s=n;return new _(s,o)}}}return e instanceof _?e:null}decode(e,t,n){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new _(t,e)}};S.defaultCodec=new S;function rn(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):rn(r)?new Uint8Array(r):Uint8Array.from(r)}var on=100,sn=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??on,this.initialBufferSize=e?.initialBufferSize??sn,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),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n}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 n=it(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),rt(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,t){let n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);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 n=J(e);this.writeU8a(n)}encodeArray(e,t){let n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let n=0;for(let i of t)e[i]!==void 0&&n++;return n}encodeMap(e,t){let n=Object.keys(e);this.sortKeys&&n.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(let o of n){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 n=e.data(this.pos+6),i=n.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(n);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 Pe(r,e){return new pe(e).encodeSharedRef(r)}function de(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var an=16,cn=16,me=class{constructor(e=an,t=cn){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let i=this.caches[n-1];e:for(let o of i){let s=o.bytes;for(let a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,t,n){let i=this.find(e,t,n);if(i!=null)return this.hit++,i;this.miss++;let o=Ce(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o}};var _e="array",Z="map_key",ut="map_value",ln=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=_e,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===_e){let n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===Z||e.type===ut){let n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},j=-1,Ne=new DataView(new ArrayBuffer(0)),un=new Uint8Array(Ne.buffer);try{Ne.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"),hn=new me,fe=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Ne,this.bytes=un,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:hn,this.mapKeyConverter=e?.mapKeyConverter??ln}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),n=J(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} 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,n;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=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 n}let{headByte:i,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${de(i)} 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 n=t,i=-1;for await(let o of e){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==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 i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e<160){let i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else{let i=e-160;t=this.decodeString(i,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 i=this.lookU8();t=this.decodeString(i,1)}else if(e===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(e===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(e===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(e===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(e===198){let i=this.lookU32();t=this.decodeBinary(i,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 i=this.lookU8();t=this.decodeExtension(i,1)}else if(e===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(e===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new m(`Unrecognized type byte: ${de(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let i=n.top();if(i.type===_e)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,n.release(i);else continue e;else if(i.type===Z){if(t==="__proto__")throw new m("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=ut;continue e}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,n.release(i);else{i.key=null,i.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 n=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,n,e):i=ot(this.bytes,n,e),this.pos+=t+e,i}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 n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new m(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,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 Ae(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,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])},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 fn(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 gn(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function bn(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(gn(arguments[e]));return r}var vt=(function(){function r(e,t){this.target=t,this.type=e}return r})(),vn=(function(r){bt(e,r);function e(t,n){var i=r.call(this,"error",n)||this;return i.message=t.message,i.error=t,i}return e})(vt),yn=(function(r){bt(e,r);function e(t,n,i){t===void 0&&(t=1e3),n===void 0&&(n="");var o=r.call(this,"close",i)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return e})(vt);var wn=function(){if(typeof WebSocket<"u")return WebSocket},xn=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},N={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},kn=(function(){function r(e,t,n){var i=this;n===void 0&&(n={}),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){i._debug("open event");var s=i._options.minUptime,a=s===void 0?N.minUptime:s;clearTimeout(i._connectTimeout),i._uptimeTimeout=setTimeout(function(){return i._acceptOpen()},a),i._ws.binaryType=i._binaryType,i._messageQueue.forEach(function(c){return i._ws.send(c)}),i._messageQueue=[],i.onopen&&i.onopen(o),i._listeners.open.forEach(function(c){return i._callEventListener(o,c)})},this._handleMessage=function(o){i._debug("message event"),i.onmessage&&i.onmessage(o),i._listeners.message.forEach(function(s){return i._callEventListener(o,s)})},this._handleError=function(o){i._debug("error event",o.message),i._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),i.onerror&&i.onerror(o),i._debug("exec error listeners"),i._listeners.error.forEach(function(s){return i._callEventListener(o,s)}),i._connect()},this._handleClose=function(o){i._debug("close event"),i._clearTimeouts(),i._shouldReconnect&&i._connect(),i.onclose&&i.onclose(o),i._listeners.close.forEach(function(s){return i._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=n,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,n){return typeof n=="string"?t+=n.length:n instanceof Blob?t+=n.size:t+=n.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,n=t===void 0?N.maxEnqueuedMessages:t;this._messageQueue.length<n&&(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,n,i=this._listeners[e.type];if(i)try{for(var o=fn(i),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&&(n=o.return)&&n.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(n){return n!==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,bn(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=t===void 0?N.reconnectionDelayGrowFactor:t,i=e.minReconnectionDelay,o=i===void 0?N.minReconnectionDelay:i,s=e.maxReconnectionDelay,a=s===void 0?N.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(n,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,n=t.maxRetries,i=n===void 0?N.maxRetries:n,o=t.connectionTimeout,s=o===void 0?N.connectionTimeout:o,a=t.WebSocket,c=a===void 0?wn():a;if(this._retryCount>=i){this._debug("max retries reached",this._retryCount,">=",i);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!xn(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 vn(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 yn(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=kn;var En=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},Sn=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 n=typeof e.name=="string"&&e.name?e.name:void 0;return n?`${n}: ${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=[],n=wt(e);n&&t.push(n);let i=wt(e.error);i&&i!==n&&t.push(`error=${i}`),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!==n&&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=${Sn(o.url)}`);let s=En(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var L=null;typeof WebSocket<"u"?L=WebSocket:typeof MozWebSocket<"u"?L=MozWebSocket:typeof global<"u"?L=global.WebSocket||global.MozWebSocket:typeof window<"u"?L=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(L=self.WebSocket||self.MozWebSocket);var xt=L;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,n){super(t);this.originalError=n;this.name="ConnectionFailedError"}},A=class extends Error{constructor(t,n){super(t);this.data=n;this.name="InvalidMessageError"}},R=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},T,Me,Be,te=class{constructor(e,t,n={}){this.eventEmitter=t;this.options=n;B(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.validateConfiguration(n),this.url=new URL(e),this.PING_INTERVAL=n.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=n.connectWaitTimeout??3e4,this.connectionStats.connectionStartTime=Date.now();let i=n.startClosed!==!1;this.rws=new yt(this.url.toString(),[],{WebSocket:n.webSocket??globalThis.WebSocket??xt,connectionTimeout:n.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:n.maxRetries??50,startClosed:i}),this.log("debug","Transport initialized",{url:this.url.toString(),options:n}),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,n){if(this.options.debug){let i=new Date().toISOString(),o=n?JSON.stringify(n,null,2):"";console[e](`[Transport ${i}] ${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 n=new Error("Unexpected message type: "+typeof t.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:n.message,messageType:typeof t.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:n,rawMessage:t.data,timestamp:Date.now()});return}t.data.arrayBuffer().then(n=>{if(n.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}try{this.handleRawMessage(Ae(n)).catch(i=>{this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:n,timestamp:Date.now()})})}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:i,rawMessage:n,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:n,as:i}=e;if(!n||typeof n!="string")throw new A("Message missing event field",e);if(this.log("debug","Processing message",{event:n,hasData:!!t}),n==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(n==="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(n==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new A("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(n==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new A("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(n,t,i)}catch(t){this.connectionStats.totalErrors++,t instanceof A?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,n){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(n||e,t)}listen(e,t,n){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,n){this.eventEmitter.once(e,t,n),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={},n={}){if(this.terminalError)throw this.terminalError;this.clearOldQueuedMessages();let i=n.responseEvent||`${e}_${g()}_response`,o=`${i}_error`,s,a=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),this.eventEmitter.removeListener(i),this.eventEmitter.removeListener(o)},c=async(l,u)=>{if(this.terminalError){u(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(n.abortSignal?.aborted&&u(d),n.abortSignal&&n.abortSignal.addEventListener("abort",()=>{u(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:n,resolve:l,reject:u,timestamp:Date.now()});return}let v=Date.now();this.listenOnce(i,p=>{let w=Date.now()-v;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+w)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:w,avgResponseTime:this.connectionStats.avgResponseTime}),l(p)}),this.listenOnce(o,p=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:p}),u(new y(p.code,p.message,p))}),s=p=>{if(p.code===1008&&(p.reason||"").includes("rate limit")){u(new O(p.reason||"Rate limit exceeded",p));return}let w=ee(p);u(this.terminalError||new be(`Connection lost to the notebook during request: ${w}`,p))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:i})),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 l=new Promise(c).finally(a);return n.timeout?ce(l,n.timeout).catch(u=>{throw u instanceof P?F.fromPromiseTimeoutError(u):u}).finally(a):l};return this.sendWithRetry(async()=>await h(),n.retries||10)}send(e,t={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:t})),this.connectionStats.totalMessages++,this.log("debug","One-way message sent",{action:e,data:t}),!0}catch(n){return this.connectionStats.totalErrors++,this.log("error","Failed to send one-way message",{action:e,error:n}),!1}}pack(e){return new Blob([Pe(e)])}sendWithRetry(e,t=10){return(0,kt.default)(async(n,i)=>{try{return await e()}catch(o){if(o instanceof y||o instanceof O||o instanceof R||o instanceof A||o instanceof E||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:i}),n(o);return}throw o instanceof F&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:i,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:i,error:o instanceof Error?o.message:String(o),nextDelay:this.getBackoffDelay(i-1)}),o}},{retries:t,onRetry:(n,i)=>{this.log("warn","Send operation retry",{attempt:i,maxRetries:t,error:n instanceof Error?n.message:String(n)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},n={}){return n.responseEvent||(n.responseEvent=`${e}_${g()}`),this.call("invoke",{action:e,data:t},n)}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,n=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,n)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let n=this.messageQueue.length,i=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(o=>{o.reject(i)}),this.messageQueue=[],n>0&&this.log("debug",`Rejected ${n} queued messages due to connection close`),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(n=>{let i=e-n.timestamp>this.QUEUE_TIMEOUT;return i&&n.reject(new Error("Queued message expired")),!i}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}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(n=>n.timestamp)):0},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(),n=[],i=[];return this.isConnected||(n.push("Connection is not established"),i.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(n.push("No pong received recently - connection may be stale"),i.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(n.push(`High error rate: ${e.connectionStats.errorRate}`),i.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(n.push("Message queue is nearly full"),i.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(n.push("High average response time"),i.push("Check network latency and server performance")),this.log("info","Connection diagnostics completed",{status:t,issueCount:n.length,recommendationCount:i.length}),{status:t,metrics:e,issues:n,recommendations:i}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{if(this.clearOldQueuedMessages(),this.options.debug){let t=this.getHealthStatus(),n=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:t,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 n,i=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(n)},s=()=>{o(),this.connectPromise=null,e(),k(this,T,Be).call(this)},a=h=>{i+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:i,error:ee(h)})},c=h=>{let l=ee(h);if("code"in h&&(h.code===1008||h.code===4e3)){o(),this.connectPromise=null,t(new be(`WebSocket connection failed: ${l}`,h));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:l})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),n=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 n=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:n})}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 n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}function Tn(r){let e=Et(r);return e.once=(t,n)=>{e.on(t,n),e.on(t,e.off.bind(e,t,n))},e}var U=class r{constructor(){this.emitter=Tn()}listen(e,t){let n=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:n}}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 ne=class{constructor(e){this.okra=e}checkpoint(e,t,n="main",i=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:n,allowEmpty:i})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,n="main",i,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:n,token:i,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 ie=class{constructor(e,t,n){this.onEvent=e;this.onceEvent=t;this.beacon=n;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=n,this.setupUrlChangeListener(),this.urlHistory.push(n.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 M=class extends Error{constructor(t,n){super(t);this.code=n;this.name="BeaconError"}},ve=class extends M{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},x=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;St(),this.iframe=e;let n={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...n,...t.retry},...t},this.eventEmitter=U.make(),this.setupMessageChannel(),this.navigator=new ie(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 n=t.data;if(!n||typeof n!="object"||!n.type)return;n.type==="beacon:ready-for-channel"&&this.establishChannel().catch(i=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",i)}),n.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",n.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(n){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",n)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new x("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,n)=>{let i=setTimeout(()=>{n(new x("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(i),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 n=this.messageHandlers.get(e.type);n&&n.forEach(i=>{try{i(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 n=this.options.timeout,i=setTimeout(()=>{t(new ve("beacon ready",n))},n),o=this.on("ready",()=>{clearTimeout(i),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 n=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,n)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new x("MessagePort not available - channel not established");let n={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(n),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",n.type,n.payload)}catch(i){throw new x(`Failed to send message via port: ${i instanceof Error?i.message:String(i)}`)}}async sendAndWaitFor(e,t,n={},i){return await this.ready(),(0,Oe.default)(async o=>new Promise((s,a)=>{let c=i||this.options.timeout,h=setTimeout(()=>{l.dispose();let u=new ve(e,c);a(u)},c),l=this.eventEmitter.listen(t,u=>{clearTimeout(h),l.dispose(),s(u)});try{this.sendMessage(e,n)}catch(u){clearTimeout(h),l.dispose(),u instanceof x?a(u):o(u)}}),{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 n=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==n&&(this.navigator.visit(n),await this.ready()),t&&await this.wait(t);let i=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,i)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new x("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 x(`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 mr(){try{return St(),!0}catch{return!1}}function In(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,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},He=class extends Error{constructor(t,n){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${n}`);this.response=t;this.body=n;this.status=t.status}},We=class{constructor(e){this.client=e;this.secrets=new ze(e),this.preview=new Ge(e),this.mail=new Qe(e)}async create(e,t={},n=!0){let i=await this.client.post("/notebook",{template:e,...t}),o=new I(i.data,this.client);return n?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 n=await this.client.put(`/notebook/${e}`,t);return new I(n.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}},Ke=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.notebook=new We(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=t,n.fetch&&(this.fetch=n.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,n){let i=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...n,headers:this.headers}));if(!i.ok)throw new He(i,await i.text());if(i.status===204)return{data:void 0};let o=await i.text();return{data:o===""?void 0:JSON.parse(o)}}},It=class extends Ke{},ze=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let i=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,i)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:In(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`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},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${Cn(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;B(this,re);this.initialized=!1;B(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 W(this),this.lsp=new K(this),this.composer=new z(this),this.log=new G(this),this.repl=new q(this),this.container=new H(this),this.laravel=new Q(this),this.shell=new V(this),this.git=new ne(this),this.services=new X(this),this.secrets=new Ve(t,this.data.id),this.preview=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={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}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,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>n(new Error("Connection closed"))),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}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 n=await this.ready();return e.src=n.data.previewUrl,Tt(e,t)}};C=new WeakMap,re=new WeakSet,qe=function(){return xe(this,C,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(i.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new $e(o.message,o.data));return}e(o)}),i=this.onDidBootError(o=>{n.dispose(),i.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.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},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 Cn(r){let e=new URLSearchParams;for(let[n,i]of Object.entries(r))(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&e.set(n,String(i));let t=e.toString();return t===""?"":`?${t}`}export{He as ApiError,Fe as Beacon,x as BeaconConnectionError,M as BeaconError,ve as BeaconTimeoutError,Ke as Client,Te as CommandError,y as ErrorEvent,Lt as FileChangeType,Ut as FileType,ae as Filesystem,ke as FilesystemError,Mt as FilesystemErrorType,Se as LspConnection,ie as Navigator,We as NotebookApi,$e as NotebookInitError,I as NotebookInstance,Je as NotebookMail,Qe as NotebookMailApi,Xe as NotebookPreview,Ge as NotebookPreviewApi,ze as NotebookSecretApi,Ve as NotebookSecrets,Ft as NotebookState,E as NotebookUnavailableError,It as PHPSandbox,et as PHPSandboxError,P as PromiseTimeoutError,O as RateLimitError,F as SendTimeoutError,te as Transport,Tt as createBeacon,mr as isBeaconSupported,$t as notebookBuiltinServices,Zn as notebookKnownServices,le as once,ce as timeout};
|
|
1
|
+
var Ct=Object.create;var Ye=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Dt=Object.getOwnPropertyNames;var Nt=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 Rt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Dt(e))!At.call(r,i)&&i!==t&&Ye(r,i,{get:()=>e[i],enumerable:!(n=_t(e,i))||n.enumerable});return r};var Ze=(r,e,t)=>(t=r!=null?Ct(Nt(r)):{},Rt(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)),B=(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,n)=>(we(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),k=(r,e,t)=>(we(r,e,"access private method"),t);var pt=oe((Mi,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 n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._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,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=i,t=s)}return e}});var dt=oe(D=>{var pn=pt();D.operation=function(r){var e=D.timeouts(r);return new pn(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 n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(o,s){return o-s}),n};D.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};D.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var o=t[i],s=r[o];r[o]=function(c){var h=D.operation(e),l=Array.prototype.slice.call(arguments,1),u=l.pop();l.push(function(d){h.retry(d)||(d&&(arguments[0]=h.mainError()),u.apply(this,arguments))}),h.attempt(function(){c.apply(r,l)})}.bind(r,s),r[o].options=e}}});var ft=oe((Oi,mt)=>{mt.exports=dt()});var Re=oe((Fi,gt)=>{var dn=ft();function mn(r,e){function t(n,i){var o=e||{},s;"randomize"in o||(o.randomize=!0),s=dn.operation(o);function a(l){i(l||new Error("Aborted"))}function c(l,u){if(l.bail){a(l);return}s.retry(l)?o.onRetry&&o.onRetry(l,u):i(s.mainError())}function h(l){var u;try{u=r(a,l)}catch(d){c(d,l);return}Promise.resolve(u).then(n).catch(function(v){c(v,l)})}s.attempt(h)}return new Promise(t)}gt.exports=mn});var y=class extends Error{constructor(t,n,i={}){super(n);this.code=t;this.message=n;this.raw=i}},O=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 Ut=(i=>(i[i.Unknown=0]="Unknown",i[i.File=1]="File",i[i.Directory=2]="Directory",i[i.SymbolicLink=64]="SymbolicLink",i))(Ut||{}),Lt=(n=>(n[n.UPDATED=1]="UPDATED",n[n.ADDED=2]="ADDED",n[n.DELETED=3]="DELETED",n))(Lt||{}),Mt=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(Mt||{}),ke=class extends y{constructor(t,n){super(t.code,t.message);this.name=n}},Ee=class{constructor(e,t,n){this.path=e;this.okra=t;this.disposable=n}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:n}of this.watches.values())this.watch(e,t,n)})}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,n){e.id||(e.id=g());let i={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(),n&&await Promise.resolve(n(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...i,...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 n=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return n instanceof Uint8Array?n:typeof n=="string"?new TextEncoder().encode(n):n}catch(n){this.handleError(n)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(n=>this.handleError(n))}writeFile(e,t,n){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:n}).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,n){return this.okra.invoke("fs.rename",{from:e,to:t,options:n}).catch(i=>this.handleError(i))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(n=>this.handleError(n))}copy(e,t,n){return this.okra.invoke("fs.copy",{source:e,destination:t,options:n}).catch(i=>this.handleError(i))}readDirectory(e,t=[],n=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:n}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,n){let i=this.okra.listen(`fs.watch.${e}`,n),o={dispose:()=>{i.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:n}),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,n){let i=g(),o=!!e,s=[];return this.okra.listen(`fs.download.${i}`,o?e:a=>{s.push(a)}),this.okra.invoke("fs.download",{id:i,exclude:t,include:n}).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 C=class extends Error{constructor(t,n){super(t);this.time=n}},F=class r extends C{static fromPromiseTimeoutError(e){return new r(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",n={}){super(t);this.raw=n;this.name="NotebookUnavailableError"}};var ce=(r,e)=>{let t;return Promise.race([r,new Promise((n,i)=>t=setTimeout(i,e,new C("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},le=r=>{let e=null;return()=>e||(e=r())};var Bt=8,Ot=/[\x00-\x1f\x7f]/,$=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 Promise.resolve(this.okra.send("terminal.input",{id:e,input:t}))}listen(e,t){return this.okra.listen(e,t)}async attach(e,t){let n=this.processHandle(e,t?.abortSignal),i=await this.okra.invoke("terminal.attach",{id:e,replayHistory:t?.replayHistory},{abortSignal:t?.abortSignal});return i?{...n.process,...i}:(n.dispose(),!1)}async spawn(e,t,n){let i=n?.id||g(),o=this.processHandle(i,n?.abortSignal),{abortSignal:s,...a}=n??{},c=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:i,...a}},{abortSignal:s});return{...o.process,...c}}processHandle(e,t){let n=new Set,i=()=>{for(let f of n)f.dispose();n.clear()},o="",s,a=()=>{if(s&&(clearTimeout(s),s=void 0),o==="")return;let f=o;o="",this.input(e,f)},c=()=>{s||(s=setTimeout(a,Bt))},h=f=>{if(o+=f,Ot.test(f)){a();return}c()},l=()=>{a(),i()},u=new WritableStream({write:h,close:l,abort:l}),d=null,v=new ReadableStream({start:f=>{d=f,n.add(this.listen(`terminal.output.${e}`,ye=>{d?.enqueue(ye.output)}))},cancel:()=>{d=null,l()}}),p=new Promise(f=>{n.add(this.listen(`terminal.close.${e}`,ye=>{if(d)try{d.close()}catch{}l(),f(ye.exitCode)}))}),w=le(()=>(l(),this.okra.invoke("terminal.close",{id:e}))),Pt=f=>{this.okra.invoke("terminal.resize",{id:e,width:f.cols,height:f.rows})};return t&&t.addEventListener("abort",w),{process:{exit:p,input:u,output:v,kill:w,resize:Pt},dispose:l}}};var Ft=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(Ft||{}),H=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",n=>{for(let i of n)t.some(o=>o.port===i.port)||e(i,"open");for(let i of t)n.some(o=>o.port===i.port)||e(i,"close");t=n})}};var W=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var K=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,n){this.okra.listen(`${t}.${e}`,i=>n(i))}onClose(e,t){this.listen(e,"lsp.closed",n=>t(n.code,n.reason))}onError(e,t){this.listen(e,"lsp.error",n=>t(n.message))}onClientDisconnect(e){this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){this.listen(e,"lsp.response",n=>t(JSON.stringify(n)))}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={},n={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:n})}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="",n={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:n})}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 nt(r,e=[],t){let n=Array.isArray(e)?e:[],i=Array.isArray(e)?t:e;return{command:Array.isArray(r)?r:n.length>0?[r,...n]:r,opts:i}}var Te=class extends Error{constructor(t,n){super(t);this.output=t;this.exitCode=n}},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=[],n){let i=nt(e,t,n),{abortSignal:o,...s}=i.opts??{},a=await this.okra.invoke("shell.exec",{command:i.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new Ie(a.output,a.exitCode)}execStream(e,t=[],n){let i=nt(e,t,n),o=i.opts?.id||g(),s=new Set,a=null,c=!1,h=()=>{for(let p of s)p.dispose();s.clear()},l=()=>{if(!c&&(c=!0,h(),a))try{a.close()}catch{}},u=p=>{c||(c=!0,h(),a&&a.error(p))},d=new ReadableStream({start:p=>{a=p,s.add(this.listen(`shell.output.${o}`,w=>{a?.enqueue(w.output)}))},cancel:()=>{c=!0,h()}}),v=this.exec(i.command,{...i.opts,id:o}).then(p=>(l(),p)).catch(p=>{throw u(p),p});return{output:d,result:v}}};var $t=["redis"],Zn=["start","nginx",...$t],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(n=>{if(!("output"in n))throw new Error(`Unexpected service.logs response for ${e}`);return n.output})}followLogs(e,t){let n=t.id||g(),i=new Set,o=null,s=!1,a=()=>{for(let d of i)d.dispose();i.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},h=d=>{s||(s=!0,a(),o&&o.error(d))},l=le(()=>(c(),this.okra.invoke("service.stop-logs",{id:n}))),u=new ReadableStream({start:d=>{o=d,i.add(this.onLog(n,v=>{o?.enqueue(v.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:n}).catch(v=>{h(v)})},cancel:()=>{l()}});return{id:n,output:u,stop:l}}};function it(r){let e=r.length,t=0,n=0;for(;n<e;){let i=r.charCodeAt(n++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&n<e){let o=r.charCodeAt(n);(o&64512)===56320&&(++n,i=((i&1023)<<10)+(o&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function Ht(r,e,t){let n=r.length,i=t,o=0;for(;o<n;){let s=r.charCodeAt(o++);if((s&4294967168)===0){e[i++]=s;continue}else if((s&4294965248)===0)e[i++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){let a=r.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[i++]=s>>12&15|224,e[i++]=s>>6&63|128):(e[i++]=s>>18&7|240,e[i++]=s>>12&63|128,e[i++]=s>>6&63|128)}e[i++]=s&63|128}}var Wt=new TextEncoder,Kt=50;function zt(r,e,t){Wt.encodeInto(r,e.subarray(t))}function rt(r,e,t){r.length>Kt?zt(r,e,t):Ht(r,e,t)}var Gt=4096;function Pe(r,e,t){let n=e,i=n+t,o=[],s="";for(;n<i;){let a=r[n++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=r[n++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=r[n++]&63,h=r[n++]&63;o.push((a&31)<<12|c<<6|h)}else if((a&248)===240){let c=r[n++]&63,h=r[n++]&63,l=r[n++]&63,u=(a&7)<<18|c<<12|h<<6|l;u>65535&&(u-=65536,o.push(u>>>10&1023|55296),u=56320|u&1023),o.push(u)}else o.push(a);o.length>=Gt&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var Qt=new TextDecoder,qt=200;function Vt(r,e,t){let n=r.subarray(e,e+t);return Qt.decode(n)}function ot(r,e,t){return t>qt?Vt(r,e,t):Pe(r,e,t)}var _=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 n=t/4294967296,i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function ue(r,e,t){let n=Math.floor(t/4294967296),i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function he(r,e){let t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function at(r,e){let t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}var Xt=-1,Jt=4294967296-1,Yt=17179869184-1;function jt({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Yt)if(e===0&&r<=Jt){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{let t=r/4294967296,n=r&4294967295,i=new Uint8Array(8),o=new DataView(i.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,n),i}else{let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),ue(n,4,r),t}}function Zt(r){let e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,i=Math.floor(n/1e9);return{sec:t+i,nsec:n-i*1e9}}function en(r){if(r instanceof Date){let e=Zt(r);return jt(e)}else return null}function tn(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),n=e.getUint32(4),i=(t&3)*4294967296+n,o=t>>>2;return{sec:i,nsec:o}}case 12:{let t=he(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new m(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function nn(r){let e=tn(r);return new Date(e.sec*1e3+e.nsec/1e6)}var ct={type:Xt,encode:en,decode:nn};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ct)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let i=this.builtInEncoders[n];if(i!=null){let o=i(e,t);if(o!=null){let s=-1-n;return new _(s,o)}}}for(let n=0;n<this.encoders.length;n++){let i=this.encoders[n];if(i!=null){let o=i(e,t);if(o!=null){let s=n;return new _(s,o)}}}return e instanceof _?e:null}decode(e,t,n){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new _(t,e)}};S.defaultCodec=new S;function rn(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):rn(r)?new Uint8Array(r):Uint8Array.from(r)}var on=100,sn=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??on,this.initialBufferSize=e?.initialBufferSize??sn,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),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n}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 n=it(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),rt(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,t){let n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);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 n=J(e);this.writeU8a(n)}encodeArray(e,t){let n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let n=0;for(let i of t)e[i]!==void 0&&n++;return n}encodeMap(e,t){let n=Object.keys(e);this.sortKeys&&n.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(let o of n){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 n=e.data(this.pos+6),i=n.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(n);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 Ce(r,e){return new pe(e).encodeSharedRef(r)}function de(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var an=16,cn=16,me=class{constructor(e=an,t=cn){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let i=this.caches[n-1];e:for(let o of i){let s=o.bytes;for(let a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,t,n){let i=this.find(e,t,n);if(i!=null)return this.hit++,i;this.miss++;let o=Pe(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o}};var _e="array",Z="map_key",ut="map_value",ln=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=_e,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===_e){let n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===Z||e.type===ut){let n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},j=-1,Ne=new DataView(new ArrayBuffer(0)),un=new Uint8Array(Ne.buffer);try{Ne.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"),hn=new me,fe=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Ne,this.bytes=un,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:hn,this.mapKeyConverter=e?.mapKeyConverter??ln}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),n=J(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} 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,n;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=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 n}let{headByte:i,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${de(i)} 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 n=t,i=-1;for await(let o of e){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==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 i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e<160){let i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else{let i=e-160;t=this.decodeString(i,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 i=this.lookU8();t=this.decodeString(i,1)}else if(e===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(e===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(e===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(e===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(e===198){let i=this.lookU32();t=this.decodeBinary(i,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 i=this.lookU8();t=this.decodeExtension(i,1)}else if(e===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(e===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new m(`Unrecognized type byte: ${de(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let i=n.top();if(i.type===_e)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,n.release(i);else continue e;else if(i.type===Z){if(t==="__proto__")throw new m("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=ut;continue e}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,n.release(i);else{i.key=null,i.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 n=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,n,e):i=ot(this.bytes,n,e),this.pos+=t+e,i}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 n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new m(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,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 Ae(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,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])},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 fn(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 gn(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function bn(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(gn(arguments[e]));return r}var vt=(function(){function r(e,t){this.target=t,this.type=e}return r})(),vn=(function(r){bt(e,r);function e(t,n){var i=r.call(this,"error",n)||this;return i.message=t.message,i.error=t,i}return e})(vt),yn=(function(r){bt(e,r);function e(t,n,i){t===void 0&&(t=1e3),n===void 0&&(n="");var o=r.call(this,"close",i)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return e})(vt);var wn=function(){if(typeof WebSocket<"u")return WebSocket},xn=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},N={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},kn=(function(){function r(e,t,n){var i=this;n===void 0&&(n={}),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){i._debug("open event");var s=i._options.minUptime,a=s===void 0?N.minUptime:s;clearTimeout(i._connectTimeout),i._uptimeTimeout=setTimeout(function(){return i._acceptOpen()},a),i._ws.binaryType=i._binaryType,i._messageQueue.forEach(function(c){return i._ws.send(c)}),i._messageQueue=[],i.onopen&&i.onopen(o),i._listeners.open.forEach(function(c){return i._callEventListener(o,c)})},this._handleMessage=function(o){i._debug("message event"),i.onmessage&&i.onmessage(o),i._listeners.message.forEach(function(s){return i._callEventListener(o,s)})},this._handleError=function(o){i._debug("error event",o.message),i._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),i.onerror&&i.onerror(o),i._debug("exec error listeners"),i._listeners.error.forEach(function(s){return i._callEventListener(o,s)}),i._connect()},this._handleClose=function(o){i._debug("close event"),i._clearTimeouts(),i._shouldReconnect&&i._connect(),i.onclose&&i.onclose(o),i._listeners.close.forEach(function(s){return i._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=n,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,n){return typeof n=="string"?t+=n.length:n instanceof Blob?t+=n.size:t+=n.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,n=t===void 0?N.maxEnqueuedMessages:t;this._messageQueue.length<n&&(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,n,i=this._listeners[e.type];if(i)try{for(var o=fn(i),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&&(n=o.return)&&n.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(n){return n!==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,bn(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=t===void 0?N.reconnectionDelayGrowFactor:t,i=e.minReconnectionDelay,o=i===void 0?N.minReconnectionDelay:i,s=e.maxReconnectionDelay,a=s===void 0?N.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(n,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,n=t.maxRetries,i=n===void 0?N.maxRetries:n,o=t.connectionTimeout,s=o===void 0?N.connectionTimeout:o,a=t.WebSocket,c=a===void 0?wn():a;if(this._retryCount>=i){this._debug("max retries reached",this._retryCount,">=",i);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!xn(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 vn(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 yn(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=kn;var En=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},Sn=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 n=typeof e.name=="string"&&e.name?e.name:void 0;return n?`${n}: ${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=[],n=wt(e);n&&t.push(n);let i=wt(e.error);i&&i!==n&&t.push(`error=${i}`),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!==n&&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=${Sn(o.url)}`);let s=En(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var L=null;typeof WebSocket<"u"?L=WebSocket:typeof MozWebSocket<"u"?L=MozWebSocket:typeof global<"u"?L=global.WebSocket||global.MozWebSocket:typeof window<"u"?L=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(L=self.WebSocket||self.MozWebSocket);var xt=L;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,n){super(t);this.originalError=n;this.name="ConnectionFailedError"}},A=class extends Error{constructor(t,n){super(t);this.data=n;this.name="InvalidMessageError"}},R=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},T,Me,Be,te=class{constructor(e,t,n={}){this.eventEmitter=t;this.options=n;B(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.incomingMessageChain=Promise.resolve();this.validateConfiguration(n),this.url=new URL(e),this.PING_INTERVAL=n.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=n.connectWaitTimeout??3e4,this.connectionStats.connectionStartTime=Date.now();let i=n.startClosed!==!1;this.rws=new yt(this.url.toString(),[],{WebSocket:n.webSocket??globalThis.WebSocket??xt,connectionTimeout:n.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:n.maxRetries??50,startClosed:i}),this.log("debug","Transport initialized",{url:this.url.toString(),options:n}),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,n){if(this.options.debug){let i=new Date().toISOString(),o=n?JSON.stringify(n,null,2):"";console[e](`[Transport ${i}] ${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=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(t)).catch(n=>{this.connectionStats.totalErrors++,this.log("error","Failed to process queued WebSocket frame",{error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:n,rawMessage:t.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){if(!(e.data instanceof Blob)){let i=new Error("Unexpected message type: "+typeof e.data);this.connectionStats.totalErrors++,this.log("error","Unexpected WebSocket message type",{error:i.message,messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:i,rawMessage:e.data,timestamp:Date.now()});return}let t=await e.data.arrayBuffer();if(t.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let n;try{n=Ae(t)}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to decode WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:i,rawMessage:t,timestamp:Date.now()});return}try{await this.handleRawMessage(n)}catch(i){this.connectionStats.totalErrors++,this.log("error","Failed to process WebSocket frame",{error:i instanceof Error?i.message:String(i),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:t,timestamp:Date.now()})}}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:n,as:i}=e;if(!n||typeof n!="string")throw new A("Message missing event field",e);if(this.log("debug","Processing message",{event:n,hasData:!!t}),n==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(n==="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(n==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new A("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(n==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new A("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(n,t,i)}catch(t){this.connectionStats.totalErrors++,t instanceof A?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,n){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,t.id);return}e&&this.eventEmitter.emit(n||e,t)}listen(e,t,n){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,n){this.eventEmitter.once(e,t,n),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={},n={}){if(this.terminalError)throw this.terminalError;this.clearOldQueuedMessages();let i=n.responseEvent||`${e}_${g()}_response`,o=`${i}_error`,s,a=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),this.eventEmitter.removeListener(i),this.eventEmitter.removeListener(o)},c=async(l,u)=>{if(this.terminalError){u(this.terminalError);return}let d=new DOMException("Request aborted","AbortError");if(n.abortSignal?.aborted&&u(d),n.abortSignal&&n.abortSignal.addEventListener("abort",()=>{u(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:n,resolve:l,reject:u,timestamp:Date.now()});return}let v=Date.now();this.listenOnce(i,p=>{let w=Date.now()-v;this.connectionStats.avgResponseTime=(this.connectionStats.avgResponseTime+w)/2,this.connectionStats.totalMessages++,this.log("debug","Message response received",{action:e,responseTime:w,avgResponseTime:this.connectionStats.avgResponseTime}),l(p)}),this.listenOnce(o,p=>{this.connectionStats.totalErrors++,this.log("error","Message error received",{action:e,error:p}),u(new y(p.code,p.message,p))}),s=p=>{if(p.code===1008&&(p.reason||"").includes("rate limit")){u(new O(p.reason||"Rate limit exceeded",p));return}let w=ee(p);u(this.terminalError||new be(`Connection lost to the notebook during request: ${w}`,p))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:i})),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 l=new Promise(c).finally(a);return n.timeout?ce(l,n.timeout).catch(u=>{throw u instanceof C?F.fromPromiseTimeoutError(u):u}).finally(a):l};return this.sendWithRetry(async()=>await h(),n.retries||10)}send(e,t={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:t})),this.connectionStats.totalMessages++,this.log("debug","One-way message sent",{action:e,data:t}),!0}catch(n){return this.connectionStats.totalErrors++,this.log("error","Failed to send one-way message",{action:e,error:n}),!1}}pack(e){return new Blob([Ce(e)])}sendWithRetry(e,t=10){return(0,kt.default)(async(n,i)=>{try{return await e()}catch(o){if(o instanceof y||o instanceof O||o instanceof R||o instanceof A||o instanceof E||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:i}),n(o);return}throw o instanceof F&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:i,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:i,error:o instanceof Error?o.message:String(o),nextDelay:this.getBackoffDelay(i-1)}),o}},{retries:t,onRetry:(n,i)=>{this.log("warn","Send operation retry",{attempt:i,maxRetries:t,error:n instanceof Error?n.message:String(n)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},n={}){return n.responseEvent||(n.responseEvent=`${e}_${g()}`),this.call("invoke",{action:e,data:t},n)}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,n=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,n)}close(e,t){if(this.closed)return;this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null;let n=this.messageQueue.length,i=this.terminalError||new Error("Connection closed while message was queued");this.messageQueue.forEach(o=>{o.reject(i)}),this.messageQueue=[],n>0&&this.log("debug",`Rejected ${n} queued messages due to connection close`),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(n=>{let i=e-n.timestamp>this.QUEUE_TIMEOUT;return i&&n.reject(new Error("Queued message expired")),!i}),t!==this.messageQueue.length&&this.log("debug",`Cleared ${t-this.messageQueue.length} expired messages`)}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(n=>n.timestamp)):0},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(),n=[],i=[];return this.isConnected||(n.push("Connection is not established"),i.push("Check network connectivity and server availability")),e.connectionStats.timeSinceLastPong>this.PING_INTERVAL*2&&(n.push("No pong received recently - connection may be stale"),i.push("Consider forcing a reconnection")),Number.parseFloat(e.connectionStats.errorRate)>10&&(n.push(`High error rate: ${e.connectionStats.errorRate}`),i.push("Check server logs and network stability")),e.messageQueue.length>this.MAX_QUEUE_SIZE*.8&&(n.push("Message queue is nearly full"),i.push("Check connection stability and consider reducing message frequency")),e.connectionStats.avgResponseTime>5e3&&(n.push("High average response time"),i.push("Check network latency and server performance")),this.log("info","Connection diagnostics completed",{status:t,issueCount:n.length,recommendationCount:i.length}),{status:t,metrics:e,issues:n,recommendations:i}}startPeriodicMaintenance(){this.disposables.add("maintenance",()=>{let e=setInterval(()=>{if(this.clearOldQueuedMessages(),this.options.debug){let t=this.getHealthStatus(),n=this.getConnectionMetrics();this.log("debug","Periodic health check",{health:t,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 n,i=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(n)},s=()=>{o(),this.connectPromise=null,e(),k(this,T,Be).call(this)},a=h=>{i+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:i,error:ee(h)})},c=h=>{let l=ee(h);if("code"in h&&(h.code===1008||h.code===4e3)){o(),this.connectPromise=null,t(new be(`WebSocket connection failed: ${l}`,h));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:l})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),n=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 n=this.connectionStats.lastPongTime-t;this.log("debug","Ping successful",{pingTime:n})}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 n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}function Tn(r){let e=Et(r);return e.once=(t,n)=>{e.on(t,n),e.on(t,e.off.bind(e,t,n))},e}var U=class r{constructor(){this.emitter=Tn()}listen(e,t){let n=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:n}}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 ne=class{constructor(e){this.okra=e}checkpoint(e,t,n="main",i=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:n,allowEmpty:i})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,n="main",i,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:n,token:i,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 ie=class{constructor(e,t,n){this.onEvent=e;this.onceEvent=t;this.beacon=n;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=n,this.setupUrlChangeListener(),this.urlHistory.push(n.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 M=class extends Error{constructor(t,n){super(t);this.code=n;this.name="BeaconError"}},ve=class extends M{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},x=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;St(),this.iframe=e;let n={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...n,...t.retry},...t},this.eventEmitter=U.make(),this.setupMessageChannel(),this.navigator=new ie(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 n=t.data;if(!n||typeof n!="object"||!n.type)return;n.type==="beacon:ready-for-channel"&&this.establishChannel().catch(i=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",i)}),n.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",n.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(n){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",n)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new x("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,n)=>{let i=setTimeout(()=>{n(new x("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(i),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 n=this.messageHandlers.get(e.type);n&&n.forEach(i=>{try{i(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 n=this.options.timeout,i=setTimeout(()=>{t(new ve("beacon ready",n))},n),o=this.on("ready",()=>{clearTimeout(i),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 n=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,n)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new x("MessagePort not available - channel not established");let n={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(n),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",n.type,n.payload)}catch(i){throw new x(`Failed to send message via port: ${i instanceof Error?i.message:String(i)}`)}}async sendAndWaitFor(e,t,n={},i){return await this.ready(),(0,Oe.default)(async o=>new Promise((s,a)=>{let c=i||this.options.timeout,h=setTimeout(()=>{l.dispose();let u=new ve(e,c);a(u)},c),l=this.eventEmitter.listen(t,u=>{clearTimeout(h),l.dispose(),s(u)});try{this.sendMessage(e,n)}catch(u){clearTimeout(h),l.dispose(),u instanceof x?a(u):o(u)}}),{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 n=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==n&&(this.navigator.visit(n),await this.ready()),t&&await this.wait(t);let i=(e.options?.timeout||3e4)+5e3;return this.sendAndWaitFor("debug","debugResult",e,i)}async wait(e){return new Promise(t=>setTimeout(t,e*1e3))}navigate(e){if(!this.iframe)throw new x("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 x(`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 mr(){try{return St(),!0}catch{return!1}}function In(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,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},He=class extends Error{constructor(t,n){super(`PHPSandbox API Error: ${t.status} ${t.statusText} - ${n}`);this.response=t;this.body=n;this.status=t.status}},We=class{constructor(e){this.client=e;this.secrets=new ze(e),this.preview=new Ge(e),this.mail=new Qe(e)}async create(e,t={},n=!0){let i=await this.client.post("/notebook",{template:e,...t}),o=new I(i.data,this.client);return n?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 n=await this.client.put(`/notebook/${e}`,t);return new I(n.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}},Ke=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.notebook=new We(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=t,n.fetch&&(this.fetch=n.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,n){let i=await this.fetch(new Request(new URL(`v1/${t.replace(/^\//,"")}`,this.baseUrl),{method:e,...n,headers:this.headers}));if(!i.ok)throw new He(i,await i.text());if(i.status===204)return{data:void 0};let o=await i.text();return{data:o===""?void 0:JSON.parse(o)}}},It=class extends Ke{},ze=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let i=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,i)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:In(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`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},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${Pn(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)}`)}},P,re,qe,I=class{constructor(e,t){this.data=e;this.client=t;B(this,re);this.initialized=!1;B(this,P);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,P,k(this,re,qe).call(this)),this.file=new ae(this),this.terminal=new $(this),this.auth=new W(this),this.lsp=new K(this),this.composer=new z(this),this.log=new G(this),this.repl=new q(this),this.container=new H(this),this.laravel=new Q(this),this.shell=new V(this),this.git=new ne(this),this.services=new X(this),this.secrets=new Ve(t,this.data.id),this.preview=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,P)))()}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={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}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,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidClose(()=>n(new Error("Connection closed"))),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}whenConnected(){let e=this.socket.getTerminalError();return e?Promise.reject(e):this.socket.isConnected?Promise.resolve(this):new Promise((t,n)=>{try{this.socket.onDidConnect(()=>t(this)),this.socket.onDidBootError(i=>n(i))}catch(i){n(i)}})}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 n=await this.ready();return e.src=n.data.previewUrl,Tt(e,t)}};P=new WeakMap,re=new WeakSet,qe=function(){return xe(this,P,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(i.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new $e(o.message,o.data));return}e(o)}),i=this.onDidBootError(o=>{n.dispose(),i.dispose(),t(o)})})),se(this,P).catch(()=>{}),se(this,P)};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.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},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 Pn(r){let e=new URLSearchParams;for(let[n,i]of Object.entries(r))(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&e.set(n,String(i));let t=e.toString();return t===""?"":`?${t}`}export{He as ApiError,Fe as Beacon,x as BeaconConnectionError,M as BeaconError,ve as BeaconTimeoutError,Ke as Client,Te as CommandError,y as ErrorEvent,Lt as FileChangeType,Ut as FileType,ae as Filesystem,ke as FilesystemError,Mt as FilesystemErrorType,Se as LspConnection,ie as Navigator,We as NotebookApi,$e as NotebookInitError,I as NotebookInstance,Je as NotebookMail,Qe as NotebookMailApi,Xe as NotebookPreview,Ge as NotebookPreviewApi,ze as NotebookSecretApi,Ve as NotebookSecrets,Ft as NotebookState,E as NotebookUnavailableError,It as PHPSandbox,et as PHPSandboxError,C as PromiseTimeoutError,O as RateLimitError,F as SendTimeoutError,te as Transport,Tt as createBeacon,mr as isBeaconSupported,$t as notebookBuiltinServices,Zn as notebookKnownServices,le as once,ce as timeout};
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
reconnecting-websocket/dist/reconnecting-websocket-mjs.js:
|