@phpsandbox/sdk 0.0.55 → 0.0.56
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.
|
@@ -5120,7 +5120,7 @@ var NotebookInstance = class {
|
|
|
5120
5120
|
return this.container.stop();
|
|
5121
5121
|
}
|
|
5122
5122
|
restart() {
|
|
5123
|
-
return this.container.
|
|
5123
|
+
return this.container.restart();
|
|
5124
5124
|
}
|
|
5125
5125
|
invoke(action, data = {}, options = {}) {
|
|
5126
5126
|
return this.socket.invoke(action, data || {}, options);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var Dt=Object.defineProperty;var it=i=>{throw TypeError(i)};var ot=(i,e)=>{for(var t in e)Dt(i,t,{get:e[t],enumerable:!0})};var De=(i,e,t)=>e.has(i)||it("Cannot "+t);var ae=(i,e,t)=>(De(i,e,"read from private field"),t?t.call(i):e.get(i)),B=(i,e,t)=>e.has(i)?it("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ie=(i,e,t,n)=>(De(i,e,"write to private field"),n?n.call(i,t):e.set(i,t),t),x=(i,e,t)=>(De(i,e,"access private method"),t);var v=class extends Error{constructor(t,n,r={}){super(n);this.code=t;this.message=n;this.raw=r}},O=class extends v{constructor(e,t={}){super(429,e,t)}},st=class extends v{};var at="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var f=(i=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(i|=0));for(;i--;)e+=at[t[i]&63];return e};var It=(r=>(r[r.Unknown=0]="Unknown",r[r.File=1]="File",r[r.Directory=2]="Directory",r[r.SymbolicLink=64]="SymbolicLink",r))(It||{}),Pt=(n=>(n[n.UPDATED=2]="UPDATED",n[n.ADDED=4]="ADDED",n[n.DELETED=8]="DELETED",n))(Pt||{}),Tt=(n=>(n[n.UPDATED=1]="UPDATED",n[n.ADDED=2]="ADDED",n[n.DELETED=3]="DELETED",n))(Tt||{}),Ct=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(Ct||{}),Pe=class extends v{constructor(t,n){super(t.code,t.message);this.name=n}},Te=class{constructor(e,t){this.disposable=e;this.onDispose=t;this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposable.dispose(),this.onDispose())}},ce=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t}of this.watches.values())this.okra.invoke("fs.watch",{path:e,options:t}).catch(()=>{})})}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:{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1,...t}})}search(e,t,n){e.id||(e.id=f());let r={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,s=async c=>{c===!1&&a.dispose(),n&&await Promise.resolve(n(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...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 n=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return n instanceof Uint8Array?n:typeof n=="string"?new TextEncoder().encode(n):n}catch(n){this.handleError(n)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(n=>this.handleError(n))}writeFile(e,t,n){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:n}).catch(r=>this.handleError(r))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,n){return this.okra.invoke("fs.rename",{from:e,to:t,options:n}).catch(r=>this.handleError(r))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(n=>this.handleError(n))}copy(e,t,n){return this.okra.invoke("fs.copy",{source:e,destination:t,options:n}).catch(r=>this.handleError(r))}readDirectory(e,t=[],n=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:n}).catch(r=>this.handleError(r))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,n){let r=this.okra.listen(`fs.watch.${e}`,n),o={dispose:()=>{r.dispose(),this.okra.invoke("fs.unwatch",{path:e}).catch(()=>{})}},s=new Te(o,()=>{this.watches.get(e)?.onDidChange===n&&this.watches.delete(e)});return this.watches.set(e,{options:t,path:e,onDidChange:n}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>s).catch(a=>{throw s.dispose(),a})}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,n){let r=f(),o=!!e,s=[],a=this.okra.listen(`fs.download.${r}`,o?e:c=>{s.push(c)});return this.okra.invoke("fs.download",{id:r,exclude:t,include:n}).then(()=>new Blob(s,{type:"application/octet-stream"})).finally(()=>a.dispose())}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof v&&"name"in e.raw?new Pe(e,e.raw.name):e}};var C=class extends Error{constructor(t,n){super(t);this.time=n}},F=class i extends C{static fromPromiseTimeoutError(e){return new i(e.message,e.time)}},E=class extends Error{constructor(t="Notebook is no longer available",n={}){super(t);this.raw=n;this.name="NotebookUnavailableError"}};var le=(i,e)=>{let t;return Promise.race([i,new Promise((n,r)=>t=setTimeout(r,e,new C("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},ue=i=>{let e=null;return()=>e||(e=i())};var Rt=8,At=/[\x00-\x1f\x7f]/,$=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}start(){return this.okra.invoke("terminal.start")}create(e){return this.okra.invoke("terminal.create",e)}onStarted(e){return 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){return this.okra.listen(`terminal.output.${e}`,t)}input(e,t){return Promise.resolve(this.okra.send("terminal.input",{id:e,input:t}))}listen(e,t){return this.okra.listen(e,t)}async attach(e,t){let n=this.processHandle(e,t?.abortSignal);try{let r=await this.okra.invoke("terminal.attach",{id:e,replayHistory:t?.replayHistory},{abortSignal:t?.abortSignal});return r?{...n.process,...r}:(n.dispose(),!1)}catch(r){throw n.dispose(),r}}async spawn(e,t,n){let r=n?.id||f(),o=this.processHandle(r,n?.abortSignal),{abortSignal:s,...a}=n??{};try{let c=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:r,...a}},{abortSignal:s});return{...o.process,...c}}catch(c){throw o.dispose(),c}}processHandle(e,t){let n=new Set,r,o=()=>{r&&(t?.removeEventListener("abort",r),r=void 0);for(let y of n)y.dispose();n.clear()},s="",a,c=()=>{if(a&&(clearTimeout(a),a=void 0),s==="")return;let y=s;s="",this.input(e,y)},l=()=>{a||(a=setTimeout(c,Rt))},h=y=>{if(s+=y,At.test(y)){c();return}l()},u=()=>{c(),o()},g=new WritableStream({write:h,close:u,abort:u}),p=null,m=new ReadableStream({start:y=>{p=y,n.add(this.listen(`terminal.output.${e}`,Se=>{p?.enqueue(Se.output)}))},cancel:()=>{p=null,u()}}),d=new Promise(y=>{n.add(this.listen(`terminal.close.${e}`,Se=>{if(p)try{p.close()}catch{}u(),y(Se.exitCode)}))}),k=ue(()=>(u(),this.okra.invoke("terminal.close",{id:e}))),St=y=>{this.okra.invoke("terminal.resize",{id:e,width:y.cols,height:y.rows})};return t&&!t.aborted&&(r=()=>{k()},t.addEventListener("abort",r,{once:!0})),{process:{exit:d,input:g,output:m,kill:k,resize:St},dispose:u}}};var Nt=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(Nt||{}),G=class{constructor(e){this.okra=e}start(){return this.okra.invoke("container.start")}restart(){return this.okra.invoke("container.restart")}stop(){return this.okra.invoke("container.stop")}state(){return this.okra.invoke("container.state")}openedPorts(){return this.okra.invoke("container.opened-ports")}setPhp(e){return this.okra.invoke("container.set-php",{version:e})}enableTelemetry(e){return this.okra.invoke("container.stream-telemetry",{features:Array.from(e)})}stopTelemetry(){return this.okra.invoke("container.stop-telemetry")}listen(e,t){return this.okra.listen(e,t)}onPort(e){let t=[];return this.listen("container.ports",n=>{for(let r of n)t.some(o=>o.port===r.port)||e(r,"open");for(let r of t)n.some(o=>o.port===r.port)||e(r,"close");t=n})}};var W=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var H=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,n){return this.okra.listen(`${t}.${e}`,r=>n(r))}onClose(e,t){return this.listen(e,"lsp.closed",n=>t(n.code,n.reason))}onError(e,t){return this.listen(e,"lsp.error",n=>t(n.message))}onClientDisconnect(e){return this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){return this.listen(e,"lsp.response",n=>t(JSON.stringify(n)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return Ce.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},Ce=class i{constructor(e,t){this.id=e;this.lsp=t}send(e){return this.lsp.message(this.id,e)}onMessage(e){return this.lsp.onResponse(this.id,e)}onError(e){return this.lsp.onError(this.id,e)}onClose(e){return this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){return this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,t){return new i(e,t)}};var z=class{constructor(e){this.okra=e}invoke(e,t={},n={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:n})}dumpAutoload(){return this.okra.invoke("composer.dump-autoload")}install(e={}){return this.invoke("install",{},e)}update(e,t={}){return this.invoke("update",e,t)}require(e,t={}){return this.invoke("require",e,t)}remove(e,t={}){return this.invoke("remove",e,t)}stream(e){return this.okra.listen("composer.log",e)}packages(){return this.okra.invoke("composer.packages")}};var K=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){return 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 j=class{constructor(e){this.okra=e}eval(e,t="",n={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:n})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}start(){return this.okra.invoke("repl.start")}resize(e,t){return this.okra.invoke("repl.resize",{cols:e,rows:t})}listen(e,t){return this.okra.listen(e,t)}onOutput(e){return this.okra.listen("repl.output",e)}};function ct(i,e=[],t){let n=Array.isArray(e)?e:[],r=Array.isArray(e)?t:e;return{command:Array.isArray(i)?i:n.length>0?[i,...n]:i,opts:r}}var Re=class extends Error{constructor(t,n){super(t);this.output=t;this.exitCode=n}},Ae=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new Re(this.output,this.exitCode);return this}},V=class{constructor(e){this.okra=e}onOutput(e,t){return this.okra.listen(`shell.output.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}async exec(e,t=[],n){let r=ct(e,t,n),{abortSignal:o,...s}=r.opts??{},a=await this.okra.invoke("shell.exec",{command:r.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new Ae(a.output,a.exitCode)}execStream(e,t=[],n){let r=ct(e,t,n),o=r.opts?.id||f(),s=new Set,a=null,c=!1,l=()=>{for(let m of s)m.dispose();s.clear()},h=()=>{if(!c&&(c=!0,l(),a))try{a.close()}catch{}},u=m=>{c||(c=!0,l(),a&&a.error(m))},g=new ReadableStream({start:m=>{a=m,s.add(this.listen(`shell.output.${o}`,d=>{a?.enqueue(d.output)}))},cancel:()=>{c=!0,l()}}),p=this.exec(r.command,{...r.opts,id:o}).then(m=>(h(),m)).catch(m=>{throw u(m),m});return{output:g,result:p}}};var _t=["redis"],Zn=["start","nginx",..._t],J=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,t){return this.okra.invoke("service.run",{name:e,command:t})}stop(e){return this.okra.invoke("service.stop",{name:e})}onLog(e,t){return this.okra.listen(`service.log.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}logs(e,t={}){return t.follow?this.followLogs(e,t):this.okra.invoke("service.logs",{name:e,tail:t.tail}).then(n=>{if(!("output"in n))throw new Error(`Unexpected service.logs response for ${e}`);return n.output})}followLogs(e,t){let n=t.id||f(),r=new Set,o=null,s=!1,a=()=>{for(let g of r)g.dispose();r.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},l=g=>{s||(s=!0,a(),o&&o.error(g))},h=ue(()=>(c(),this.okra.invoke("service.stop-logs",{id:n}))),u=new ReadableStream({start:g=>{o=g,r.add(this.onLog(n,p=>{o?.enqueue(p.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:n}).catch(p=>{l(p)})},cancel:()=>{h()}});return{id:n,output:u,stop:h}}};var Q=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function lt(i){let e=i.length,t=0,n=0;for(;n<e;){let r=i.charCodeAt(n++);if((r&4294967168)===0){t++;continue}else if((r&4294965248)===0)t+=2;else{if(r>=55296&&r<=56319&&n<e){let o=i.charCodeAt(n);(o&64512)===56320&&(++n,r=((r&1023)<<10)+(o&1023)+65536)}(r&4294901760)===0?t+=3:t+=4}}return t}function Ut(i,e,t){let n=i.length,r=t,o=0;for(;o<n;){let s=i.charCodeAt(o++);if((s&4294967168)===0){e[r++]=s;continue}else if((s&4294965248)===0)e[r++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){let a=i.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128):(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128)}e[r++]=s&63|128}}var Lt=new TextEncoder,Mt=50;function Bt(i,e,t){Lt.encodeInto(i,e.subarray(t))}function ut(i,e,t){i.length>Mt?Bt(i,e,t):Ut(i,e,t)}var Ot=4096;function Ne(i,e,t){let n=e,r=n+t,o=[],s="";for(;n<r;){let a=i[n++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=i[n++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=i[n++]&63,l=i[n++]&63;o.push((a&31)<<12|c<<6|l)}else if((a&248)===240){let c=i[n++]&63,l=i[n++]&63,h=i[n++]&63,u=(a&7)<<18|c<<12|l<<6|h;u>65535&&(u-=65536,o.push(u>>>10&1023|55296),u=56320|u&1023),o.push(u)}else o.push(a);o.length>=Ot&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var Ft=new TextDecoder,$t=200;function Gt(i,e,t){let n=i.subarray(e,e+t);return Ft.decode(n)}function pt(i,e,t){return t>$t?Gt(i,e,t):Ne(i,e,t)}var R=class{constructor(e,t){this.type=e,this.data=t}};var b=class i extends Error{constructor(e){super(e);let t=Object.create(i.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:i.name})}};function dt(i,e,t){let n=t/4294967296,r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function pe(i,e,t){let n=Math.floor(t/4294967296),r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function de(i,e){let t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function ht(i,e){let t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}var Wt=-1,Ht=4294967296-1,zt=17179869184-1;function Kt({sec:i,nsec:e}){if(i>=0&&e>=0&&i<=zt)if(e===0&&i<=Ht){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,i),t}else{let t=i/4294967296,n=i&4294967295,r=new Uint8Array(8),o=new DataView(r.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,n),r}else{let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),pe(n,4,i),t}}function qt(i){let e=i.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,r=Math.floor(n/1e9);return{sec:t+r,nsec:n-r*1e9}}function jt(i){if(i instanceof Date){let e=qt(i);return Kt(e)}else return null}function Vt(i){let e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(i.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),n=e.getUint32(4),r=(t&3)*4294967296+n,o=t>>>2;return{sec:r,nsec:o}}case 12:{let t=de(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new b(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${i.length}`)}}function Jt(i){let e=Vt(i);return new Date(e.sec*1e3+e.nsec/1e6)}var mt={type:Wt,encode:jt,decode:Jt};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(mt)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let o=r(e,t);if(o!=null){let s=-1-n;return new R(s,o)}}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let o=r(e,t);if(o!=null){let s=n;return new R(s,o)}}}return e instanceof R?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new R(t,e)}};S.defaultCodec=new S;function Qt(i){return i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer}function X(i){return i instanceof Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):Qt(i)?new Uint8Array(i):Uint8Array.from(i)}var Xt=100,Yt=2048,he=class i{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??S.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Xt,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 i({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let n=lt(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),ut(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,t){let n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let n=X(e);this.writeU8a(n)}encodeArray(e,t){let n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let r of e)this.doEncode(r,t+1)}countWithoutUndefined(e,t){let n=0;for(let r of t)e[r]!==void 0&&n++;return n}encodeMap(e,t){let n=Object.keys(e);this.sortKeys&&n.sort();let r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else if(r<4294967296)this.writeU8(223),this.writeU32(r);else throw new Error(`Too large map object: ${r}`);for(let o of n){let s=e[o];this.ignoreUndefined&&s===void 0||(this.encodeString(o),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let n=e.data(this.pos+6),r=n.length;if(r>=4294967296)throw new Error(`Too large extension object: ${r}`);this.writeU8(201),this.writeU32(r),this.writeI8(e.type),this.writeU8a(n);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),dt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),pe(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(i,e){return new he(e).encodeSharedRef(i)}function me(i){return`${i<0?"-":""}0x${Math.abs(i).toString(16).padStart(2,"0")}`}var Zt=16,en=16,ge=class{constructor(e=Zt,t=en){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];e:for(let o of r){let s=o.bytes;for(let a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let o=Ne(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o}};var Ue="array",ee="map_key",ft="map_value",tn=i=>{if(typeof i=="string"||typeof i=="number")return i;throw new b("The type of key must be string or number but "+typeof i)},Le=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=Ue,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=ee,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===Ue){let n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===ee||e.type===ft){let n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Z=-1,Me=new DataView(new ArrayBuffer(0)),nn=new Uint8Array(Me.buffer);try{Me.getInt8(0)}catch(i){if(!(i 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 gt=new RangeError("Insufficient data"),rn=new ge,fe=class i{constructor(e){this.totalPos=0,this.pos=0,this.view=Me,this.bytes=nn,this.headByte=Z,this.stack=new Le,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:rn,this.mapKeyConverter=e?.mapKeyConverter??tn}clone(){return new i({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=X(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),n=X(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${me(r)} at ${s} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,r=-1;for await(let o of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let r=e-128;if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e<160){let r=e-144;if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else{let r=e-160;t=this.decodeString(r,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let r=this.lookU8();t=this.decodeString(r,1)}else if(e===218){let r=this.lookU16();t=this.decodeString(r,2)}else if(e===219){let r=this.lookU32();t=this.decodeString(r,4)}else if(e===220){let r=this.readU16();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===221){let r=this.readU32();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===222){let r=this.readU16();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===223){let r=this.readU32();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===196){let r=this.lookU8();t=this.decodeBinary(r,1)}else if(e===197){let r=this.lookU16();t=this.decodeBinary(r,2)}else if(e===198){let r=this.lookU32();t=this.decodeBinary(r,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let r=this.lookU8();t=this.decodeExtension(r,1)}else if(e===200){let r=this.lookU16();t=this.decodeExtension(r,2)}else if(e===201){let r=this.lookU32();t=this.decodeExtension(r,4)}else throw new b(`Unrecognized type byte: ${me(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let r=n.top();if(r.type===Ue)if(r.array[r.position]=t,r.position++,r.position===r.size)t=r.array,n.release(r);else continue e;else if(r.type===ee){if(t==="__proto__")throw new b("The key __proto__ is not allowed");r.key=this.mapKeyConverter(t),r.type=ft;continue e}else if(r.map[r.key]=t,r.readCount++,r.readCount===r.size)t=r.map,n.release(r);else{r.key=null,r.type=ee;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 b(`Unrecognized array type byte: ${me(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new b(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new b(`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 b(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw gt;let n=this.pos+t,r;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?r=this.keyDecoder.decode(this.bytes,n,e):r=pt(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ee:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new b(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw gt;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new b(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=ht(this.view,this.pos);return this.pos+=8,e}readI64(){let e=de(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 Be(i,e){return new fe(e).decode(i)}var be=class{constructor(e){this.error=e}},on=i=>new Promise(e=>{setTimeout(e,i)}),sn=(i,e)=>{let t=e.randomize?Math.random()+1:1,n=Math.max(e.minTimeout,1)*Math.pow(e.factor,i-1);return Math.round(Math.min(t*n,e.maxTimeout))};async function te(i,e={}){let t={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},n=o=>{throw new be(o??new Error("Aborted"))},r;for(let o=1;o<=t.retries+1;o++)try{return await i(n,o)}catch(s){if(s instanceof be)throw s.error;if(r=s,o>t.retries)throw s;await e.onRetry?.(s,o),await on(sn(o,t))}throw r}var $e={};ot($e,{default:()=>Fe});var Oe=function(i,e){return Oe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])},Oe(i,e)};function bt(i,e){Oe(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function an(i){var e=typeof Symbol=="function"&&i[Symbol.iterator],t=0;return e?e.call(i):{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}}}function cn(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function ln(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(cn(arguments[e]));return i}var yt=(function(){function i(e,t){this.target=t,this.type=e}return i})(),un=(function(i){bt(e,i);function e(t,n){var r=i.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return e})(yt),pn=(function(i){bt(e,i);function e(t,n,r){t===void 0&&(t=1e3),n===void 0&&(n="");var o=i.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return e})(yt);var dn=function(){if(typeof WebSocket<"u")return WebSocket},hn=function(i){return typeof i<"u"&&!!i&&i.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},mn=(function(){function i(e,t,n){var r=this;n===void 0&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){r._debug("open event");var s=r._options.minUptime,a=s===void 0?A.minUptime:s;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout(function(){return r._acceptOpen()},a),r._ws.binaryType=r._binaryType,r._messageQueue.forEach(function(c){return r._ws.send(c)}),r._messageQueue=[],r.onopen&&r.onopen(o),r._listeners.open.forEach(function(c){return r._callEventListener(o,c)})},this._handleMessage=function(o){r._debug("message event"),r.onmessage&&r.onmessage(o),r._listeners.message.forEach(function(s){return r._callEventListener(o,s)})},this._handleError=function(o){r._debug("error event",o.message),r._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),r.onerror&&r.onerror(o),r._debug("exec error listeners"),r._listeners.error.forEach(function(s){return r._callEventListener(o,s)}),r._connect()},this._handleClose=function(o){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(o),r._listeners.close.forEach(function(s){return r._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(i,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(i,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(i,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"CONNECTING",{get:function(){return i.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"OPEN",{get:function(){return i.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"CLOSING",{get:function(){return i.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"CLOSED",{get:function(){return i.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(i.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(i.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(t,n){return typeof n=="string"?t+=n.length:n instanceof Blob?t+=n.size:t+=n.byteLength,t},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?i.CLOSED:i.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),i.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)},i.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())},i.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=t===void 0?A.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},i.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},i.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var o=an(r),s=o.next();!s.done;s=o.next()){var a=s.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},i.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(n){return n!==t}))},i.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,ln(["RWS>"],e))},i.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=t===void 0?A.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=r===void 0?A.minReconnectionDelay:r,s=e.maxReconnectionDelay,a=s===void 0?A.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(n,this._retryCount-1),c>a&&(c=a)),this._debug("next delay",c),c},i.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},i.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")},i.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=n===void 0?A.maxRetries:n,o=t.connectionTimeout,s=o===void 0?A.connectionTimeout:o,a=t.WebSocket,c=a===void 0?dn():a;if(this._retryCount>=r){this._debug("max retries reached",this._retryCount,">=",r);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!hn(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(l){e._closeCalled||(e._debug("connect",{url:l,protocols:e._protocols}),e._ws=e._protocols?new c(l,e._protocols):new c(l),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},s))})}},i.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new un(Error("TIMEOUT"),this))},i.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 pn(e,t,this))}catch{}}},i.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},i.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},i.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))},i.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))},i.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},i})(),Fe=mn;var gn=i=>{if(typeof i=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[i]??`STATE_${i}`},fn=i=>{try{let e=new URL(i);return`${e.origin}${e.pathname}`}catch{return i}},vt=i=>{if(i instanceof Error)return i.message?`${i.name}: ${i.message}`:i.name;if(typeof i=="string")return i;if(!i||typeof i!="object")return;let e=i,t=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!t)return;let n=typeof e.name=="string"&&e.name?e.name:void 0;return n?`${n}: ${t}`:t},ye=i=>{if(i instanceof Error)return i.message?`${i.name}: ${i.message}`:i.name;if(typeof i=="string")return i;if(!i||typeof i!="object")return String(i);let e=i,t=[],n=vt(e);n&&t.push(n);let r=vt(e.error);r&&r!==n&&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!==n&&t.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&t.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&t.push(`url=${fn(o.url)}`);let s=gn(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var L=null;typeof WebSocket<"u"?L=WebSocket:typeof MozWebSocket<"u"?L=MozWebSocket:typeof global<"u"?L=global.WebSocket||global.MozWebSocket:typeof window<"u"?L=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(L=self.WebSocket||self.MozWebSocket);var wt=L;var ve=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 bn=Fe??$e;var Ge=class extends Error{constructor(e="WebSocket connection timeout"){super(e),this.name="ConnectionTimeoutError"}},ne=class extends Error{constructor(t,n){super(t);this.originalError=n;this.name="ConnectionFailedError"}},N=class extends Error{constructor(t,n){super(t);this.data=n;this.name="InvalidMessageError"}},_=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},D,We,He,re=class{constructor(e,t,n={}){this.eventEmitter=t;this.options=n;B(this,D);this.clientId="";this.closed=!1;this.disposables=new ve;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(n),this.url=new URL(e),this.PING_INTERVAL=n.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=n.connectWaitTimeout??3e4;let r=n.startClosed!==!1;this.rws=new bn(this.url.toString(),[],{WebSocket:n.webSocket??globalThis.WebSocket??wt,connectionTimeout:n.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:n.maxRetries??50,startClosed:r}),this.log("debug","Transport initialized",{url:this.url.toString(),options:n}),this.registerWatchers()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new _("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new _("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new _("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new _("maxRetries must be between 0 and 100")}log(e,t,n){if(this.options.debug){let r=new Date().toISOString(),o=n?JSON.stringify(n,null,2):"";console[e](`[Transport ${r}] ${t}${o?`
|
|
2
2
|
`+o:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):x(this,D,We).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(t)).catch(n=>{this.log("error","Failed to process queued WebSocket frame",{error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:n,rawMessage:t.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){let t;try{t=await this.toArrayBuffer(e.data)}catch(r){this.log("error","Unexpected WebSocket message type",{error:r instanceof Error?r.message:String(r),messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:r,rawMessage:e.data,timestamp:Date.now()});return}if(t.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let n;try{n=Be(t)}catch(r){this.log("error","Failed to decode WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:r,rawMessage:t,timestamp:Date.now()});return}try{await this.handleRawMessage(n)}catch(r){this.log("error","Failed to process WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:r,rawMessage:t,timestamp:Date.now()})}}async toArrayBuffer(e){if(e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer;throw new Error("Unexpected message type: "+typeof e)}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:n,as:r}=e;if(!n||typeof n!="string")throw new N("Message missing event field",e);if(this.log("debug","Processing message",{event:n,hasData:!!t}),n==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(n==="Events.BootError"){let o=t,s=new E(o?.message||"Notebook is no longer available",o||{});this.log("error","Boot error received",{data:t}),this.terminate(s,4e3,s.message);return}if(n==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new N("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(n==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new N("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(n,t,r)}catch(t){t instanceof N?this.log("error","Invalid message format",{error:t.message,data:t.data}):this.log("error","Failed to parse message",{ev:e,error:t instanceof Error?t.message:String(t)}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:t,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,t,n){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,this.clientId);return}e&&this.eventEmitter.emit(n||e,t)}listen(e,t,n){return this.eventEmitter.listen(e,t)}onDidBootError(e){return this.eventEmitter.listen("transport.boot_error",t=>{e(t.error)})}removeListener(e,t){this.eventEmitter.removeListener(e,t)}listenOnce(e,t,n){return this.eventEmitter.once(e,t,n)}emit(e,...t){this.eventEmitter.emit(e,...t)}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,t={},n={}){if(this.terminalError)throw this.terminalError;let r=n.responseEvent||`${e}_${f()}_response`,o=`${r}_error`,s,a,c=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),a&&(n.abortSignal?.removeEventListener("abort",a),a=void 0),this.eventEmitter.removeListener(r),this.eventEmitter.removeListener(o)},l=(g,p)=>{if(this.terminalError){p(this.terminalError);return}let m=new DOMException("Request aborted","AbortError");if(n.abortSignal?.aborted){p(m);return}if(n.abortSignal&&(a=()=>{p(m)},n.abortSignal.addEventListener("abort",a,{once:!0})),!this.isConnected||this.isClosed){p(new ne(`Connection is not open while sending ${e}. Current status: ${this.status}`));return}this.listenOnce(r,d=>{this.log("debug","Message response received",{action:e}),g(d)}),this.listenOnce(o,d=>{this.log("error","Message error received",{action:e,error:d});let k=d;p(new v(k.code,k.message,k))}),s=d=>{if(d.code===1008&&(d.reason||"").includes("rate limit")){p(new O(d.reason||"Rate limit exceeded",d));return}let k=ye(d);p(this.terminalError||new ne(`Connection lost to the notebook during request: ${k}`,d))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:r})),this.log("debug","Message sent",{action:e,data:t})}catch(d){this.log("error","Failed to send message",{action:e,error:d}),p(d)}},h=async()=>{if(n.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");if(await x(this,D,We).call(this),n.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");let g=new Promise(l).finally(c);return n.timeout?le(g,n.timeout).catch(p=>{throw p instanceof C?F.fromPromiseTimeoutError(p):p}).finally(c):g},u=n.retries===!1?0:n.retries??0;return this.sendWithRetry(async()=>await h(),u)}send(e,t={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:t})),this.log("debug","One-way message sent",{action:e,data:t}),!0}catch(n){return this.log("error","Failed to send one-way message",{action:e,error:n}),!1}}pack(e){return new Blob([_e(e)])}sendWithRetry(e,t){return te(async(n,r)=>{try{return await e()}catch(o){if(o instanceof v||o instanceof O||o instanceof _||o instanceof N||o instanceof E||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:r}),n(o);return}throw o instanceof F&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:r,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:r,error:o instanceof Error?o.message:String(o)}),o}},{retries:t,onRetry:(n,r)=>{this.log("warn","Send operation retry",{attempt:r,maxRetries:t,error:n instanceof Error?n.message:String(n)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},n={}){return n.responseEvent||(n.responseEvent=`${e}_${f()}`),this.call("invoke",{action:e,data:t},n)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){this.closed||this.close()}terminate(e,t=4e3,n=e.message){this.terminalError=e,e instanceof E&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,n)}close(e,t){if(!this.closed){this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null,this.disposables.dispose();try{this.rws.close(e,t)}catch(n){this.log("error","Error closing WebSocket",{error:n instanceof Error?n.message:String(n)})}this.eventEmitter.emit("transport.closed",{code:e,reason:t,timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}}onDidConnect(e){this.rws.addEventListener("open",e);let t={dispose:()=>{this.rws.removeEventListener("open",e)}};return this.disposables.add(`connect_${f()}`,t),t}onDidClose(e){this.rws.addEventListener("close",e);let t={dispose:()=>{this.rws.removeEventListener("close",e)}};return this.disposables.add(`close_${f()}`,t),t}};D=new WeakSet,We=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(),x(this,D,He).call(this);return}let n,r=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(n)},s=()=>{o(),this.connectPromise=null,e(),x(this,D,He).call(this)},a=l=>{r+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:r,error:ye(l)})},c=l=>{let h=ye(l);if(l.code===1008||l.code===4e3){o(),this.connectPromise=null,t(new ne(`WebSocket connection failed: ${h}`,l));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:h})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),n=setTimeout(()=>{o(),this.connectPromise=null,t(new Ge(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},He=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.log("debug","Sending periodic ping"),await this.invoke("ping"),this.log("debug","Ping successful")}catch(t){this.log("error","Ping failed",{error:t instanceof Error?t.message:String(t)})}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};var Ke={};ot(Ke,{default:()=>ze});function ze(i){return{all:i=i||new Map,on:function(e,t){var n=i.get(e);n?n.push(t):i.set(e,[t])},off:function(e,t){var n=i.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var n=i.get(e);n&&n.slice().map(function(r){r(t)}),(n=i.get("*"))&&n.slice().map(function(r){r(e,t)})}}}var yn=ze??Ke;function vn(i){let e=yn(i);return e.once=(t,n)=>{let r=o=>{e.off(t,r),n(o)};return e.on(t,r),{dispose:()=>{e.off(t,r)}}},e}var U=class i{constructor(){this.emitter=vn()}listen(e,t){let n=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:n}}emit(e,...t){this.emitter.emit(e,t.length>1?t:t[0])}once(e,t){return this.emitter.once(e,t)}static make(){return new i}static refresh(){return new i}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new i}inspect(){return this.emitter.all}};var ie=class{constructor(e){this.okra=e}checkpoint(e,t,n="main",r=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:n,allowEmpty:r})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,n="main",r,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:n,token:r,direction:o,force:s})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",this.normalizeRemoteInput(e))}merge(e){return this.okra.invoke("git.merge",this.normalizeRemoteInput(e))}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,t){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:t})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}credentials(){return this.okra.gitCredentials()}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}normalizeRemoteInput(e){if(e.notebookId===void 0)return e;let t=e.notebookId.trim();if(!t)throw new Error("'notebookId' cannot be empty.");if(e.url?.trim())throw new Error("Pass either 'url' or 'notebookId', not both.");if(e.target?.trim())throw new Error("Pass either 'target' or 'notebookId', not both.");let{notebookId:n,...r}=e;return{...r,url:this.gitUrlForNotebook(t)}}gitUrlForNotebook(e){let t=new URL(this.okra.data.gitUrl);return t.username="",t.password="",t.pathname=`/${encodeURIComponent(e)}.git`,t.search="",t.hash="",t.toString()}};var oe=class{constructor(e,t,n){this.onEvent=e;this.onceEvent=t;this.beacon=n;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=n,this.setupUrlChangeListener(),this.urlHistory.push(n.iframe.src),this.updateNavigationState()}visit(e){if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState(),this.emitHistoryChange(e,"push")}setupUrlChangeListener(){this.beacon.on("urlChange",e=>{this.addToHistory(e.newUrl)})}addToHistory(e){this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState()}updateNavigationState(){let e=this._canGoBack,t=this._canGoForward;this._canGoBack=this.currentIndex>0,this._canGoForward=this.currentIndex<this.urlHistory.length-1,(e!==this._canGoBack||t!==this._canGoForward)&&this.emitNavigationStateChange()}emitNavigationStateChange(){this.beacon&&this.beacon.emit&&this.beacon.emit("navigationStateChange",{canGoBack:this._canGoBack,canGoForward:this._canGoForward,currentIndex:this.currentIndex,historyLength:this.urlHistory.length,timestamp:Date.now()})}get canGoBack(){return this._canGoBack}get canGoForward(){return this._canGoForward}async goBack(){if(!this.canGoBack)return{success:!1,error:"Cannot go back - no previous history"};this.currentIndex--,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"back"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async goForward(){if(!this.canGoForward)return{success:!1,error:"Cannot go forward - no forward history"};this.currentIndex++,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"forward"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async reload(){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){let e=this.urlHistory[this.currentIndex];if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"reload")}}getCurrentUrl(){return this.currentIndex>=0&&this.currentIndex<this.urlHistory.length?new URL(this.urlHistory[this.currentIndex]):new URL("about:blank")}getHistory(){return[...this.urlHistory]}getCurrentIndex(){return this.currentIndex}canGoBackSync(){return this.currentIndex>0}canGoForwardSync(){return this.currentIndex<this.urlHistory.length-1}emitHistoryChange(e,t){this.beacon&&this.beacon.emit&&this.beacon.emit("historyChange",{url:e,state:null,direction:t,timestamp:Date.now()})}async pushState(e){this.visit(e)}async replaceState(e){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){if(this.urlHistory[this.currentIndex]=e,!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"replace")}else this.visit(e)}async getHistoryLength(){return this.urlHistory.length}async getHistoryState(){return null}async getHistoryInfo(){return{length:this.urlHistory.length,state:null,url:this.urlHistory[this.currentIndex]||"",canGoBack:this.canGoBack,canGoForward:this.canGoForward}}on(e,t){return this.onEvent(e,t)}once(e,t){this.onceEvent(e,t)}};function kt(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var M=class extends Error{constructor(t,n){super(t);this.code=n;this.name="BeaconError"}},we=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"}},qe=class{constructor(e,t={}){this.messageHandlers=new Map;this.isBeaconReady=!1;this.readyPromise=null;this.isStarted=!1;this.disposables=[];this.messageChannel=null;this.port=null;this.channelEstablished=!1;kt(),this.iframe=e;let n={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...n,...t.retry},...t},this.eventEmitter=U.make(),this.setupMessageChannel(),this.navigator=new oe(this.eventEmitter.listen.bind(this.eventEmitter),this.eventEmitter.once.bind(this.eventEmitter),this)}setupMessageChannel(){let e=t=>{try{if(t.source!==this.iframe.contentWindow)return;let n=t.data;if(!n||typeof n!="object"||!n.type)return;n.type==="beacon:ready-for-channel"&&this.establishChannel().catch(r=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",r)}),n.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",n.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(n){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",n)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new 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,n)=>{let r=setTimeout(()=>{n(new w("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(r),t()):setTimeout(o,100)};o()})}handleBeaconMessage(e){this.options.debug&&console.log("[Beacon SDK] Received message:",e.type,e.payload);let t=e.type.replace("beacon:","");this.emit(t,e.payload);let n=this.messageHandlers.get(e.type);n&&n.forEach(r=>{try{r(e.payload)}catch(o){this.options.debug&&console.error("[Beacon SDK] Message handler error:",o)}})}waitForBeaconReady(){return te(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let n=this.options.timeout,r=setTimeout(()=>{t(new we("beacon ready",n))},n),o=this.on("ready",()=>{clearTimeout(r),o.dispose(),e()})}),{retries:this.options.retry?.retries??3,minTimeout:this.options.retry?.minTimeout??1e3,maxTimeout:this.options.retry?.maxTimeout??5e3,factor:this.options.retry?.factor??2,randomize:this.options.retry?.randomize??!0,onRetry:(e,t)=>{if(this.options.debug){let n=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,n)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new w("MessagePort not available - channel not established");let n={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(n),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",n.type,n.payload)}catch(r){throw new w(`Failed to send message via port: ${r instanceof Error?r.message:String(r)}`)}}async sendAndWaitFor(e,t,n={},r){return await this.ready(),te(async o=>new Promise((s,a)=>{let c=r||this.options.timeout,l=setTimeout(()=>{h.dispose();let u=new we(e,c);a(u)},c),h=this.eventEmitter.listen(t,u=>{clearTimeout(l),h.dispose(),s(u)});try{this.sendMessage(e,n)}catch(u){clearTimeout(l),h.dispose(),u instanceof w?a(u):o(u)}}),{retries:this.options.retry?.retries??3,minTimeout:this.options.retry?.minTimeout??1e3,maxTimeout:this.options.retry?.maxTimeout??5e3,factor:this.options.retry?.factor??2,randomize:this.options.retry?.randomize??!0,onRetry:(o,s)=>{if(this.options.debug){let a=o instanceof Error?o.message:String(o);console.warn(`[Beacon SDK] Retry attempt ${s} for ${e}:`,a)}}})}generateId(){return`sdk_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}emit(e,t){this.eventEmitter.emit(e,t)}start(){return this.isStarted?this.readyPromise||Promise.resolve():(this.isStarted=!0,this.readyPromise=this.waitForBeaconReady(),this.readyPromise)}async ready(){if(!this.isStarted)throw new M("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new M("Beacon ready promise is not available");return le(this.readyPromise,this.options.timeout)}get isReady(){return this.isBeaconReady}on(e,t){return this.eventEmitter.listen(e,t)}once(e,t){return 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 captureScreenshot(e={}){let t=e.mediaTimeoutMs??e.timeout??3e4,n=e.transportTimeoutMs??t+5e3;return this.sendAndWaitFor("captureScreenshot","screenshotResult",e,n)}async debug(e,t){let n=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==n&&(this.navigator.visit(n),await this.ready()),t&&await this.wait(t);let 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 xt(i,e){return new qe(i,e)}function ai(){try{return kt(),!0}catch{return!1}}var ke=class{constructor(e){this.client=e}async create(e,t={}){let n=await this.client.post(`/notebook/${e}/deployments`,t);return new I(n.data,this.client)}async list(e){return(await this.client.get(`/notebook/${e}/deployments`)).data}async slugAvailability(e,t){let n=new URLSearchParams({slug:t}).toString();return(await this.client.get(`/notebook/${e}/deployments/slug-availability?${n}`)).data}},xe=class{constructor(e){this.client=e}async get(e){let t=await this.client.get(`/deployments/${e}`);return new I(t.data,this.client)}async redeploy(e,t={}){let n=await this.client.post(`/deployments/${e}/redeploy`,t);return new I(n.data,this.client)}async delete(e){await this.client.delete(`/deployments/${e}`)}async setProtection(e,t){let n=await this.client.put(`/deployments/${e}/protection`,t);return new I(n.data,this.client)}async protection(e){return(await this.client.get(`/deployments/${e}/protection`)).data}async createProtectionSession(e){return(await this.client.post(`/deployments/${e}/protection/session`)).data}async disableProtection(e){let t=await this.client.delete(`/deployments/${e}/protection`);return new I(t.data,this.client)}async setFeedback(e,t){let n=await this.client.put(`/deployments/${e}/feedback`,t);return new I(n.data,this.client)}async listDomains(e){let t=await this.client.get(`/deployments/${e}/domains`);return xn(t.data)}async createDomain(e,t){return(await this.client.post(`/deployments/${e}/domains`,t)).data}async refreshDomain(e,t){return(await this.client.post(`/deployments/${e}/domains/${t}/refresh`)).data}async deleteDomain(e,t){await this.client.delete(`/deployments/${e}/domains/${t}`)}async events(e){return je(await this.client.stream(`/deployments/${e}/events/stream`))}async buildLogs(e,t){return je(await this.client.stream(`/deployments/${e}/builds/${t}/logs/stream`))}async logs(e){return je(await this.client.stream(`/deployments/${e}/logs/stream`))}},I=class{constructor(e,t){this.data=e;this.client=t}refresh(){return this.client.deployments.get(this.data.id)}redeploy(e={}){return this.client.deployments.redeploy(this.data.id,e)}delete(){return this.client.deployments.delete(this.data.id)}async wait(e={}){let t=e.intervalMs??1e3,n=e.timeoutMs??3e5,r=Date.now(),o=this;for(;!wn(o.data.status);){if(Date.now()-r>n)throw new Error(`Timed out waiting for deployment ${this.data.id}`);await kn(t),o=await o.refresh()}return o}events(){return this.client.deployments.events(this.data.id)}buildLogs(e=this.data.latest_build?.id??""){return e===""?Promise.reject(new Error("Deployment has no latest build id")):this.client.deployments.buildLogs(this.data.id,e)}logs(){return this.client.deployments.logs(this.data.id)}setProtection(e){return this.client.deployments.setProtection(this.data.id,e)}protection(){return this.client.deployments.protection(this.data.id)}createProtectionSession(){return this.client.deployments.createProtectionSession(this.data.id)}disableProtection(){return this.client.deployments.disableProtection(this.data.id)}setFeedback(e){return this.client.deployments.setFeedback(this.data.id,e)}domains(){return this.client.deployments.listDomains(this.data.id)}addDomain(e){return this.client.deployments.createDomain(this.data.id,e)}refreshDomain(e){return this.client.deployments.refreshDomain(this.data.id,e)}deleteDomain(e){return this.client.deployments.deleteDomain(this.data.id,e)}};function wn(i){return["healthy","failed","stopped","deleted","delete_failed"].includes(i)}function kn(i){return new Promise(e=>setTimeout(e,i))}function xn(i){return Array.isArray(i)?i:Array.isArray(i.data)?i.data:[]}function je(i){let e=new TextDecoder,t="";return i.pipeThrough(new TransformStream({transform(n,r){t+=e.decode(n,{stream:!0});let o=t.split(`
|
|
3
|
-
`);t=o.pop()??"";for(let s of o){let a=s.trim();a!==""&&r.enqueue(JSON.parse(a))}},flush(n){t+=e.decode();let r=t.trim();r!==""&&n.enqueue(JSON.parse(r))}}))}function En(i){return Array.isArray(i)?i:Object.entries(i).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Ve=class extends Error{constructor(t,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},Ee=class extends Error{constructor(t,n){let r=Sn(n),o=Dn(r,n);super(`PHPSandbox API Error: ${t.status} ${t.statusText}${o===""?"":` - ${o}`}`);this.response=t;this.body=n;this.status=t.status,this.data=r,this.apiMessage=o===""?void 0:o}};function Sn(i){try{return JSON.parse(i)}catch{return null}}function Dn(i,e){if(i!==null&&typeof i=="object"){let t=i;if(typeof t.message=="string"&&t.message.trim()!=="")return t.message.trim();if(t.error!==void 0)return typeof t.error=="string"?t.error.trim():JSON.stringify(t.error)}return e.trim()}var Je=class{constructor(e){this.client=e;this.secrets=new Xe(e),this.preview=new Ye(e),this.mail=new Ze(e),this.deployments=new ke(e)}async create(e,t={},n=!0){let r=await this.client.post("/notebook",{template:e,...t}),o=new P(r.data,this.client);return n?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new P(t.data,this.client)}async update(e,t={}){let n=await this.client.put(`/notebook/${e}`,t);return new P(n.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e,t={}){let n=await this.client.post(`/notebook/${e}/fork`,t);return this.init(new P(n.data,this.client))}async gitCredentials(e){return(await this.client.post(`/notebook/${e}/git/credentials`)).data}async open(e){let t=await this.client.get(`/notebook/${e}`);return new P(t.data,this.client)}openFromData(e){return this.init(new P(e,this.client))}async init(e){return await e.ready(),e}};function In(i){let e=new URL(i),t=e.pathname.replace(/\/+$/,"");return e.pathname=t===""||t==="/"?"/v1/":`${t}/`,e.search="",e.hash="",e.toString()}var Qe=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.deployments=new xe(this),this.notebook=new Je(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=In(t),n.fetch&&(this.fetch=n.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t===void 0?void 0:JSON.stringify(t)})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t===void 0?void 0:JSON.stringify(t)})}async stream(e){let t=await this.fetch(new Request(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!t.ok)throw new Ee(t,await t.text());if(!t.body)throw new Error("PHPSandbox API Error: response body is not readable");return t.body}async makeRequest(e,t,n){let r=await this.fetch(new Request(new URL(t.replace(/^\//,""),this.baseUrl),{method:e,...n,headers:this.headers}));if(!r.ok)throw new Ee(r,await r.text());if(r.status===204)return{data:void 0};let o=await r.text();return{data:o===""?void 0:JSON.parse(o)}}},Et=class extends Qe{},Xe=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let r=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,r)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:En(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ye=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},Ze=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${Pn(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},T,se,et,P=class{constructor(e,t){this.data=e;this.client=t;B(this,se);this.initialized=!1;B(this,T);this.disposables=[];this.emitter=U.createInstance(),this.socket=new re(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),Ie(this,T,x(this,se,et).call(this)),this.file=new ce(this),this.terminal=new $(this),this.auth=new W(this),this.lsp=new H(this),this.composer=new z(this),this.log=new K(this),this.repl=new j(this),this.container=new G(this),this.laravel=new q(this),this.shell=new V(this),this.git=new ie(this),this.services=new J(this),this.config=new Q(this),this.secrets=new tt(t,this.data.id),this.preview=new nt(t,this.data.id),this.mail=new rt(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(),ae(this,T)))()}fork(e={}){return this.client.notebook.fork(this.data.id,e)}deploy(e={}){return this.client.notebook.deployments.create(this.data.id,e)}gitCredentials(){return this.client.notebook.gitCredentials(this.data.id)}delete(){return this.client.notebook.delete(this.data.id).then(()=>{this.socket.terminate(new E("Notebook has been deleted.",{id:this.data.id}))})}stop(){return this.container.stop()}restart(){return this.container.start()}invoke(e,t={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}whenConnected(){return this.waitForSocketConnection({rejectOnClose:!1})}waitForSocketConnection(e){let t=this.socket.getTerminalError();return t?Promise.reject(t):this.socket.isConnected?Promise.resolve(this):new Promise((n,r)=>{let o=[],s=!1,a=()=>{for(let l of o)l.dispose();o.length=0},c=l=>{s||(s=!0,a(),l())};try{o.push(this.socket.onDidConnect(()=>c(()=>n(this)))),e.rejectOnClose&&o.push(this.socket.onDidClose(()=>c(()=>r(new Error("Connection closed"))))),o.push(this.socket.onDidBootError(l=>c(()=>r(l))))}catch(l){c(()=>r(l))}})}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,x(this,se,et).call(this),this.ready().then(()=>this)}async beacon(e,t){let n=await this.ready();return e.src=n.data.previewUrl,xt(e,t)}};T=new WeakMap,se=new WeakSet,et=function(){return Ie(this,T,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(r.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new Ve(o.message,o.data));return}e(o)}),r=this.onDidBootError(o=>{n.dispose(),r.dispose(),t(o)})})),ae(this,T).catch(()=>{}),ae(this,T)};var tt=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)}},nt=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},rt=class{constructor(e,t){this.client=e;this.notebookId=t}status(){return this.client.notebook.mail.status(this.notebookId)}enable(){return this.client.notebook.mail.enable(this.notebookId)}disable(){return this.client.notebook.mail.disable(this.notebookId)}list(e={}){return this.client.notebook.mail.list(this.notebookId,e)}get(e){return this.client.notebook.mail.get(this.notebookId,e)}delete(e){return this.client.notebook.mail.delete(this.notebookId,e)}};function Pn(i){let e=new URLSearchParams;for(let[n,r]of Object.entries(i))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&e.set(n,String(r));let t=e.toString();return t===""?"":`?${t}`}export{Ee as ApiError,qe as Beacon,w as BeaconConnectionError,M as BeaconError,we as BeaconTimeoutError,Qe as Client,Re as CommandError,xe as DeploymentApi,I as DeploymentInstance,v as ErrorEvent,Pt as FileChangeFilter,Tt as FileChangeType,It as FileType,ce as Filesystem,Pe as FilesystemError,Ct as FilesystemErrorType,Ce as LspConnection,oe as Navigator,Je as NotebookApi,ke as NotebookDeploymentApi,Ve as NotebookInitError,P as NotebookInstance,rt as NotebookMail,Ze as NotebookMailApi,nt as NotebookPreview,Ye as NotebookPreviewApi,Xe as NotebookSecretApi,tt as NotebookSecrets,Nt as NotebookState,E as NotebookUnavailableError,Et as PHPSandbox,st as PHPSandboxError,C as PromiseTimeoutError,O as RateLimitError,F as SendTimeoutError,re as Transport,xt as createBeacon,ai as isBeaconSupported,_t as notebookBuiltinServices,Zn as notebookKnownServices,ue as once,le as timeout};
|
|
3
|
+
`);t=o.pop()??"";for(let s of o){let a=s.trim();a!==""&&r.enqueue(JSON.parse(a))}},flush(n){t+=e.decode();let r=t.trim();r!==""&&n.enqueue(JSON.parse(r))}}))}function En(i){return Array.isArray(i)?i:Object.entries(i).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Ve=class extends Error{constructor(t,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},Ee=class extends Error{constructor(t,n){let r=Sn(n),o=Dn(r,n);super(`PHPSandbox API Error: ${t.status} ${t.statusText}${o===""?"":` - ${o}`}`);this.response=t;this.body=n;this.status=t.status,this.data=r,this.apiMessage=o===""?void 0:o}};function Sn(i){try{return JSON.parse(i)}catch{return null}}function Dn(i,e){if(i!==null&&typeof i=="object"){let t=i;if(typeof t.message=="string"&&t.message.trim()!=="")return t.message.trim();if(t.error!==void 0)return typeof t.error=="string"?t.error.trim():JSON.stringify(t.error)}return e.trim()}var Je=class{constructor(e){this.client=e;this.secrets=new Xe(e),this.preview=new Ye(e),this.mail=new Ze(e),this.deployments=new ke(e)}async create(e,t={},n=!0){let r=await this.client.post("/notebook",{template:e,...t}),o=new P(r.data,this.client);return n?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new P(t.data,this.client)}async update(e,t={}){let n=await this.client.put(`/notebook/${e}`,t);return new P(n.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e,t={}){let n=await this.client.post(`/notebook/${e}/fork`,t);return this.init(new P(n.data,this.client))}async gitCredentials(e){return(await this.client.post(`/notebook/${e}/git/credentials`)).data}async open(e){let t=await this.client.get(`/notebook/${e}`);return new P(t.data,this.client)}openFromData(e){return this.init(new P(e,this.client))}async init(e){return await e.ready(),e}};function In(i){let e=new URL(i),t=e.pathname.replace(/\/+$/,"");return e.pathname=t===""||t==="/"?"/v1/":`${t}/`,e.search="",e.hash="",e.toString()}var Qe=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.deployments=new xe(this),this.notebook=new Je(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=In(t),n.fetch&&(this.fetch=n.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t===void 0?void 0:JSON.stringify(t)})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t===void 0?void 0:JSON.stringify(t)})}async stream(e){let t=await this.fetch(new Request(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!t.ok)throw new Ee(t,await t.text());if(!t.body)throw new Error("PHPSandbox API Error: response body is not readable");return t.body}async makeRequest(e,t,n){let r=await this.fetch(new Request(new URL(t.replace(/^\//,""),this.baseUrl),{method:e,...n,headers:this.headers}));if(!r.ok)throw new Ee(r,await r.text());if(r.status===204)return{data:void 0};let o=await r.text();return{data:o===""?void 0:JSON.parse(o)}}},Et=class extends Qe{},Xe=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let r=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,r)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:En(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ye=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},Ze=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${Pn(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},T,se,et,P=class{constructor(e,t){this.data=e;this.client=t;B(this,se);this.initialized=!1;B(this,T);this.disposables=[];this.emitter=U.createInstance(),this.socket=new re(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),Ie(this,T,x(this,se,et).call(this)),this.file=new ce(this),this.terminal=new $(this),this.auth=new W(this),this.lsp=new H(this),this.composer=new z(this),this.log=new K(this),this.repl=new j(this),this.container=new G(this),this.laravel=new q(this),this.shell=new V(this),this.git=new ie(this),this.services=new J(this),this.config=new Q(this),this.secrets=new tt(t,this.data.id),this.preview=new nt(t,this.data.id),this.mail=new rt(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(),ae(this,T)))()}fork(e={}){return this.client.notebook.fork(this.data.id,e)}deploy(e={}){return this.client.notebook.deployments.create(this.data.id,e)}gitCredentials(){return this.client.notebook.gitCredentials(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.restart()}invoke(e,t={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}whenConnected(){return this.waitForSocketConnection({rejectOnClose:!1})}waitForSocketConnection(e){let t=this.socket.getTerminalError();return t?Promise.reject(t):this.socket.isConnected?Promise.resolve(this):new Promise((n,r)=>{let o=[],s=!1,a=()=>{for(let l of o)l.dispose();o.length=0},c=l=>{s||(s=!0,a(),l())};try{o.push(this.socket.onDidConnect(()=>c(()=>n(this)))),e.rejectOnClose&&o.push(this.socket.onDidClose(()=>c(()=>r(new Error("Connection closed"))))),o.push(this.socket.onDidBootError(l=>c(()=>r(l))))}catch(l){c(()=>r(l))}})}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,x(this,se,et).call(this),this.ready().then(()=>this)}async beacon(e,t){let n=await this.ready();return e.src=n.data.previewUrl,xt(e,t)}};T=new WeakMap,se=new WeakSet,et=function(){return Ie(this,T,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(r.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new Ve(o.message,o.data));return}e(o)}),r=this.onDidBootError(o=>{n.dispose(),r.dispose(),t(o)})})),ae(this,T).catch(()=>{}),ae(this,T)};var tt=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)}},nt=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},rt=class{constructor(e,t){this.client=e;this.notebookId=t}status(){return this.client.notebook.mail.status(this.notebookId)}enable(){return this.client.notebook.mail.enable(this.notebookId)}disable(){return this.client.notebook.mail.disable(this.notebookId)}list(e={}){return this.client.notebook.mail.list(this.notebookId,e)}get(e){return this.client.notebook.mail.get(this.notebookId,e)}delete(e){return this.client.notebook.mail.delete(this.notebookId,e)}};function Pn(i){let e=new URLSearchParams;for(let[n,r]of Object.entries(i))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&e.set(n,String(r));let t=e.toString();return t===""?"":`?${t}`}export{Ee as ApiError,qe as Beacon,w as BeaconConnectionError,M as BeaconError,we as BeaconTimeoutError,Qe as Client,Re as CommandError,xe as DeploymentApi,I as DeploymentInstance,v as ErrorEvent,Pt as FileChangeFilter,Tt as FileChangeType,It as FileType,ce as Filesystem,Pe as FilesystemError,Ct as FilesystemErrorType,Ce as LspConnection,oe as Navigator,Je as NotebookApi,ke as NotebookDeploymentApi,Ve as NotebookInitError,P as NotebookInstance,rt as NotebookMail,Ze as NotebookMailApi,nt as NotebookPreview,Ye as NotebookPreviewApi,Xe as NotebookSecretApi,tt as NotebookSecrets,Nt as NotebookState,E as NotebookUnavailableError,Et as PHPSandbox,st as PHPSandboxError,C as PromiseTimeoutError,O as RateLimitError,F as SendTimeoutError,re as Transport,xt as createBeacon,ai as isBeaconSupported,_t as notebookBuiltinServices,Zn as notebookKnownServices,ue as once,le as timeout};
|
|
4
4
|
/*! Bundled license information:
|
|
5
5
|
|
|
6
6
|
reconnecting-websocket/dist/reconnecting-websocket-mjs.js:
|
|
@@ -5180,7 +5180,7 @@ var PHPSandbox = (() => {
|
|
|
5180
5180
|
return this.container.stop();
|
|
5181
5181
|
}
|
|
5182
5182
|
restart() {
|
|
5183
|
-
return this.container.
|
|
5183
|
+
return this.container.restart();
|
|
5184
5184
|
}
|
|
5185
5185
|
invoke(action, data = {}, options = {}) {
|
|
5186
5186
|
return this.socket.invoke(action, data || {}, options);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var PHPSandbox=(()=>{var Oe=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Ut=Object.prototype.hasOwnProperty;var lt=i=>{throw TypeError(i)};var Fe=(i,e)=>{for(var t in e)Oe(i,t,{get:e[t],enumerable:!0})},Lt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _t(e))!Ut.call(i,r)&&r!==t&&Oe(i,r,{get:()=>e[r],enumerable:!(n=Nt(e,r))||n.enumerable});return i};var Mt=i=>Lt(Oe({},"__esModule",{value:!0}),i);var $e=(i,e,t)=>e.has(i)||lt("Cannot "+t);var me=(i,e,t)=>($e(i,e,"read from private field"),t?t.call(i):e.get(i)),G=(i,e,t)=>e.has(i)?lt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ge=(i,e,t,n)=>($e(i,e,"write to private field"),n?n.call(i,t):e.set(i,t),t),D=(i,e,t)=>($e(i,e,"access private method"),t);var Ln={};Fe(Ln,{ApiError:()=>de,Beacon:()=>Pe,BeaconConnectionError:()=>w,BeaconError:()=>L,BeaconTimeoutError:()=>le,Client:()=>Re,CommandError:()=>be,DeploymentApi:()=>pe,DeploymentInstance:()=>x,ErrorEvent:()=>v,FileChangeFilter:()=>dt,FileChangeType:()=>ht,FileType:()=>pt,Filesystem:()=>W,FilesystemError:()=>ge,FilesystemErrorType:()=>mt,LspConnection:()=>fe,Navigator:()=>$,NotebookApi:()=>Ce,NotebookDeploymentApi:()=>ue,NotebookInitError:()=>Te,NotebookInstance:()=>E,NotebookMail:()=>Me,NotebookMailApi:()=>_e,NotebookPreview:()=>Le,NotebookPreviewApi:()=>Ne,NotebookSecretApi:()=>Ae,NotebookSecrets:()=>Ue,NotebookState:()=>gt,NotebookUnavailableError:()=>k,PHPSandbox:()=>at,PHPSandboxError:()=>We,PromiseTimeoutError:()=>I,RateLimitError:()=>M,SendTimeoutError:()=>B,Transport:()=>F,createBeacon:()=>ot,isBeaconSupported:()=>In,notebookBuiltinServices:()=>bt,notebookKnownServices:()=>Ft,once:()=>z,timeout:()=>H});var v=class extends Error{constructor(t,n,r={}){super(n);this.code=t;this.message=n;this.raw=r}},M=class extends v{constructor(e,t={}){super(429,e,t)}},We=class extends v{};var ut="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var f=(i=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(i|=0));for(;i--;)e+=ut[t[i]&63];return e};var pt=(r=>(r[r.Unknown=0]="Unknown",r[r.File=1]="File",r[r.Directory=2]="Directory",r[r.SymbolicLink=64]="SymbolicLink",r))(pt||{}),dt=(n=>(n[n.UPDATED=2]="UPDATED",n[n.ADDED=4]="ADDED",n[n.DELETED=8]="DELETED",n))(dt||{}),ht=(n=>(n[n.UPDATED=1]="UPDATED",n[n.ADDED=2]="ADDED",n[n.DELETED=3]="DELETED",n))(ht||{}),mt=(s=>(s.Unavailable="Unavailable",s.NoPermissions="NoPermissions",s.FileExists="FileExists",s.FileNotFound="FileNotFound",s.FileIsADirectory="FileIsADirectory",s.FileNotADirectory="FileNotADirectory",s))(mt||{}),ge=class extends v{constructor(t,n){super(t.code,t.message);this.name=n}},He=class{constructor(e,t){this.disposable=e;this.onDispose=t;this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposable.dispose(),this.onDispose())}},W=class{constructor(e){this.okra=e;this.watches=new Map;this.watchOkraConnection()}watchOkraConnection(){this.okra.onDidConnect(()=>{for(let{path:e,options:t}of this.watches.values())this.okra.invoke("fs.watch",{path:e,options:t}).catch(()=>{})})}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:{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1,...t}})}search(e,t,n){e.id||(e.id=f());let r={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,s=async c=>{c===!1&&a.dispose(),n&&await Promise.resolve(n(c))===!1&&a.dispose()},a=this.okra.listen(`fs.text.search.${o}`,s);return this.okra.invoke("fs.textSearch",{query:e,options:{...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 n=await this.okra.invoke("fs.readFile",{path:e,lineRange:t});return n instanceof Uint8Array?n:typeof n=="string"?new TextEncoder().encode(n):n}catch(n){this.handleError(n)}}tail(e,t=10){return this.okra.invoke("fs.tail",{path:e,lines:t}).catch(n=>this.handleError(n))}writeFile(e,t,n){return this.okra.invoke("fs.writeFile",{path:e,contents:t,options:n}).catch(r=>this.handleError(r))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(t=>this.handleError(t))}rename(e,t,n){return this.okra.invoke("fs.rename",{from:e,to:t,options:n}).catch(r=>this.handleError(r))}delete(e,t){return this.okra.invoke("fs.delete",{path:e,options:t}).catch(n=>this.handleError(n))}copy(e,t,n){return this.okra.invoke("fs.copy",{source:e,destination:t,options:n}).catch(r=>this.handleError(r))}readDirectory(e,t=[],n=[]){return this.okra.invoke("fs.readDirectory",{path:e,include:t,exclude:n}).catch(r=>this.handleError(r))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(t=>this.handleError(t))}watch(e,t,n){let r=this.okra.listen(`fs.watch.${e}`,n),o={dispose:()=>{r.dispose(),this.okra.invoke("fs.unwatch",{path:e}).catch(()=>{})}},s=new He(o,()=>{this.watches.get(e)?.onDidChange===n&&this.watches.delete(e)});return this.watches.set(e,{options:t,path:e,onDidChange:n}),this.okra.invoke("fs.watch",{path:e,options:t}).then(()=>s).catch(a=>{throw s.dispose(),a})}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}async download(e,t,n){let r=f(),o=!!e,s=[],a=this.okra.listen(`fs.download.${r}`,o?e:c=>{s.push(c)});return this.okra.invoke("fs.download",{id:r,exclude:t,include:n}).then(()=>new Blob(s,{type:"application/octet-stream"})).finally(()=>a.dispose())}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e instanceof v&&"name"in e.raw?new ge(e,e.raw.name):e}};var I=class extends Error{constructor(t,n){super(t);this.time=n}},B=class i extends I{static fromPromiseTimeoutError(e){return new i(e.message,e.time)}},k=class extends Error{constructor(t="Notebook is no longer available",n={}){super(t);this.raw=n;this.name="NotebookUnavailableError"}};var H=(i,e)=>{let t;return Promise.race([i,new Promise((n,r)=>t=setTimeout(r,e,new I("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(t))},z=i=>{let e=null;return()=>e||(e=i())};var Bt=8,Ot=/[\x00-\x1f\x7f]/,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){return 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){return this.okra.listen(`terminal.output.${e}`,t)}input(e,t){return Promise.resolve(this.okra.send("terminal.input",{id:e,input:t}))}listen(e,t){return this.okra.listen(e,t)}async attach(e,t){let n=this.processHandle(e,t?.abortSignal);try{let r=await this.okra.invoke("terminal.attach",{id:e,replayHistory:t?.replayHistory},{abortSignal:t?.abortSignal});return r?{...n.process,...r}:(n.dispose(),!1)}catch(r){throw n.dispose(),r}}async spawn(e,t,n){let r=n?.id||f(),o=this.processHandle(r,n?.abortSignal),{abortSignal:s,...a}=n??{};try{let c=await this.okra.invoke("terminal.spawn",{command:[e,...t],opts:{id:r,...a}},{abortSignal:s});return{...o.process,...c}}catch(c){throw o.dispose(),c}}processHandle(e,t){let n=new Set,r,o=()=>{r&&(t?.removeEventListener("abort",r),r=void 0);for(let y of n)y.dispose();n.clear()},s="",a,c=()=>{if(a&&(clearTimeout(a),a=void 0),s==="")return;let y=s;s="",this.input(e,y)},l=()=>{a||(a=setTimeout(c,Bt))},h=y=>{if(s+=y,Ot.test(y)){c();return}l()},u=()=>{c(),o()},g=new WritableStream({write:h,close:u,abort:u}),p=null,m=new ReadableStream({start:y=>{p=y,n.add(this.listen(`terminal.output.${e}`,Be=>{p?.enqueue(Be.output)}))},cancel:()=>{p=null,u()}}),d=new Promise(y=>{n.add(this.listen(`terminal.close.${e}`,Be=>{if(p)try{p.close()}catch{}u(),y(Be.exitCode)}))}),S=z(()=>(u(),this.okra.invoke("terminal.close",{id:e}))),At=y=>{this.okra.invoke("terminal.resize",{id:e,width:y.cols,height:y.rows})};return t&&!t.aborted&&(r=()=>{S()},t.addEventListener("abort",r,{once:!0})),{process:{exit:d,input:g,output:m,kill:S,resize:At},dispose:u}}};var gt=(a=>(a.RUNNING="running",a.STOPPED="stopped",a.STARTING="starting",a.STOPPING="stopping",a.KILLED="killed",a.ERROR="error",a.PROVISIONING="provisioning",a))(gt||{}),q=class{constructor(e){this.okra=e}start(){return this.okra.invoke("container.start")}restart(){return this.okra.invoke("container.restart")}stop(){return this.okra.invoke("container.stop")}state(){return this.okra.invoke("container.state")}openedPorts(){return this.okra.invoke("container.opened-ports")}setPhp(e){return this.okra.invoke("container.set-php",{version:e})}enableTelemetry(e){return this.okra.invoke("container.stream-telemetry",{features:Array.from(e)})}stopTelemetry(){return this.okra.invoke("container.stop-telemetry")}listen(e,t){return this.okra.listen(e,t)}onPort(e){let t=[];return this.listen("container.ports",n=>{for(let r of n)t.some(o=>o.port===r.port)||e(r,"open");for(let r of t)n.some(o=>o.port===r.port)||e(r,"close");t=n})}};var j=class{constructor(e){this.okra=e}logout(){return this.okra.invoke("auth.logout")}login(e){return this.okra.invoke("auth.login",{newConnectionData:e})}};var V=class{constructor(e){this.okra=e}message(e,t){return this.okra.invoke("lsp.message",{id:e,message:t})}listen(e,t,n){return this.okra.listen(`${t}.${e}`,r=>n(r))}onClose(e,t){return this.listen(e,"lsp.closed",n=>t(n.code,n.reason))}onError(e,t){return this.listen(e,"lsp.error",n=>t(n.message))}onClientDisconnect(e){return this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,t){return this.listen(e,"lsp.response",n=>t(JSON.stringify(n)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return fe.create(e,this)}whenSocketConnected(){return this.okra.whenConnected()}},fe=class i{constructor(e,t){this.id=e;this.lsp=t}send(e){return this.lsp.message(this.id,e)}onMessage(e){return this.lsp.onResponse(this.id,e)}onError(e){return this.lsp.onError(this.id,e)}onClose(e){return this.lsp.onClose(this.id,e)}dispose(){this.lsp.close(this.id)}start(){this.lsp.start(this.id)}onClientDisconnect(e){return this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,t){return new i(e,t)}};var J=class{constructor(e){this.okra=e}invoke(e,t={},n={}){return this.okra.invoke("composer.invoke",{command:e,args:t,options:n})}dumpAutoload(){return this.okra.invoke("composer.dump-autoload")}install(e={}){return this.invoke("install",{},e)}update(e,t={}){return this.invoke("update",e,t)}require(e,t={}){return this.invoke("require",e,t)}remove(e,t={}){return this.invoke("remove",e,t)}stream(e){return this.okra.listen("composer.log",e)}packages(){return this.okra.invoke("composer.packages")}};var Q=class{constructor(e){this.okra=e}stream(e){return this.okra.listen("notebook.log",e)}listen(e,t){return this.okra.listen(e,t)}};var X=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 Y=class{constructor(e){this.okra=e}eval(e,t="",n={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:t,repl:n})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}start(){return this.okra.invoke("repl.start")}resize(e,t){return this.okra.invoke("repl.resize",{cols:e,rows:t})}listen(e,t){return this.okra.listen(e,t)}onOutput(e){return this.okra.listen("repl.output",e)}};function ft(i,e=[],t){let n=Array.isArray(e)?e:[],r=Array.isArray(e)?t:e;return{command:Array.isArray(i)?i:n.length>0?[i,...n]:i,opts:r}}var be=class extends Error{constructor(t,n){super(t);this.output=t;this.exitCode=n}},ze=class{constructor(e,t){this.output=e;this.exitCode=t}throw(){if(this.exitCode!==0)throw new be(this.output,this.exitCode);return this}},Z=class{constructor(e){this.okra=e}onOutput(e,t){return this.okra.listen(`shell.output.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}async exec(e,t=[],n){let r=ft(e,t,n),{abortSignal:o,...s}=r.opts??{},a=await this.okra.invoke("shell.exec",{command:r.command,opts:Object.keys(s).length>0?s:void 0},{abortSignal:o});return new ze(a.output,a.exitCode)}execStream(e,t=[],n){let r=ft(e,t,n),o=r.opts?.id||f(),s=new Set,a=null,c=!1,l=()=>{for(let m of s)m.dispose();s.clear()},h=()=>{if(!c&&(c=!0,l(),a))try{a.close()}catch{}},u=m=>{c||(c=!0,l(),a&&a.error(m))},g=new ReadableStream({start:m=>{a=m,s.add(this.listen(`shell.output.${o}`,d=>{a?.enqueue(d.output)}))},cancel:()=>{c=!0,l()}}),p=this.exec(r.command,{...r.opts,id:o}).then(m=>(h(),m)).catch(m=>{throw u(m),m});return{output:g,result:p}}};var bt=["redis"],Ft=["start","nginx",...bt],ee=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,t){return this.okra.invoke("service.run",{name:e,command:t})}stop(e){return this.okra.invoke("service.stop",{name:e})}onLog(e,t){return this.okra.listen(`service.log.${e}`,t)}listen(e,t){return this.okra.listen(e,t)}logs(e,t={}){return t.follow?this.followLogs(e,t):this.okra.invoke("service.logs",{name:e,tail:t.tail}).then(n=>{if(!("output"in n))throw new Error(`Unexpected service.logs response for ${e}`);return n.output})}followLogs(e,t){let n=t.id||f(),r=new Set,o=null,s=!1,a=()=>{for(let g of r)g.dispose();r.clear()},c=()=>{if(!s&&(s=!0,a(),o))try{o.close()}catch{}},l=g=>{s||(s=!0,a(),o&&o.error(g))},h=z(()=>(c(),this.okra.invoke("service.stop-logs",{id:n}))),u=new ReadableStream({start:g=>{o=g,r.add(this.onLog(n,p=>{o?.enqueue(p.output)})),this.okra.invoke("service.logs",{name:e,tail:t.tail,follow:!0,id:n}).catch(p=>{l(p)})},cancel:()=>{h()}});return{id:n,output:u,stop:h}}};var te=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function yt(i){let e=i.length,t=0,n=0;for(;n<e;){let r=i.charCodeAt(n++);if((r&4294967168)===0){t++;continue}else if((r&4294965248)===0)t+=2;else{if(r>=55296&&r<=56319&&n<e){let o=i.charCodeAt(n);(o&64512)===56320&&(++n,r=((r&1023)<<10)+(o&1023)+65536)}(r&4294901760)===0?t+=3:t+=4}}return t}function $t(i,e,t){let n=i.length,r=t,o=0;for(;o<n;){let s=i.charCodeAt(o++);if((s&4294967168)===0){e[r++]=s;continue}else if((s&4294965248)===0)e[r++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){let a=i.charCodeAt(o);(a&64512)===56320&&(++o,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128):(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128)}e[r++]=s&63|128}}var Gt=new TextEncoder,Wt=50;function Ht(i,e,t){Gt.encodeInto(i,e.subarray(t))}function vt(i,e,t){i.length>Wt?Ht(i,e,t):$t(i,e,t)}var zt=4096;function Ke(i,e,t){let n=e,r=n+t,o=[],s="";for(;n<r;){let a=i[n++];if((a&128)===0)o.push(a);else if((a&224)===192){let c=i[n++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){let c=i[n++]&63,l=i[n++]&63;o.push((a&31)<<12|c<<6|l)}else if((a&248)===240){let c=i[n++]&63,l=i[n++]&63,h=i[n++]&63,u=(a&7)<<18|c<<12|l<<6|h;u>65535&&(u-=65536,o.push(u>>>10&1023|55296),u=56320|u&1023),o.push(u)}else o.push(a);o.length>=zt&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var Kt=new TextDecoder,qt=200;function jt(i,e,t){let n=i.subarray(e,e+t);return Kt.decode(n)}function wt(i,e,t){return t>qt?jt(i,e,t):Ke(i,e,t)}var R=class{constructor(e,t){this.type=e,this.data=t}};var b=class i extends Error{constructor(e){super(e);let t=Object.create(i.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:i.name})}};function kt(i,e,t){let n=t/4294967296,r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function ye(i,e,t){let n=Math.floor(t/4294967296),r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function ve(i,e){let t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function xt(i,e){let t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}var Vt=-1,Jt=4294967296-1,Qt=17179869184-1;function Xt({sec:i,nsec:e}){if(i>=0&&e>=0&&i<=Qt)if(e===0&&i<=Jt){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,i),t}else{let t=i/4294967296,n=i&4294967295,r=new Uint8Array(8),o=new DataView(r.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,n),r}else{let t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),ye(n,4,i),t}}function Yt(i){let e=i.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,r=Math.floor(n/1e9);return{sec:t+r,nsec:n-r*1e9}}function Zt(i){if(i instanceof Date){let e=Yt(i);return Xt(e)}else return null}function en(i){let e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(i.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),n=e.getUint32(4),r=(t&3)*4294967296+n,o=t>>>2;return{sec:r,nsec:o}}case 12:{let t=ve(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new b(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${i.length}`)}}function tn(i){let e=en(i);return new Date(e.sec*1e3+e.nsec/1e6)}var Et={type:Vt,encode:Zt,decode:tn};var P=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Et)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let o=r(e,t);if(o!=null){let s=-1-n;return new R(s,o)}}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let o=r(e,t);if(o!=null){let s=n;return new R(s,o)}}}return e instanceof R?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new R(t,e)}};P.defaultCodec=new P;function nn(i){return i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer}function ne(i){return i instanceof Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):nn(i)?new Uint8Array(i):Uint8Array.from(i)}var rn=100,on=2048,we=class i{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??P.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??rn,this.initialBufferSize=e?.initialBufferSize??on,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 i({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let n=yt(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),vt(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,t){let n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let n=ne(e);this.writeU8a(n)}encodeArray(e,t){let n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let r of e)this.doEncode(r,t+1)}countWithoutUndefined(e,t){let n=0;for(let r of t)e[r]!==void 0&&n++;return n}encodeMap(e,t){let n=Object.keys(e);this.sortKeys&&n.sort();let r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else if(r<4294967296)this.writeU8(223),this.writeU32(r);else throw new Error(`Too large map object: ${r}`);for(let o of n){let s=e[o];this.ignoreUndefined&&s===void 0||(this.encodeString(o),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let n=e.data(this.pos+6),r=n.length;if(r>=4294967296)throw new Error(`Too large extension object: ${r}`);this.writeU8(201),this.writeU32(r),this.writeI8(e.type),this.writeU8a(n);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),kt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ye(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 qe(i,e){return new we(e).encodeSharedRef(i)}function ke(i){return`${i<0?"-":""}0x${Math.abs(i).toString(16).padStart(2,"0")}`}var sn=16,an=16,xe=class{constructor(e=sn,t=an){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];e:for(let o of r){let s=o.bytes;for(let a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return o.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let o=Ke(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o}};var je="array",oe="map_key",Dt="map_value",cn=i=>{if(typeof i=="string"||typeof i=="number")return i;throw new b("The type of key must be string or number but "+typeof i)},Ve=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=je,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=oe,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===je){let n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===oe||e.type===Dt){let n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},ie=-1,Je=new DataView(new ArrayBuffer(0)),ln=new Uint8Array(Je.buffer);try{Je.getInt8(0)}catch(i){if(!(i 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 St=new RangeError("Insufficient data"),un=new xe,Ee=class i{constructor(e){this.totalPos=0,this.pos=0,this.view=Je,this.bytes=ln,this.headByte=ie,this.stack=new Ve,this.entered=!1,this.extensionCodec=e?.extensionCodec??P.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:un,this.mapKeyConverter=e?.mapKeyConverter??cn}clone(){return new i({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=ie,this.stack.reset()}setBuffer(e){let t=ne(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ie&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=ne(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${ke(r)} at ${s} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,r=-1;for await(let o of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let r=e-128;if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e<160){let r=e-144;if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else{let r=e-160;t=this.decodeString(r,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let r=this.lookU8();t=this.decodeString(r,1)}else if(e===218){let r=this.lookU16();t=this.decodeString(r,2)}else if(e===219){let r=this.lookU32();t=this.decodeString(r,4)}else if(e===220){let r=this.readU16();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===221){let r=this.readU32();if(r!==0){this.pushArrayState(r),this.complete();continue e}else t=[]}else if(e===222){let r=this.readU16();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===223){let r=this.readU32();if(r!==0){this.pushMapState(r),this.complete();continue e}else t={}}else if(e===196){let r=this.lookU8();t=this.decodeBinary(r,1)}else if(e===197){let r=this.lookU16();t=this.decodeBinary(r,2)}else if(e===198){let r=this.lookU32();t=this.decodeBinary(r,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let r=this.lookU8();t=this.decodeExtension(r,1)}else if(e===200){let r=this.lookU16();t=this.decodeExtension(r,2)}else if(e===201){let r=this.lookU32();t=this.decodeExtension(r,4)}else throw new b(`Unrecognized type byte: ${ke(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let r=n.top();if(r.type===je)if(r.array[r.position]=t,r.position++,r.position===r.size)t=r.array,n.release(r);else continue e;else if(r.type===oe){if(t==="__proto__")throw new b("The key __proto__ is not allowed");r.key=this.mapKeyConverter(t),r.type=Dt;continue e}else if(r.map[r.key]=t,r.readCount++,r.readCount===r.size)t=r.map,n.release(r);else{r.key=null,r.type=oe;continue e}}return t}}readHeadByte(){return this.headByte===ie&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ie}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 b(`Unrecognized array type byte: ${ke(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new b(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new b(`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 b(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw St;let n=this.pos+t,r;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?r=this.keyDecoder.decode(this.bytes,n,e):r=wt(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===oe:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new b(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw St;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new b(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=xt(this.view,this.pos);return this.pos+=8,e}readI64(){let e=ve(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 Qe(i,e){return new Ee(e).decode(i)}var Se=class{constructor(e){this.error=e}},pn=i=>new Promise(e=>{setTimeout(e,i)}),dn=(i,e)=>{let t=e.randomize?Math.random()+1:1,n=Math.max(e.minTimeout,1)*Math.pow(e.factor,i-1);return Math.round(Math.min(t*n,e.maxTimeout))};async function se(i,e={}){let t={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},n=o=>{throw new Se(o??new Error("Aborted"))},r;for(let o=1;o<=t.retries+1;o++)try{return await i(n,o)}catch(s){if(s instanceof Se)throw s.error;if(r=s,o>t.retries)throw s;await e.onRetry?.(s,o),await pn(dn(o,t))}throw r}var Ze={};Fe(Ze,{default:()=>Ye});var Xe=function(i,e){return Xe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])},Xe(i,e)};function It(i,e){Xe(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function hn(i){var e=typeof Symbol=="function"&&i[Symbol.iterator],t=0;return e?e.call(i):{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}}}function mn(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function gn(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(mn(arguments[e]));return i}var Pt=(function(){function i(e,t){this.target=t,this.type=e}return i})(),fn=(function(i){It(e,i);function e(t,n){var r=i.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return e})(Pt),bn=(function(i){It(e,i);function e(t,n,r){t===void 0&&(t=1e3),n===void 0&&(n="");var o=i.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return e})(Pt);var yn=function(){if(typeof WebSocket<"u")return WebSocket},vn=function(i){return typeof i<"u"&&!!i&&i.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},wn=(function(){function i(e,t,n){var r=this;n===void 0&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){r._debug("open event");var s=r._options.minUptime,a=s===void 0?A.minUptime:s;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout(function(){return r._acceptOpen()},a),r._ws.binaryType=r._binaryType,r._messageQueue.forEach(function(c){return r._ws.send(c)}),r._messageQueue=[],r.onopen&&r.onopen(o),r._listeners.open.forEach(function(c){return r._callEventListener(o,c)})},this._handleMessage=function(o){r._debug("message event"),r.onmessage&&r.onmessage(o),r._listeners.message.forEach(function(s){return r._callEventListener(o,s)})},this._handleError=function(o){r._debug("error event",o.message),r._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),r.onerror&&r.onerror(o),r._debug("exec error listeners"),r._listeners.error.forEach(function(s){return r._callEventListener(o,s)}),r._connect()},this._handleClose=function(o){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(o),r._listeners.close.forEach(function(s){return r._callEventListener(o,s)})},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(i,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(i,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(i,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"CONNECTING",{get:function(){return i.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"OPEN",{get:function(){return i.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"CLOSING",{get:function(){return i.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"CLOSED",{get:function(){return i.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(i.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(i.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(t,n){return typeof n=="string"?t+=n.length:n instanceof Blob?t+=n.size:t+=n.byteLength,t},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?i.CLOSED:i.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),i.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)},i.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())},i.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=t===void 0?A.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},i.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},i.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var o=hn(r),s=o.next();!s.done;s=o.next()){var a=s.value;this._callEventListener(e,a)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},i.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(n){return n!==t}))},i.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,gn(["RWS>"],e))},i.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=t===void 0?A.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=r===void 0?A.minReconnectionDelay:r,s=e.maxReconnectionDelay,a=s===void 0?A.maxReconnectionDelay:s,c=0;return this._retryCount>0&&(c=o*Math.pow(n,this._retryCount-1),c>a&&(c=a)),this._debug("next delay",c),c},i.prototype._wait=function(){var e=this;return new Promise(function(t){setTimeout(t,e._getNextDelay())})},i.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")},i.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=n===void 0?A.maxRetries:n,o=t.connectionTimeout,s=o===void 0?A.connectionTimeout:o,a=t.WebSocket,c=a===void 0?yn():a;if(this._retryCount>=r){this._debug("max retries reached",this._retryCount,">=",r);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!vn(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(l){e._closeCalled||(e._debug("connect",{url:l,protocols:e._protocols}),e._ws=e._protocols?new c(l,e._protocols):new c(l),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},s))})}},i.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new fn(Error("TIMEOUT"),this))},i.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 bn(e,t,this))}catch{}}},i.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},i.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},i.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))},i.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))},i.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},i})(),Ye=wn;var kn=i=>{if(typeof i=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[i]??`STATE_${i}`},xn=i=>{try{let e=new URL(i);return`${e.origin}${e.pathname}`}catch{return i}},Tt=i=>{if(i instanceof Error)return i.message?`${i.name}: ${i.message}`:i.name;if(typeof i=="string")return i;if(!i||typeof i!="object")return;let e=i,t=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!t)return;let n=typeof e.name=="string"&&e.name?e.name:void 0;return n?`${n}: ${t}`:t},De=i=>{if(i instanceof Error)return i.message?`${i.name}: ${i.message}`:i.name;if(typeof i=="string")return i;if(!i||typeof i!="object")return String(i);let e=i,t=[],n=Tt(e);n&&t.push(n);let r=Tt(e.error);r&&r!==n&&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!==n&&t.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&t.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&t.push(`url=${xn(o.url)}`);let s=kn(o.readyState);s&&t.push(`readyState=${s}`)}return t.length>0?t.join(" | "):"Unknown websocket event"};var O=null;typeof WebSocket<"u"?O=WebSocket:typeof MozWebSocket<"u"?O=MozWebSocket:typeof global<"u"?O=global.WebSocket||global.MozWebSocket:typeof window<"u"?O=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(O=self.WebSocket||self.MozWebSocket);var Ct=O;var Ie=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 En=Ye??Ze;var et=class extends Error{constructor(e="WebSocket connection timeout"){super(e),this.name="ConnectionTimeoutError"}},ae=class extends Error{constructor(t,n){super(t);this.originalError=n;this.name="ConnectionFailedError"}},N=class extends Error{constructor(t,n){super(t);this.data=n;this.name="InvalidMessageError"}},_=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},T,tt,nt,F=class{constructor(e,t,n={}){this.eventEmitter=t;this.options=n;G(this,T);this.clientId="";this.closed=!1;this.disposables=new Ie;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(n),this.url=new URL(e),this.PING_INTERVAL=n.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=n.connectWaitTimeout??3e4;let r=n.startClosed!==!1;this.rws=new En(this.url.toString(),[],{WebSocket:n.webSocket??globalThis.WebSocket??Ct,connectionTimeout:n.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:n.maxRetries??50,startClosed:r}),this.log("debug","Transport initialized",{url:this.url.toString(),options:n}),this.registerWatchers()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new _("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new _("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new _("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new _("maxRetries must be between 0 and 100")}log(e,t,n){if(this.options.debug){let r=new Date().toISOString(),o=n?JSON.stringify(n,null,2):"";console[e](`[Transport ${r}] ${t}${o?`
|
|
2
2
|
`+o:""}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):D(this,T,tt).call(this)}id(){return this.clientId}async registerWatchers(){let e=t=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(t)).catch(n=>{this.log("error","Failed to process queued WebSocket frame",{error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:n,rawMessage:t.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){let t;try{t=await this.toArrayBuffer(e.data)}catch(r){this.log("error","Unexpected WebSocket message type",{error:r instanceof Error?r.message:String(r),messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:r,rawMessage:e.data,timestamp:Date.now()});return}if(t.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let n;try{n=Qe(t)}catch(r){this.log("error","Failed to decode WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:r,rawMessage:t,timestamp:Date.now()});return}try{await this.handleRawMessage(n)}catch(r){this.log("error","Failed to process WebSocket frame",{error:r instanceof Error?r.message:String(r),byteLength:t.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:r,rawMessage:t,timestamp:Date.now()})}}async toArrayBuffer(e){if(e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer;throw new Error("Unexpected message type: "+typeof e)}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:t,event:n,as:r}=e;if(!n||typeof n!="string")throw new N("Message missing event field",e);if(this.log("debug","Processing message",{event:n,hasData:!!t}),n==="App.Actions.GetClientId"){this.clientId=t.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(n==="Events.BootError"){let o=t,s=new k(o?.message||"Notebook is no longer available",o||{});this.log("error","Boot error received",{data:t}),this.terminate(s,4e3,s.message);return}if(n==="response"){let{responseEvent:o,data:s}=t;if(!o)throw new N("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,s);return}if(n==="error"){let{errorEvent:o,data:s}=t;if(!o)throw new N("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:s}),await this.handleMessage(o,s);return}await this.handleMessage(n,t,r)}catch(t){t instanceof N?this.log("error","Invalid message format",{error:t.message,data:t.data}):this.log("error","Failed to parse message",{ev:e,error:t instanceof Error?t.message:String(t)}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:t,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,t,n){if(e==="App.Actions.GetClientId"){this.clientId=t.id,this.eventEmitter.emit(e,this.clientId);return}e&&this.eventEmitter.emit(n||e,t)}listen(e,t,n){return this.eventEmitter.listen(e,t)}onDidBootError(e){return this.eventEmitter.listen("transport.boot_error",t=>{e(t.error)})}removeListener(e,t){this.eventEmitter.removeListener(e,t)}listenOnce(e,t,n){return this.eventEmitter.once(e,t,n)}emit(e,...t){this.eventEmitter.emit(e,...t)}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,t={},n={}){if(this.terminalError)throw this.terminalError;let r=n.responseEvent||`${e}_${f()}_response`,o=`${r}_error`,s,a,c=()=>{s&&(this.rws.removeEventListener("close",s),this.rws.removeEventListener("error",s)),a&&(n.abortSignal?.removeEventListener("abort",a),a=void 0),this.eventEmitter.removeListener(r),this.eventEmitter.removeListener(o)},l=(g,p)=>{if(this.terminalError){p(this.terminalError);return}let m=new DOMException("Request aborted","AbortError");if(n.abortSignal?.aborted){p(m);return}if(n.abortSignal&&(a=()=>{p(m)},n.abortSignal.addEventListener("abort",a,{once:!0})),!this.isConnected||this.isClosed){p(new ae(`Connection is not open while sending ${e}. Current status: ${this.status}`));return}this.listenOnce(r,d=>{this.log("debug","Message response received",{action:e}),g(d)}),this.listenOnce(o,d=>{this.log("error","Message error received",{action:e,error:d});let S=d;p(new v(S.code,S.message,S))}),s=d=>{if(d.code===1008&&(d.reason||"").includes("rate limit")){p(new M(d.reason||"Rate limit exceeded",d));return}let S=De(d);p(this.terminalError||new ae(`Connection lost to the notebook during request: ${S}`,d))},this.rws.addEventListener("close",s),this.rws.addEventListener("error",s);try{this.rws.send(this.pack({action:e,data:t,errorEvent:o,responseEvent:r})),this.log("debug","Message sent",{action:e,data:t})}catch(d){this.log("error","Failed to send message",{action:e,error:d}),p(d)}},h=async()=>{if(n.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");if(await D(this,T,tt).call(this),n.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");let g=new Promise(l).finally(c);return n.timeout?H(g,n.timeout).catch(p=>{throw p instanceof I?B.fromPromiseTimeoutError(p):p}).finally(c):g},u=n.retries===!1?0:n.retries??0;return this.sendWithRetry(async()=>await h(),u)}send(e,t={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:t})),this.log("debug","One-way message sent",{action:e,data:t}),!0}catch(n){return this.log("error","Failed to send one-way message",{action:e,error:n}),!1}}pack(e){return new Blob([qe(e)])}sendWithRetry(e,t){return se(async(n,r)=>{try{return await e()}catch(o){if(o instanceof v||o instanceof M||o instanceof _||o instanceof N||o instanceof k||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:r}),n(o);return}throw o instanceof B&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:r,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:r,error:o instanceof Error?o.message:String(o)}),o}},{retries:t,onRetry:(n,r)=>{this.log("warn","Send operation retry",{attempt:r,maxRetries:t,error:n instanceof Error?n.message:String(n)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,t={},n={}){return n.responseEvent||(n.responseEvent=`${e}_${f()}`),this.call("invoke",{action:e,data:t},n)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){this.closed||this.close()}terminate(e,t=4e3,n=e.message){this.terminalError=e,e instanceof k&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(t,n)}close(e,t){if(!this.closed){this.log("info","Closing transport connection",{code:e,reason:t}),this.connectPromise=null,this.disposables.dispose();try{this.rws.close(e,t)}catch(n){this.log("error","Error closing WebSocket",{error:n instanceof Error?n.message:String(n)})}this.eventEmitter.emit("transport.closed",{code:e,reason:t,timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}}onDidConnect(e){this.rws.addEventListener("open",e);let t={dispose:()=>{this.rws.removeEventListener("open",e)}};return this.disposables.add(`connect_${f()}`,t),t}onDidClose(e){this.rws.addEventListener("close",e);let t={dispose:()=>{this.rws.removeEventListener("close",e)}};return this.disposables.add(`close_${f()}`,t),t}};T=new WeakSet,tt=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(),D(this,T,nt).call(this);return}let n,r=0,o=()=>{this.rws.removeEventListener("open",s),this.rws.removeEventListener("error",a),this.rws.removeEventListener("close",c),clearTimeout(n)},s=()=>{o(),this.connectPromise=null,e(),D(this,T,nt).call(this)},a=l=>{r+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:r,error:De(l)})},c=l=>{let h=De(l);if(l.code===1008||l.code===4e3){o(),this.connectPromise=null,t(new ae(`WebSocket connection failed: ${h}`,l));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:h})};this.rws.addEventListener("open",s),this.rws.addEventListener("error",a),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),n=setTimeout(()=>{o(),this.connectPromise=null,t(new et(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},nt=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.log("debug","Sending periodic ping"),await this.invoke("ping"),this.log("debug","Ping successful")}catch(t){this.log("error","Ping failed",{error:t instanceof Error?t.message:String(t)})}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};var it={};Fe(it,{default:()=>rt});function rt(i){return{all:i=i||new Map,on:function(e,t){var n=i.get(e);n?n.push(t):i.set(e,[t])},off:function(e,t){var n=i.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var n=i.get(e);n&&n.slice().map(function(r){r(t)}),(n=i.get("*"))&&n.slice().map(function(r){r(e,t)})}}}var Sn=rt??it;function Dn(i){let e=Sn(i);return e.once=(t,n)=>{let r=o=>{e.off(t,r),n(o)};return e.on(t,r),{dispose:()=>{e.off(t,r)}}},e}var U=class i{constructor(){this.emitter=Dn()}listen(e,t){let n=()=>{this.removeListener(e,t)};return this.emitter.on(e,t),{dispose:n}}emit(e,...t){this.emitter.emit(e,t.length>1?t:t[0])}once(e,t){return this.emitter.once(e,t)}static make(){return new i}static refresh(){return new i}removeListener(e,t){this.emitter.off(e,t)}static createInstance(){return new i}inspect(){return this.emitter.all}};var ce=class{constructor(e){this.okra=e}checkpoint(e,t,n="main",r=!1){return this.okra.invoke("git.checkpoint",{author:e,message:t,branch:n,allowEmpty:r})}checkout(e,t=!0){return this.okra.invoke("git.checkout",{branch:e,create:t})}sync(e,t,n="main",r,o="both",s=!1){return this.okra.invoke("git.sync",{url:e,author:t,ref:n,token:r,direction:o,force:s})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",this.normalizeRemoteInput(e))}merge(e){return this.okra.invoke("git.merge",this.normalizeRemoteInput(e))}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,t){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:t})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}credentials(){return this.okra.gitCredentials()}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}normalizeRemoteInput(e){if(e.notebookId===void 0)return e;let t=e.notebookId.trim();if(!t)throw new Error("'notebookId' cannot be empty.");if(e.url?.trim())throw new Error("Pass either 'url' or 'notebookId', not both.");if(e.target?.trim())throw new Error("Pass either 'target' or 'notebookId', not both.");let{notebookId:n,...r}=e;return{...r,url:this.gitUrlForNotebook(t)}}gitUrlForNotebook(e){let t=new URL(this.okra.data.gitUrl);return t.username="",t.password="",t.pathname=`/${encodeURIComponent(e)}.git`,t.search="",t.hash="",t.toString()}};var $=class{constructor(e,t,n){this.onEvent=e;this.onceEvent=t;this.beacon=n;this.urlHistory=[];this.currentIndex=0;this._canGoBack=!1;this._canGoForward=!1;this.beacon=n,this.setupUrlChangeListener(),this.urlHistory.push(n.iframe.src),this.updateNavigationState()}visit(e){if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState(),this.emitHistoryChange(e,"push")}setupUrlChangeListener(){this.beacon.on("urlChange",e=>{this.addToHistory(e.newUrl)})}addToHistory(e){this.currentIndex<this.urlHistory.length-1&&(this.urlHistory=this.urlHistory.slice(0,this.currentIndex+1)),this.urlHistory.push(e),this.currentIndex=this.urlHistory.length-1,this.updateNavigationState()}updateNavigationState(){let e=this._canGoBack,t=this._canGoForward;this._canGoBack=this.currentIndex>0,this._canGoForward=this.currentIndex<this.urlHistory.length-1,(e!==this._canGoBack||t!==this._canGoForward)&&this.emitNavigationStateChange()}emitNavigationStateChange(){this.beacon&&this.beacon.emit&&this.beacon.emit("navigationStateChange",{canGoBack:this._canGoBack,canGoForward:this._canGoForward,currentIndex:this.currentIndex,historyLength:this.urlHistory.length,timestamp:Date.now()})}get canGoBack(){return this._canGoBack}get canGoForward(){return this._canGoForward}async goBack(){if(!this.canGoBack)return{success:!1,error:"Cannot go back - no previous history"};this.currentIndex--,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"back"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async goForward(){if(!this.canGoForward)return{success:!1,error:"Cannot go forward - no forward history"};this.currentIndex++,this.updateNavigationState();let e=this.urlHistory[this.currentIndex];return this.beacon?(this.beacon.navigate(e),this.emitHistoryChange(e,"forward"),{success:!0,url:e}):{success:!1,error:"Beacon reference not set"}}async reload(){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){let e=this.urlHistory[this.currentIndex];if(!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"reload")}}getCurrentUrl(){return this.currentIndex>=0&&this.currentIndex<this.urlHistory.length?new URL(this.urlHistory[this.currentIndex]):new URL("about:blank")}getHistory(){return[...this.urlHistory]}getCurrentIndex(){return this.currentIndex}canGoBackSync(){return this.currentIndex>0}canGoForwardSync(){return this.currentIndex<this.urlHistory.length-1}emitHistoryChange(e,t){this.beacon&&this.beacon.emit&&this.beacon.emit("historyChange",{url:e,state:null,direction:t,timestamp:Date.now()})}async pushState(e){this.visit(e)}async replaceState(e){if(this.currentIndex>=0&&this.currentIndex<this.urlHistory.length){if(this.urlHistory[this.currentIndex]=e,!this.beacon)throw new Error("Beacon reference not set");this.beacon.navigate(e),this.emitHistoryChange(e,"replace")}else this.visit(e)}async getHistoryLength(){return this.urlHistory.length}async getHistoryState(){return null}async getHistoryInfo(){return{length:this.urlHistory.length,state:null,url:this.urlHistory[this.currentIndex]||"",canGoBack:this.canGoBack,canGoForward:this.canGoForward}}on(e,t){return this.onEvent(e,t)}once(e,t){this.onceEvent(e,t)}};function Rt(){if(typeof window>"u")throw new Error("Beacon SDK can only be used in a browser environment")}var L=class extends Error{constructor(t,n){super(t);this.code=n;this.name="BeaconError"}},le=class extends L{constructor(e,t){super(`Beacon operation '${e}' timed out after ${t}ms`),this.code="TIMEOUT"}},w=class extends L{constructor(e){super(`Beacon connection error: ${e}`),this.code="CONNECTION_ERROR"}},Pe=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;Rt(),this.iframe=e;let n={retries:3,minTimeout:1e3,maxTimeout:5e3,factor:2,randomize:!0};this.options={timeout:1e4,targetOrigin:"*",debug:!1,retry:{...n,...t.retry},...t},this.eventEmitter=U.make(),this.setupMessageChannel(),this.navigator=new $(this.eventEmitter.listen.bind(this.eventEmitter),this.eventEmitter.once.bind(this.eventEmitter),this)}setupMessageChannel(){let e=t=>{try{if(t.source!==this.iframe.contentWindow)return;let n=t.data;if(!n||typeof n!="object"||!n.type)return;n.type==="beacon:ready-for-channel"&&this.establishChannel().catch(r=>{this.options.debug&&console.error("[Beacon SDK] Channel establishment failed:",r)}),n.type==="beacon:channel-established"&&(this.channelEstablished=!0,this.isBeaconReady=!0,this.emit("ready",n.payload),this.options.debug&&console.log("[Beacon SDK] Channel established and beacon ready"))}catch(n){this.options.debug&&console.error("[Beacon SDK] Message parsing error:",n)}};window.addEventListener("message",e),this.disposables.push({dispose:()=>window.removeEventListener("message",e)})}async establishChannel(){if(!this.iframe.contentWindow)throw new 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,n)=>{let r=setTimeout(()=>{n(new w("Channel establishment timeout"))},this.options.timeout),o=()=>{this.channelEstablished&&this.isBeaconReady?(clearTimeout(r),t()):setTimeout(o,100)};o()})}handleBeaconMessage(e){this.options.debug&&console.log("[Beacon SDK] Received message:",e.type,e.payload);let t=e.type.replace("beacon:","");this.emit(t,e.payload);let n=this.messageHandlers.get(e.type);n&&n.forEach(r=>{try{r(e.payload)}catch(o){this.options.debug&&console.error("[Beacon SDK] Message handler error:",o)}})}waitForBeaconReady(){return se(async()=>new Promise((e,t)=>{if(this.isBeaconReady&&this.channelEstablished){e();return}let n=this.options.timeout,r=setTimeout(()=>{t(new le("beacon ready",n))},n),o=this.on("ready",()=>{clearTimeout(r),o.dispose(),e()})}),{retries:this.options.retry?.retries??3,minTimeout:this.options.retry?.minTimeout??1e3,maxTimeout:this.options.retry?.maxTimeout??5e3,factor:this.options.retry?.factor??2,randomize:this.options.retry?.randomize??!0,onRetry:(e,t)=>{if(this.options.debug){let n=e instanceof Error?e.message:String(e);console.warn(`[Beacon SDK] Beacon ready retry attempt ${t}:`,n)}this.isBeaconReady=!1,this.channelEstablished=!1}})}sendMessage(e,t={}){if(!this.port)throw new w("MessagePort not available - channel not established");let n={type:`beacon:${e}`,payload:t,timestamp:Date.now(),source:"parent",id:this.generateId()};try{this.port.postMessage(n),this.options.debug&&console.log("[Beacon SDK] Sent message via port:",n.type,n.payload)}catch(r){throw new w(`Failed to send message via port: ${r instanceof Error?r.message:String(r)}`)}}async sendAndWaitFor(e,t,n={},r){return await this.ready(),se(async o=>new Promise((s,a)=>{let c=r||this.options.timeout,l=setTimeout(()=>{h.dispose();let u=new le(e,c);a(u)},c),h=this.eventEmitter.listen(t,u=>{clearTimeout(l),h.dispose(),s(u)});try{this.sendMessage(e,n)}catch(u){clearTimeout(l),h.dispose(),u instanceof w?a(u):o(u)}}),{retries:this.options.retry?.retries??3,minTimeout:this.options.retry?.minTimeout??1e3,maxTimeout:this.options.retry?.maxTimeout??5e3,factor:this.options.retry?.factor??2,randomize:this.options.retry?.randomize??!0,onRetry:(o,s)=>{if(this.options.debug){let a=o instanceof Error?o.message:String(o);console.warn(`[Beacon SDK] Retry attempt ${s} for ${e}:`,a)}}})}generateId(){return`sdk_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}emit(e,t){this.eventEmitter.emit(e,t)}start(){return this.isStarted?this.readyPromise||Promise.resolve():(this.isStarted=!0,this.readyPromise=this.waitForBeaconReady(),this.readyPromise)}async ready(){if(!this.isStarted)throw new L("Beacon has not been started. Call start() first.");if(!this.readyPromise)throw new L("Beacon ready promise is not available");return H(this.readyPromise,this.options.timeout)}get isReady(){return this.isBeaconReady}on(e,t){return this.eventEmitter.listen(e,t)}once(e,t){return 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 captureScreenshot(e={}){let t=e.mediaTimeoutMs??e.timeout??3e4,n=e.transportTimeoutMs??t+5e3;return this.sendAndWaitFor("captureScreenshot","screenshotResult",e,n)}async debug(e,t){let n=new URL(e.path,this.iframe.src||window.location.origin).href;this.iframe.src!==n&&(this.navigator.visit(n),await this.ready()),t&&await this.wait(t);let 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 ot(i,e){return new Pe(i,e)}function In(){try{return Rt(),!0}catch{return!1}}var ue=class{constructor(e){this.client=e}async create(e,t={}){let n=await this.client.post(`/notebook/${e}/deployments`,t);return new x(n.data,this.client)}async list(e){return(await this.client.get(`/notebook/${e}/deployments`)).data}async slugAvailability(e,t){let n=new URLSearchParams({slug:t}).toString();return(await this.client.get(`/notebook/${e}/deployments/slug-availability?${n}`)).data}},pe=class{constructor(e){this.client=e}async get(e){let t=await this.client.get(`/deployments/${e}`);return new x(t.data,this.client)}async redeploy(e,t={}){let n=await this.client.post(`/deployments/${e}/redeploy`,t);return new x(n.data,this.client)}async delete(e){await this.client.delete(`/deployments/${e}`)}async setProtection(e,t){let n=await this.client.put(`/deployments/${e}/protection`,t);return new x(n.data,this.client)}async protection(e){return(await this.client.get(`/deployments/${e}/protection`)).data}async createProtectionSession(e){return(await this.client.post(`/deployments/${e}/protection/session`)).data}async disableProtection(e){let t=await this.client.delete(`/deployments/${e}/protection`);return new x(t.data,this.client)}async setFeedback(e,t){let n=await this.client.put(`/deployments/${e}/feedback`,t);return new x(n.data,this.client)}async listDomains(e){let t=await this.client.get(`/deployments/${e}/domains`);return Cn(t.data)}async createDomain(e,t){return(await this.client.post(`/deployments/${e}/domains`,t)).data}async refreshDomain(e,t){return(await this.client.post(`/deployments/${e}/domains/${t}/refresh`)).data}async deleteDomain(e,t){await this.client.delete(`/deployments/${e}/domains/${t}`)}async events(e){return st(await this.client.stream(`/deployments/${e}/events/stream`))}async buildLogs(e,t){return st(await this.client.stream(`/deployments/${e}/builds/${t}/logs/stream`))}async logs(e){return st(await this.client.stream(`/deployments/${e}/logs/stream`))}},x=class{constructor(e,t){this.data=e;this.client=t}refresh(){return this.client.deployments.get(this.data.id)}redeploy(e={}){return this.client.deployments.redeploy(this.data.id,e)}delete(){return this.client.deployments.delete(this.data.id)}async wait(e={}){let t=e.intervalMs??1e3,n=e.timeoutMs??3e5,r=Date.now(),o=this;for(;!Pn(o.data.status);){if(Date.now()-r>n)throw new Error(`Timed out waiting for deployment ${this.data.id}`);await Tn(t),o=await o.refresh()}return o}events(){return this.client.deployments.events(this.data.id)}buildLogs(e=this.data.latest_build?.id??""){return e===""?Promise.reject(new Error("Deployment has no latest build id")):this.client.deployments.buildLogs(this.data.id,e)}logs(){return this.client.deployments.logs(this.data.id)}setProtection(e){return this.client.deployments.setProtection(this.data.id,e)}protection(){return this.client.deployments.protection(this.data.id)}createProtectionSession(){return this.client.deployments.createProtectionSession(this.data.id)}disableProtection(){return this.client.deployments.disableProtection(this.data.id)}setFeedback(e){return this.client.deployments.setFeedback(this.data.id,e)}domains(){return this.client.deployments.listDomains(this.data.id)}addDomain(e){return this.client.deployments.createDomain(this.data.id,e)}refreshDomain(e){return this.client.deployments.refreshDomain(this.data.id,e)}deleteDomain(e){return this.client.deployments.deleteDomain(this.data.id,e)}};function Pn(i){return["healthy","failed","stopped","deleted","delete_failed"].includes(i)}function Tn(i){return new Promise(e=>setTimeout(e,i))}function Cn(i){return Array.isArray(i)?i:Array.isArray(i.data)?i.data:[]}function st(i){let e=new TextDecoder,t="";return i.pipeThrough(new TransformStream({transform(n,r){t+=e.decode(n,{stream:!0});let o=t.split(`
|
|
3
|
-
`);t=o.pop()??"";for(let s of o){let a=s.trim();a!==""&&r.enqueue(JSON.parse(a))}},flush(n){t+=e.decode();let r=t.trim();r!==""&&n.enqueue(JSON.parse(r))}}))}function Rn(i){return Array.isArray(i)?i:Object.entries(i).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Te=class extends Error{constructor(t,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},de=class extends Error{constructor(t,n){let r=An(n),o=Nn(r,n);super(`PHPSandbox API Error: ${t.status} ${t.statusText}${o===""?"":` - ${o}`}`);this.response=t;this.body=n;this.status=t.status,this.data=r,this.apiMessage=o===""?void 0:o}};function An(i){try{return JSON.parse(i)}catch{return null}}function Nn(i,e){if(i!==null&&typeof i=="object"){let t=i;if(typeof t.message=="string"&&t.message.trim()!=="")return t.message.trim();if(t.error!==void 0)return typeof t.error=="string"?t.error.trim():JSON.stringify(t.error)}return e.trim()}var Ce=class{constructor(e){this.client=e;this.secrets=new Ae(e),this.preview=new Ne(e),this.mail=new _e(e),this.deployments=new ue(e)}async create(e,t={},n=!0){let r=await this.client.post("/notebook",{template:e,...t}),o=new E(r.data,this.client);return n?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new E(t.data,this.client)}async update(e,t={}){let n=await this.client.put(`/notebook/${e}`,t);return new E(n.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e,t={}){let n=await this.client.post(`/notebook/${e}/fork`,t);return this.init(new E(n.data,this.client))}async gitCredentials(e){return(await this.client.post(`/notebook/${e}/git/credentials`)).data}async open(e){let t=await this.client.get(`/notebook/${e}`);return new E(t.data,this.client)}openFromData(e){return this.init(new E(e,this.client))}async init(e){return await e.ready(),e}};function _n(i){let e=new URL(i),t=e.pathname.replace(/\/+$/,"");return e.pathname=t===""||t==="/"?"/v1/":`${t}/`,e.search="",e.hash="",e.toString()}var Re=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.deployments=new pe(this),this.notebook=new Ce(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=_n(t),n.fetch&&(this.fetch=n.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t===void 0?void 0:JSON.stringify(t)})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t===void 0?void 0:JSON.stringify(t)})}async stream(e){let t=await this.fetch(new Request(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!t.ok)throw new de(t,await t.text());if(!t.body)throw new Error("PHPSandbox API Error: response body is not readable");return t.body}async makeRequest(e,t,n){let r=await this.fetch(new Request(new URL(t.replace(/^\//,""),this.baseUrl),{method:e,...n,headers:this.headers}));if(!r.ok)throw new de(r,await r.text());if(r.status===204)return{data:void 0};let o=await r.text();return{data:o===""?void 0:JSON.parse(o)}}},at=class extends Re{},Ae=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let r=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,r)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:Rn(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ne=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},_e=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${Un(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},C,he,ct,E=class{constructor(e,t){this.data=e;this.client=t;G(this,he);this.initialized=!1;G(this,C);this.disposables=[];this.emitter=U.createInstance(),this.socket=new F(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),Ge(this,C,D(this,he,ct).call(this)),this.file=new W(this),this.terminal=new K(this),this.auth=new j(this),this.lsp=new V(this),this.composer=new J(this),this.log=new Q(this),this.repl=new Y(this),this.container=new q(this),this.laravel=new X(this),this.shell=new Z(this),this.git=new ce(this),this.services=new ee(this),this.config=new te(this),this.secrets=new Ue(t,this.data.id),this.preview=new Le(t,this.data.id),this.mail=new Me(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(),me(this,C)))()}fork(e={}){return this.client.notebook.fork(this.data.id,e)}deploy(e={}){return this.client.notebook.deployments.create(this.data.id,e)}gitCredentials(){return this.client.notebook.gitCredentials(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.
|
|
3
|
+
`);t=o.pop()??"";for(let s of o){let a=s.trim();a!==""&&r.enqueue(JSON.parse(a))}},flush(n){t+=e.decode();let r=t.trim();r!==""&&n.enqueue(JSON.parse(r))}}))}function Rn(i){return Array.isArray(i)?i:Object.entries(i).map(([e,t])=>({name:e,...typeof t=="string"?{value:t}:t}))}var Te=class extends Error{constructor(t,n={}){super(t);this.message=t;this.data=n;this.name="NotebookInitError"}},de=class extends Error{constructor(t,n){let r=An(n),o=Nn(r,n);super(`PHPSandbox API Error: ${t.status} ${t.statusText}${o===""?"":` - ${o}`}`);this.response=t;this.body=n;this.status=t.status,this.data=r,this.apiMessage=o===""?void 0:o}};function An(i){try{return JSON.parse(i)}catch{return null}}function Nn(i,e){if(i!==null&&typeof i=="object"){let t=i;if(typeof t.message=="string"&&t.message.trim()!=="")return t.message.trim();if(t.error!==void 0)return typeof t.error=="string"?t.error.trim():JSON.stringify(t.error)}return e.trim()}var Ce=class{constructor(e){this.client=e;this.secrets=new Ae(e),this.preview=new Ne(e),this.mail=new _e(e),this.deployments=new ue(e)}async create(e,t={},n=!0){let r=await this.client.post("/notebook",{template:e,...t}),o=new E(r.data,this.client);return n?this.init(o):o}async get(e){let t=await this.client.get(`/notebook/${e}`);return new E(t.data,this.client)}async update(e,t={}){let n=await this.client.put(`/notebook/${e}`,t);return new E(n.data,this.client)}async delete(e){await this.client.delete(`/notebook/${e}`)}async fork(e,t={}){let n=await this.client.post(`/notebook/${e}/fork`,t);return this.init(new E(n.data,this.client))}async gitCredentials(e){return(await this.client.post(`/notebook/${e}/git/credentials`)).data}async open(e){let t=await this.client.get(`/notebook/${e}`);return new E(t.data,this.client)}openFromData(e){return this.init(new E(e,this.client))}async init(e){return await e.ready(),e}};function _n(i){let e=new URL(i),t=e.pathname.replace(/\/+$/,"");return e.pathname=t===""||t==="/"?"/v1/":`${t}/`,e.search="",e.hash="",e.toString()}var Re=class{constructor(e,t="https://api.phpsandbox.io/v1",n={}){this.fetch=globalThis.fetch;this.deployments=new pe(this),this.notebook=new Ce(this),this.options=Object.assign({startClosed:!0},n),this.baseUrl=_n(t),n.fetch&&(this.fetch=n.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get(e){return this.makeRequest("GET",e)}post(e,t){return this.makeRequest("POST",e,{body:t===void 0?void 0:JSON.stringify(t)})}delete(e){return this.makeRequest("DELETE",e)}put(e,t){return this.makeRequest("PUT",e,{body:t===void 0?void 0:JSON.stringify(t)})}async stream(e){let t=await this.fetch(new Request(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!t.ok)throw new de(t,await t.text());if(!t.body)throw new Error("PHPSandbox API Error: response body is not readable");return t.body}async makeRequest(e,t,n){let r=await this.fetch(new Request(new URL(t.replace(/^\//,""),this.baseUrl),{method:e,...n,headers:this.headers}));if(!r.ok)throw new de(r,await r.text());if(r.status===204)return{data:void 0};let o=await r.text();return{data:o===""?void 0:JSON.parse(o)}}},at=class extends Re{},Ae=class{constructor(e){this.client=e}async list(e){return(await this.client.get(`/notebook/${e}/secrets`)).data}async set(e,t,n){let r=typeof n=="string"?{name:t,value:n}:{name:t,...n};return(await this.client.put(`/notebook/${e}/secrets`,r)).data}async setMany(e,t){return(await this.client.put(`/notebook/${e}/secrets`,{secrets:Rn(t)})).data}async delete(e,t){await this.client.delete(`/notebook/${e}/secrets/${encodeURIComponent(t)}`)}},Ne=class{constructor(e){this.client=e}async get(e){return(await this.client.get(`/notebook/${e}/preview`)).data}async setPassword(e,t){return(await this.client.put(`/notebook/${e}/preview`,t)).data}async disable(e){await this.client.delete(`/notebook/${e}/preview`)}async createSession(e){return(await this.client.post(`/notebook/${e}/preview/session`)).data}async createHandoff(e,t){return(await this.client.post(`/notebook/${e}/preview/handoff`,t)).data}},_e=class{constructor(e){this.client=e}async status(e){return(await this.client.get(`/notebook/${e}/mail`)).data}async enable(e){return(await this.client.put(`/notebook/${e}/mail`)).data}async disable(e){await this.client.delete(`/notebook/${e}/mail`)}async list(e,t={}){return(await this.client.get(`/notebook/${e}/mails${Un(t)}`)).data}async get(e,t){return(await this.client.get(`/notebook/${e}/mails/${encodeURIComponent(t)}`)).data}async delete(e,t){await this.client.delete(`/notebook/${e}/mails/${encodeURIComponent(t)}`)}},C,he,ct,E=class{constructor(e,t){this.data=e;this.client=t;G(this,he);this.initialized=!1;G(this,C);this.disposables=[];this.emitter=U.createInstance(),this.socket=new F(e.okraUrl,this.emitter,{debug:t.options.debug,startClosed:t.options.startClosed,webSocket:t.options.webSocket}),this.watchConnection(),Ge(this,C,D(this,he,ct).call(this)),this.file=new W(this),this.terminal=new K(this),this.auth=new j(this),this.lsp=new V(this),this.composer=new J(this),this.log=new Q(this),this.repl=new Y(this),this.container=new q(this),this.laravel=new X(this),this.shell=new Z(this),this.git=new ce(this),this.services=new ee(this),this.config=new te(this),this.secrets=new Ue(t,this.data.id),this.preview=new Le(t,this.data.id),this.mail=new Me(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(),me(this,C)))()}fork(e={}){return this.client.notebook.fork(this.data.id,e)}deploy(e={}){return this.client.notebook.deployments.create(this.data.id,e)}gitCredentials(){return this.client.notebook.gitCredentials(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.restart()}invoke(e,t={},n={}){return this.socket.invoke(e,t||{},n)}send(e,t={}){return this.socket.send(e,t||{})}ping(){return this.invoke("ping")}listen(e,t){let n=this.emitter.listen(e,t);return this.disposables.push(n),n}dispose(){this.disposables.forEach(e=>e.dispose()),!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}whenConnected(){return this.waitForSocketConnection({rejectOnClose:!1})}waitForSocketConnection(e){let t=this.socket.getTerminalError();return t?Promise.reject(t):this.socket.isConnected?Promise.resolve(this):new Promise((n,r)=>{let o=[],s=!1,a=()=>{for(let l of o)l.dispose();o.length=0},c=l=>{s||(s=!0,a(),l())};try{o.push(this.socket.onDidConnect(()=>c(()=>n(this)))),e.rejectOnClose&&o.push(this.socket.onDidClose(()=>c(()=>r(new Error("Connection closed"))))),o.push(this.socket.onDidBootError(l=>c(()=>r(l))))}catch(l){c(()=>r(l))}})}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,D(this,he,ct).call(this),this.ready().then(()=>this)}async beacon(e,t){let n=await this.ready();return e.src=n.data.previewUrl,ot(e,t)}};C=new WeakMap,he=new WeakSet,ct=function(){return Ge(this,C,new Promise((e,t)=>{let n=this.onDidInitialize(o=>{if(r.dispose(),n.dispose(),this.initialized=o,o.type==="error"){t(new Te(o.message,o.data));return}e(o)}),r=this.onDidBootError(o=>{n.dispose(),r.dispose(),t(o)})})),me(this,C).catch(()=>{}),me(this,C)};var Ue=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)}},Le=class{constructor(e,t){this.client=e;this.notebookId=t}get(){return this.client.notebook.preview.get(this.notebookId)}setPassword(e){return this.client.notebook.preview.setPassword(this.notebookId,e)}disable(){return this.client.notebook.preview.disable(this.notebookId)}createSession(){return this.client.notebook.preview.createSession(this.notebookId)}createHandoff(e){return this.client.notebook.preview.createHandoff(this.notebookId,e)}},Me=class{constructor(e,t){this.client=e;this.notebookId=t}status(){return this.client.notebook.mail.status(this.notebookId)}enable(){return this.client.notebook.mail.enable(this.notebookId)}disable(){return this.client.notebook.mail.disable(this.notebookId)}list(e={}){return this.client.notebook.mail.list(this.notebookId,e)}get(e){return this.client.notebook.mail.get(this.notebookId,e)}delete(e){return this.client.notebook.mail.delete(this.notebookId,e)}};function Un(i){let e=new URLSearchParams;for(let[n,r]of Object.entries(i))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&e.set(n,String(r));let t=e.toString();return t===""?"":`?${t}`}return Mt(Ln);})();
|
|
4
4
|
/*! Bundled license information:
|
|
5
5
|
|
|
6
6
|
reconnecting-websocket/dist/reconnecting-websocket-mjs.js:
|
package/dist/index.js
CHANGED
|
@@ -349,7 +349,7 @@ export class NotebookInstance {
|
|
|
349
349
|
return this.container.stop();
|
|
350
350
|
}
|
|
351
351
|
restart() {
|
|
352
|
-
return this.container.
|
|
352
|
+
return this.container.restart();
|
|
353
353
|
}
|
|
354
354
|
invoke(action, data = {}, options = {}) {
|
|
355
355
|
return this.socket.invoke(action, data || {}, options);
|
package/package.json
CHANGED