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