Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@devbookhq/sdk

Package Overview
Dependencies
Maintainers
2
Versions
152
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@devbookhq/sdk - npm Package Compare versions

Comparing version 2.5.0 to 2.5.1

2

dist/cjs/index.js

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var s=require("rpc-websocket-client");require("cross-fetch/polyfill");var e=require("openapi-typescript-fetch");function i(s,e,i,t){return new(i||(i=Promise))((function(o,n){function r(s){try{c(t.next(s))}catch(s){n(s)}}function l(s){try{c(t.throw(s))}catch(s){n(s)}}function c(s){var e;s.done?o(s.value):(e=s.value,e instanceof i?e:new i((function(s){s(e)}))).then(r,l)}c((t=t.apply(s,e||[])).next())}))}const t=e.Fetcher.for();function o(s){return new Promise((e=>setTimeout(e,s)))}t.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,e=!1){this.logID=s,this.isEnabled=e}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[${this.id()}]`,...s)}error(...s){console.error(`[${this.id()} ERROR]`,...s)}}function r(s){return"fulfilled"===s.status}function l(s){if(!s.every((s=>"fulfilled"===s.status)))return s.reduce(((s,e,i)=>"rejected"===e.status?s+"\n"+`[${i}]: `+`${JSON.stringify(e)}`:s),"errors:\n")}function c(){let s,e;const i=new Promise(((i,t)=>{s=i,e=t}));return{resolve:s,reject:e,promise:i}}const d=t.path("/sessions").method("post").create({api_key:!0}),h=t.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var a;exports.CodeSnippetExecState=void 0,(a=exports.CodeSnippetExecState||(exports.CodeSnippetExecState={})).Running="Running",a.Stopped="Stopped";function u(s){let e="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=i.length;for(let o=0;o<s;o++)e+=i.charAt(Math.floor(Math.random()*t));return e}var p;exports.OutType=void 0,(p=exports.OutType||(exports.OutType={})).Stdout="Stdout",p.Stderr="Stderr",exports.Session=class extends class{constructor(e){this.opts=e,this.isOpen=!1,this.rpc=new s.RpcWebSocketClient,this.subscribers=[],this.logger=new n("Session",e.debug),this.logger.log(`Session for code snippet "${e.id}" initialized`)}call(s,e,t){return i(this,void 0,void 0,(function*(){return this.logger.log(`${s}_${e}`,t),this.rpc.call(`${s}_${e}`,t)}))}handleSubscriptions(...s){return i(this,void 0,void 0,(function*(){const e=yield Promise.allSettled(s);if(e.every((s=>"fulfilled"===s.status)))return e.map((s=>"fulfilled"===s.status?s.value:void 0));throw yield Promise.all(e.filter(r).map((s=>s.value?this.unsubscribe(s.value):void 0))),new Error(l(e))}))}unsubscribe(s){return i(this,void 0,void 0,(function*(){const e=this.subscribers.find((e=>e.subID===s));e&&(yield this.call(e.service,"unsubscribe",[e.subID]),this.subscribers=this.subscribers.filter((s=>s!==e)),this.logger.log(`Unsubscribed from "${e.service}"`))}))}subscribe(s,e,t,...o){return i(this,void 0,void 0,(function*(){const i=yield this.call(s,"subscribe",[t,...o]);if("string"!=typeof i)throw new Error(`Cannot subscribe to ${s}_${t}${o.length>0?" with params ["+o.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(i)}`);return this.subscribers.push({subID:i,handler:e,service:s}),this.logger.log(`Subscribed to "${s}_${t}"${o.length>0?" with params ["+o.join(", ")+"] and":""} with id "${i}"`),i}))}getHostname(s){if(this.opts.__debug_hostname)return s&&"remote"===this.opts.__debug_devEnv?`${s}-${this.opts.__debug_hostname}`:s?`${this.opts.__debug_hostname}:${s}`:this.opts.__debug_hostname;if(!this.session)return;const e=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${e}`:e}close(){var s,e,t;return i(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(t=null===(e=this.opts)||void 0===e?void 0:e.onClose)||void 0===t||t.call(e),this.logger.log("Disconected from the session")}}))}open(){return i(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");if(this.isOpen=!0,!this.opts.__debug_hostname)try{const s=yield d({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof d.Error){const e=s.getActualType();if(400===e.status)throw new Error(`Error creating session - (${e.status}) bad request: ${e.data.message}`);if(401===e.status)throw new Error(`Error creating session - (${e.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${e.data.message}`);if(500===e.status)throw new Error(`Error creating session - (${e.status}) server error: ${e.data.message}`);throw s}}const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const e=`${"local"===this.opts.__debug_devEnv?"ws":"wss"}://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let t,n,r=!1;const l=new Promise(((s,e)=>{t=()=>{r||(r=!0,s())},n=()=>{r||(r=!0,e())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==t||t()})),this.rpc.onClose((s=>i(this,void 0,void 0,(function*(){var i,t,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(t=(i=this.opts).onDisconnect)||void 0===t||t.call(i),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{this.subscribers=[],yield this.rpc.connect(e),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(e)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((e=>{var i;return e.subID===(null===(i=s.params)||void 0===i?void 0:i.subscription)})).forEach((e=>{var i;return e.handler(null===(i=s.params)||void 0===i?void 0:i.result)}))}refresh(s){return i(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield h({sessionID:s,api_key:this.opts.apiKey})}catch(e){if(e instanceof h.Error){const i=e.getActualType();if(404===i.status)return void this.logger.error(`Error refreshing session - (${i.status}): ${i.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${i.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var e,t,o,n;return i(this,void 0,void 0,(function*(){yield s.open.call(this),yield this.handleSubscriptions((null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):void 0,(null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):void 0,(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):void 0,(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):void 0),this.codeSnippet={run:(s,e={})=>i(this,void 0,void 0,(function*(){var i,t;const o=yield this.call("codeSnippet","run",[s,e]);return null===(t=null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)||void 0===t||t.call(i,o),o})),stop:()=>i(this,void 0,void 0,(function*(){var s,e;const i=yield this.call("codeSnippet","stop");return null===(e=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===e||e.call(s,i),i}))},this.filesystem={listAllFiles:s=>i(this,void 0,void 0,(function*(){return yield this.call("filesystem","listAllFiles",[s])})),removeFile:s=>i(this,void 0,void 0,(function*(){yield this.call("filesystem","removeFile",[s])})),writeFile:(s,e)=>i(this,void 0,void 0,(function*(){yield this.call("filesystem","writeFile",[s,e])})),readFile:s=>i(this,void 0,void 0,(function*(){return yield this.call("filesystem","readFile",[s])}))},this.terminal={killProcess:s=>i(this,void 0,void 0,(function*(){yield this.call("terminal","killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:e,size:t,terminalID:o=u(12)})=>i(this,void 0,void 0,(function*(){const[n,c]=yield this.handleSubscriptions(this.subscribe("terminal",s,"onData",o),e?this.subscribe("terminal",e,"onChildProcessesChange",o):void 0);try{yield this.call("terminal","start",[o,t.cols,t.rows])}catch(s){const e=l(yield Promise.allSettled([this.unsubscribe(n),c?this.unsubscribe(c):void 0]));throw e&&this.logger.error(e),s}return{terminalID:o,destroy:()=>i(this,void 0,void 0,(function*(){!function(s){if(s.some((s=>"rejected"===s.status)))throw new Error(l(s));s.filter(r).map((s=>s.value))}(yield Promise.allSettled([this.unsubscribe(n),c?this.unsubscribe(c):void 0,yield this.call("terminal","destroy",[o])]))})),sendData:s=>i(this,void 0,void 0,(function*(){yield this.call("terminal","data",[o,s])})),resize:({cols:s,rows:e})=>i(this,void 0,void 0,(function*(){yield this.call("terminal","resize",[o,s,e])}))}}))},this.process={start:({cmd:s,onStdout:e,onStderr:t,onExit:o,envVars:n={},rootdir:r="/",processID:d=u(12)})=>i(this,void 0,void 0,(function*(){const{promise:h,resolve:a}=c(),[u,p,v]=yield this.handleSubscriptions(this.subscribe("process",a,"onExit",d),e?this.subscribe("process",e,"onStdout",d):void 0,t?this.subscribe("process",t,"onStderr",d):void 0),{promise:g,resolve:f}=c();h.then((()=>i(this,void 0,void 0,(function*(){const s=l(yield Promise.allSettled([this.unsubscribe(u),p?this.unsubscribe(p):void 0,v?this.unsubscribe(v):void 0]));s&&this.logger.error(s),null==o||o(),f()}))));try{yield this.call("process","start",[d,s,n,r])}catch(s){throw a(),yield g,s}return{processID:d,kill:()=>i(this,void 0,void 0,(function*(){try{yield this.call("process","kill",[d])}finally{a(),yield g}})),sendStdin:s=>i(this,void 0,void 0,(function*(){yield this.call("process","stdin",[d,s])}))}}))}}))}},exports.api=t;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var s=require("rpc-websocket-client");require("cross-fetch/polyfill");var i=require("openapi-typescript-fetch");function e(s,i,e,t){return new(e||(e=Promise))((function(o,n){function r(s){try{c(t.next(s))}catch(s){n(s)}}function l(s){try{c(t.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof e?i:new e((function(s){s(i)}))).then(r,l)}c((t=t.apply(s,i||[])).next())}))}const t=i.Fetcher.for();function o(s){return new Promise((i=>setTimeout(i,s)))}t.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[${this.id()}]`,...s)}error(...s){console.error(`[${this.id()} ERROR]`,...s)}}function r(s){return"fulfilled"===s.status}function l(s){if(!s.every((s=>"fulfilled"===s.status)))return s.reduce(((s,i,e)=>"rejected"===i.status?s+"\n"+`[${e}]: `+`${JSON.stringify(i)}`:s),"errors:\n")}function c(){let s,i;const e=new Promise(((e,t)=>{s=e,i=t}));return{resolve:s,reject:i,promise:e}}const d=t.path("/sessions").method("post").create({api_key:!0}),h=t.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var a;exports.CodeSnippetExecState=void 0,(a=exports.CodeSnippetExecState||(exports.CodeSnippetExecState={})).Running="Running",a.Stopped="Stopped";function u(s){let i="";const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length;for(let o=0;o<s;o++)i+=e.charAt(Math.floor(Math.random()*t));return i}var p;exports.OutType=void 0,(p=exports.OutType||(exports.OutType={})).Stdout="Stdout",p.Stderr="Stderr",exports.Session=class extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s.RpcWebSocketClient,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i,t){return e(this,void 0,void 0,(function*(){return this.rpc.call(`${s}_${i}`,t)}))}handleSubscriptions(...s){return e(this,void 0,void 0,(function*(){const i=yield Promise.allSettled(s);if(i.every((s=>"fulfilled"===s.status)))return i.map((s=>"fulfilled"===s.status?s.value:void 0));throw yield Promise.all(i.filter(r).map((s=>s.value?this.unsubscribe(s.value):void 0))),new Error(l(i))}))}unsubscribe(s){return e(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subID===s));i&&(yield this.call(i.service,"unsubscribe",[i.subID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.service}"`))}))}subscribe(s,i,t,...o){return e(this,void 0,void 0,(function*(){const e=yield this.call(s,"subscribe",[t,...o]);if("string"!=typeof e)throw new Error(`Cannot subscribe to ${s}_${t}${o.length>0?" with params ["+o.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(e)}`);return this.subscribers.push({subID:e,handler:i,service:s}),this.logger.log(`Subscribed to "${s}_${t}"${o.length>0?" with params ["+o.join(", ")+"] and":""} with id "${e}"`),e}))}getHostname(s){if(this.opts.__debug_hostname)return s&&"remote"===this.opts.__debug_devEnv?`${s}-${this.opts.__debug_hostname}`:s?`${this.opts.__debug_hostname}:${s}`:this.opts.__debug_hostname;if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,t;return e(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(t=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===t||t.call(i),this.logger.log("Disconected from the session")}}))}open(){return e(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");if(this.isOpen=!0,!this.opts.__debug_hostname)try{const s=yield d({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof d.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`${"local"===this.opts.__debug_devEnv?"ws":"wss"}://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let t,n,r=!1;const l=new Promise(((s,i)=>{t=()=>{r||(r=!0,s())},n=()=>{r||(r=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==t||t()})),this.rpc.onClose((s=>e(this,void 0,void 0,(function*(){var e,t,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(t=(e=this.opts).onDisconnect)||void 0===t||t.call(e),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{this.subscribers=[],yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var e;return i.subID===(null===(e=s.params)||void 0===e?void 0:e.subscription)})).forEach((i=>{var e;return i.handler(null===(e=s.params)||void 0===e?void 0:e.result)}))}refresh(s){return e(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield h({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof h.Error){const e=i.getActualType();if(404===e.status)return void this.logger.error(`Error refreshing session - (${e.status}): ${e.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${e.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,t,o,n;return e(this,void 0,void 0,(function*(){yield s.open.call(this),yield this.handleSubscriptions((null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):void 0,(null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):void 0,(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):void 0,(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):void 0),this.codeSnippet={run:(s,i={})=>e(this,void 0,void 0,(function*(){var e,t;const o=yield this.call("codeSnippet","run",[s,i]);return null===(t=null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStateChange)||void 0===t||t.call(e,o),o})),stop:()=>e(this,void 0,void 0,(function*(){var s,i;const e=yield this.call("codeSnippet","stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,e),e}))},this.filesystem={listAllFiles:s=>e(this,void 0,void 0,(function*(){return yield this.call("filesystem","listAllFiles",[s])})),removeFile:s=>e(this,void 0,void 0,(function*(){yield this.call("filesystem","removeFile",[s])})),writeFile:(s,i)=>e(this,void 0,void 0,(function*(){yield this.call("filesystem","writeFile",[s,i])})),readFile:s=>e(this,void 0,void 0,(function*(){return yield this.call("filesystem","readFile",[s])}))},this.terminal={killProcess:s=>e(this,void 0,void 0,(function*(){yield this.call("terminal","killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:t,onExit:o,terminalID:n=u(12)})=>e(this,void 0,void 0,(function*(){const{promise:r,resolve:d}=c(),[h,a,u]=yield this.handleSubscriptions(this.subscribe("terminal",s,"onData",n),this.subscribe("terminal",d,"onExit",n),i?this.subscribe("terminal",i,"onChildProcessesChange",n):void 0),{promise:p,resolve:v}=c();r.then((()=>e(this,void 0,void 0,(function*(){const s=l(yield Promise.allSettled([this.unsubscribe(a),this.unsubscribe(h),u?this.unsubscribe(u):void 0]));s&&this.logger.error(s),null==o||o(),v()}))));try{yield this.call("terminal","start",[n,t.cols,t.rows])}catch(s){throw d(),yield p,s}return{terminalID:n,destroy:()=>e(this,void 0,void 0,(function*(){try{yield this.call("terminal","destroy",[n])}finally{d(),yield p}})),sendData:s=>e(this,void 0,void 0,(function*(){yield this.call("terminal","data",[n,s])})),resize:({cols:s,rows:i})=>e(this,void 0,void 0,(function*(){yield this.call("terminal","resize",[n,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:t,onExit:o,envVars:n={},rootdir:r="/",processID:d=u(12)})=>e(this,void 0,void 0,(function*(){const{promise:h,resolve:a}=c(),[u,p,v]=yield this.handleSubscriptions(this.subscribe("process",a,"onExit",d),i?this.subscribe("process",i,"onStdout",d):void 0,t?this.subscribe("process",t,"onStderr",d):void 0),{promise:g,resolve:f}=c();h.then((()=>e(this,void 0,void 0,(function*(){const s=l(yield Promise.allSettled([this.unsubscribe(u),p?this.unsubscribe(p):void 0,v?this.unsubscribe(v):void 0]));s&&this.logger.error(s),null==o||o(),f()}))));try{yield this.call("process","start",[d,s,n,r])}catch(s){throw a(),yield g,s}return{processID:d,kill:()=>e(this,void 0,void 0,(function*(){try{yield this.call("process","kill",[d])}finally{a(),yield g}})),sendStdin:s=>e(this,void 0,void 0,(function*(){yield this.call("process","stdin",[d,s])}))}}))}}))}},exports.api=t;
//# sourceMappingURL=index.js.map

@@ -18,4 +18,5 @@ export declare const terminalService = "terminal";

readonly createSession: (opts: {
onExit?: () => void;
onData: (data: string) => void;
onChildProcessesChange: ((cps: ChildProcess[]) => void) | undefined;
onChildProcessesChange?: (cps: ChildProcess[]) => void;
size: {

@@ -22,0 +23,0 @@ cols: number;

export declare function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T>;
export declare function assertRejected<T>(item: PromiseSettledResult<T>): item is PromiseRejectedResult;
export declare function formatSettledErrors<T>(settled: PromiseSettledResult<T>[]): string | undefined;
export declare function evaluateSettledPromises<T>(settled: PromiseSettledResult<T>[]): T[];
export declare function createDeferredPromise<T = void>(): {

@@ -6,0 +5,0 @@ resolve: (value: T) => void;

@@ -1,2 +0,2 @@

import{RpcWebSocketClient as s}from"rpc-websocket-client";import"cross-fetch/polyfill";import{Fetcher as i}from"openapi-typescript-fetch";function t(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const e=i.for();function o(s){return new Promise((i=>setTimeout(i,s)))}e.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[${this.id()}]`,...s)}error(...s){console.error(`[${this.id()} ERROR]`,...s)}}function r(s){return"fulfilled"===s.status}function l(s){if(!s.every((s=>"fulfilled"===s.status)))return s.reduce(((s,i,t)=>"rejected"===i.status?s+"\n"+`[${t}]: `+`${JSON.stringify(i)}`:s),"errors:\n")}function c(){let s,i;const t=new Promise(((t,e)=>{s=t,i=e}));return{resolve:s,reject:i,promise:t}}const d=e.path("/sessions").method("post").create({api_key:!0}),h=e.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var a;!function(s){s.Running="Running",s.Stopped="Stopped"}(a||(a={}));function u(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}class p extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i,e){return t(this,void 0,void 0,(function*(){return this.logger.log(`${s}_${i}`,e),this.rpc.call(`${s}_${i}`,e)}))}handleSubscriptions(...s){return t(this,void 0,void 0,(function*(){const i=yield Promise.allSettled(s);if(i.every((s=>"fulfilled"===s.status)))return i.map((s=>"fulfilled"===s.status?s.value:void 0));throw yield Promise.all(i.filter(r).map((s=>s.value?this.unsubscribe(s.value):void 0))),new Error(l(i))}))}unsubscribe(s){return t(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subID===s));i&&(yield this.call(i.service,"unsubscribe",[i.subID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.service}"`))}))}subscribe(s,i,e,...o){return t(this,void 0,void 0,(function*(){const t=yield this.call(s,"subscribe",[e,...o]);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s}_${e}${o.length>0?" with params ["+o.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(t)}`);return this.subscribers.push({subID:t,handler:i,service:s}),this.logger.log(`Subscribed to "${s}_${e}"${o.length>0?" with params ["+o.join(", ")+"] and":""} with id "${t}"`),t}))}getHostname(s){if(this.opts.__debug_hostname)return s&&"remote"===this.opts.__debug_devEnv?`${s}-${this.opts.__debug_hostname}`:s?`${this.opts.__debug_hostname}:${s}`:this.opts.__debug_hostname;if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return t(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return t(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");if(this.isOpen=!0,!this.opts.__debug_hostname)try{const s=yield d({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof d.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`${"local"===this.opts.__debug_devEnv?"ws":"wss"}://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,n,r=!1;const l=new Promise(((s,i)=>{e=()=>{r||(r=!0,s())},n=()=>{r||(r=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>t(this,void 0,void 0,(function*(){var t,e,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(e=(t=this.opts).onDisconnect)||void 0===e||e.call(t),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{this.subscribers=[],yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return t(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield h({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof h.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,o,n;return t(this,void 0,void 0,(function*(){yield s.open.call(this),yield this.handleSubscriptions((null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):void 0,(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):void 0,(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):void 0,(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):void 0),this.codeSnippet={run:(s,i={})=>t(this,void 0,void 0,(function*(){var t,e;const o=yield this.call("codeSnippet","run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>t(this,void 0,void 0,(function*(){var s,i;const t=yield this.call("codeSnippet","stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this.filesystem={listAllFiles:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem","listAllFiles",[s])})),removeFile:s=>t(this,void 0,void 0,(function*(){yield this.call("filesystem","removeFile",[s])})),writeFile:(s,i)=>t(this,void 0,void 0,(function*(){yield this.call("filesystem","writeFile",[s,i])})),readFile:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem","readFile",[s])}))},this.terminal={killProcess:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal","killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,terminalID:o=u(12)})=>t(this,void 0,void 0,(function*(){const[n,c]=yield this.handleSubscriptions(this.subscribe("terminal",s,"onData",o),i?this.subscribe("terminal",i,"onChildProcessesChange",o):void 0);try{yield this.call("terminal","start",[o,e.cols,e.rows])}catch(s){const i=l(yield Promise.allSettled([this.unsubscribe(n),c?this.unsubscribe(c):void 0]));throw i&&this.logger.error(i),s}return{terminalID:o,destroy:()=>t(this,void 0,void 0,(function*(){!function(s){if(s.some((s=>"rejected"===s.status)))throw new Error(l(s));s.filter(r).map((s=>s.value))}(yield Promise.allSettled([this.unsubscribe(n),c?this.unsubscribe(c):void 0,yield this.call("terminal","destroy",[o])]))})),sendData:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal","data",[o,s])})),resize:({cols:s,rows:i})=>t(this,void 0,void 0,(function*(){yield this.call("terminal","resize",[o,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:e,onExit:o,envVars:n={},rootdir:r="/",processID:d=u(12)})=>t(this,void 0,void 0,(function*(){const{promise:h,resolve:a}=c(),[u,p,g]=yield this.handleSubscriptions(this.subscribe("process",a,"onExit",d),i?this.subscribe("process",i,"onStdout",d):void 0,e?this.subscribe("process",e,"onStderr",d):void 0),{promise:v,resolve:f}=c();h.then((()=>t(this,void 0,void 0,(function*(){const s=l(yield Promise.allSettled([this.unsubscribe(u),p?this.unsubscribe(p):void 0,g?this.unsubscribe(g):void 0]));s&&this.logger.error(s),null==o||o(),f()}))));try{yield this.call("process","start",[d,s,n,r])}catch(s){throw a(),yield v,s}return{processID:d,kill:()=>t(this,void 0,void 0,(function*(){try{yield this.call("process","kill",[d])}finally{a(),yield v}})),sendStdin:s=>t(this,void 0,void 0,(function*(){yield this.call("process","stdin",[d,s])}))}}))}}))}}var g;!function(s){s.Stdout="Stdout",s.Stderr="Stderr"}(g||(g={}));export{a as CodeSnippetExecState,g as OutType,p as Session,e as api};
import{RpcWebSocketClient as s}from"rpc-websocket-client";import"cross-fetch/polyfill";import{Fetcher as i}from"openapi-typescript-fetch";function t(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const e=i.for();function o(s){return new Promise((i=>setTimeout(i,s)))}e.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[${this.id()}]`,...s)}error(...s){console.error(`[${this.id()} ERROR]`,...s)}}function r(s){return"fulfilled"===s.status}function l(s){if(!s.every((s=>"fulfilled"===s.status)))return s.reduce(((s,i,t)=>"rejected"===i.status?s+"\n"+`[${t}]: `+`${JSON.stringify(i)}`:s),"errors:\n")}function c(){let s,i;const t=new Promise(((t,e)=>{s=t,i=e}));return{resolve:s,reject:i,promise:t}}const d=e.path("/sessions").method("post").create({api_key:!0}),h=e.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var a;!function(s){s.Running="Running",s.Stopped="Stopped"}(a||(a={}));function u(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}class p extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i,e){return t(this,void 0,void 0,(function*(){return this.rpc.call(`${s}_${i}`,e)}))}handleSubscriptions(...s){return t(this,void 0,void 0,(function*(){const i=yield Promise.allSettled(s);if(i.every((s=>"fulfilled"===s.status)))return i.map((s=>"fulfilled"===s.status?s.value:void 0));throw yield Promise.all(i.filter(r).map((s=>s.value?this.unsubscribe(s.value):void 0))),new Error(l(i))}))}unsubscribe(s){return t(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subID===s));i&&(yield this.call(i.service,"unsubscribe",[i.subID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.service}"`))}))}subscribe(s,i,e,...o){return t(this,void 0,void 0,(function*(){const t=yield this.call(s,"subscribe",[e,...o]);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s}_${e}${o.length>0?" with params ["+o.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(t)}`);return this.subscribers.push({subID:t,handler:i,service:s}),this.logger.log(`Subscribed to "${s}_${e}"${o.length>0?" with params ["+o.join(", ")+"] and":""} with id "${t}"`),t}))}getHostname(s){if(this.opts.__debug_hostname)return s&&"remote"===this.opts.__debug_devEnv?`${s}-${this.opts.__debug_hostname}`:s?`${this.opts.__debug_hostname}:${s}`:this.opts.__debug_hostname;if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return t(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return t(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");if(this.isOpen=!0,!this.opts.__debug_hostname)try{const s=yield d({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof d.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`${"local"===this.opts.__debug_devEnv?"ws":"wss"}://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,n,r=!1;const l=new Promise(((s,i)=>{e=()=>{r||(r=!0,s())},n=()=>{r||(r=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>t(this,void 0,void 0,(function*(){var t,e,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(e=(t=this.opts).onDisconnect)||void 0===e||e.call(t),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{this.subscribers=[],yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return t(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield h({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof h.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,o,n;return t(this,void 0,void 0,(function*(){yield s.open.call(this),yield this.handleSubscriptions((null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):void 0,(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):void 0,(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):void 0,(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):void 0),this.codeSnippet={run:(s,i={})=>t(this,void 0,void 0,(function*(){var t,e;const o=yield this.call("codeSnippet","run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>t(this,void 0,void 0,(function*(){var s,i;const t=yield this.call("codeSnippet","stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this.filesystem={listAllFiles:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem","listAllFiles",[s])})),removeFile:s=>t(this,void 0,void 0,(function*(){yield this.call("filesystem","removeFile",[s])})),writeFile:(s,i)=>t(this,void 0,void 0,(function*(){yield this.call("filesystem","writeFile",[s,i])})),readFile:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem","readFile",[s])}))},this.terminal={killProcess:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal","killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,onExit:o,terminalID:n=u(12)})=>t(this,void 0,void 0,(function*(){const{promise:r,resolve:d}=c(),[h,a,u]=yield this.handleSubscriptions(this.subscribe("terminal",s,"onData",n),this.subscribe("terminal",d,"onExit",n),i?this.subscribe("terminal",i,"onChildProcessesChange",n):void 0),{promise:p,resolve:v}=c();r.then((()=>t(this,void 0,void 0,(function*(){const s=l(yield Promise.allSettled([this.unsubscribe(a),this.unsubscribe(h),u?this.unsubscribe(u):void 0]));s&&this.logger.error(s),null==o||o(),v()}))));try{yield this.call("terminal","start",[n,e.cols,e.rows])}catch(s){throw d(),yield p,s}return{terminalID:n,destroy:()=>t(this,void 0,void 0,(function*(){try{yield this.call("terminal","destroy",[n])}finally{d(),yield p}})),sendData:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal","data",[n,s])})),resize:({cols:s,rows:i})=>t(this,void 0,void 0,(function*(){yield this.call("terminal","resize",[n,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:e,onExit:o,envVars:n={},rootdir:r="/",processID:d=u(12)})=>t(this,void 0,void 0,(function*(){const{promise:h,resolve:a}=c(),[u,p,v]=yield this.handleSubscriptions(this.subscribe("process",a,"onExit",d),i?this.subscribe("process",i,"onStdout",d):void 0,e?this.subscribe("process",e,"onStderr",d):void 0),{promise:g,resolve:f}=c();h.then((()=>t(this,void 0,void 0,(function*(){const s=l(yield Promise.allSettled([this.unsubscribe(u),p?this.unsubscribe(p):void 0,v?this.unsubscribe(v):void 0]));s&&this.logger.error(s),null==o||o(),f()}))));try{yield this.call("process","start",[d,s,n,r])}catch(s){throw a(),yield g,s}return{processID:d,kill:()=>t(this,void 0,void 0,(function*(){try{yield this.call("process","kill",[d])}finally{a(),yield g}})),sendStdin:s=>t(this,void 0,void 0,(function*(){yield this.call("process","stdin",[d,s])}))}}))}}))}}var v;!function(s){s.Stdout="Stdout",s.Stderr="Stderr"}(v||(v={}));export{a as CodeSnippetExecState,v as OutType,p as Session,e as api};
//# sourceMappingURL=index.js.map

@@ -18,4 +18,5 @@ export declare const terminalService = "terminal";

readonly createSession: (opts: {
onExit?: () => void;
onData: (data: string) => void;
onChildProcessesChange: ((cps: ChildProcess[]) => void) | undefined;
onChildProcessesChange?: (cps: ChildProcess[]) => void;
size: {

@@ -22,0 +23,0 @@ cols: number;

export declare function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T>;
export declare function assertRejected<T>(item: PromiseSettledResult<T>): item is PromiseRejectedResult;
export declare function formatSettledErrors<T>(settled: PromiseSettledResult<T>[]): string | undefined;
export declare function evaluateSettledPromises<T>(settled: PromiseSettledResult<T>[]): T[];
export declare function createDeferredPromise<T = void>(): {

@@ -6,0 +5,0 @@ resolve: (value: T) => void;

@@ -1,2 +0,2 @@

!function(s,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("rpc-websocket-client"),require("cross-fetch/polyfill"),require("openapi-typescript-fetch")):"function"==typeof define&&define.amd?define(["exports","rpc-websocket-client","cross-fetch/polyfill","openapi-typescript-fetch"],i):i((s="undefined"!=typeof globalThis?globalThis:s||self)["@devbookhq/sdk"]={},s.rpcWebsocketClient,null,s.openapiTypescriptFetch)}(this,(function(s,i,t,e){"use strict";function o(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const n=e.Fetcher.for();function r(s){return new Promise((i=>setTimeout(i,s)))}n.configure({baseUrl:"https://ondevbook.com"});class l{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[${this.id()}]`,...s)}error(...s){console.error(`[${this.id()} ERROR]`,...s)}}function c(s){return"fulfilled"===s.status}function d(s){if(!s.every((s=>"fulfilled"===s.status)))return s.reduce(((s,i,t)=>"rejected"===i.status?s+"\n"+`[${t}]: `+`${JSON.stringify(i)}`:s),"errors:\n")}function h(){let s,i;const t=new Promise(((t,e)=>{s=t,i=e}));return{resolve:s,reject:i,promise:t}}const u=n.path("/sessions").method("post").create({api_key:!0}),a=n.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});const p="codeSnippet";var g;s.CodeSnippetExecState=void 0,(g=s.CodeSnippetExecState||(s.CodeSnippetExecState={})).Running="Running",g.Stopped="Stopped";const v="terminal",f="filesystem",b="process";function y(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}var S;s.OutType=void 0,(S=s.OutType||(s.OutType={})).Stdout="Stdout",S.Stderr="Stderr",s.Session=class extends class{constructor(s){this.opts=s,this.isOpen=!1,this.rpc=new i.RpcWebSocketClient,this.subscribers=[],this.logger=new l("Session",s.debug),this.logger.log(`Session for code snippet "${s.id}" initialized`)}call(s,i,t){return o(this,void 0,void 0,(function*(){return this.logger.log(`${s}_${i}`,t),this.rpc.call(`${s}_${i}`,t)}))}handleSubscriptions(...s){return o(this,void 0,void 0,(function*(){const i=yield Promise.allSettled(s);if(i.every((s=>"fulfilled"===s.status)))return i.map((s=>"fulfilled"===s.status?s.value:void 0));throw yield Promise.all(i.filter(c).map((s=>s.value?this.unsubscribe(s.value):void 0))),new Error(d(i))}))}unsubscribe(s){return o(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subID===s));i&&(yield this.call(i.service,"unsubscribe",[i.subID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.service}"`))}))}subscribe(s,i,t,...e){return o(this,void 0,void 0,(function*(){const o=yield this.call(s,"subscribe",[t,...e]);if("string"!=typeof o)throw new Error(`Cannot subscribe to ${s}_${t}${e.length>0?" with params ["+e.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(o)}`);return this.subscribers.push({subID:o,handler:i,service:s}),this.logger.log(`Subscribed to "${s}_${t}"${e.length>0?" with params ["+e.join(", ")+"] and":""} with id "${o}"`),o}))}getHostname(s){if(this.opts.__debug_hostname)return s&&"remote"===this.opts.__debug_devEnv?`${s}-${this.opts.__debug_hostname}`:s?`${this.opts.__debug_hostname}:${s}`:this.opts.__debug_hostname;if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,t;return o(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(t=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===t||t.call(i),this.logger.log("Disconected from the session")}}))}open(){return o(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");if(this.isOpen=!0,!this.opts.__debug_hostname)try{const s=yield u({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof u.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`${"local"===this.opts.__debug_devEnv?"ws":"wss"}://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let t,e,n=!1;const l=new Promise(((s,i)=>{t=()=>{n||(n=!0,s())},e=()=>{n||(n=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==t||t()})),this.rpc.onClose((s=>o(this,void 0,void 0,(function*(){var t,o,n,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(o=(t=this.opts).onDisconnect)||void 0===o||o.call(t),yield r(100),this.logger.log("Reconnecting to session:",this.session);try{this.subscribers=[],yield this.rpc.connect(i),null===(l=(n=this.opts).onReconnect)||void 0===l||l.call(n),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==e||e()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return o(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield r(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield a({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof a.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,t,e,n;return o(this,void 0,void 0,(function*(){yield s.open.call(this),yield this.handleSubscriptions((null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe(p,this.codeSnippetOpts.onStateChange,"state"):void 0,(null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStderr)?this.subscribe(p,this.codeSnippetOpts.onStderr,"stderr"):void 0,(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStdout)?this.subscribe(p,this.codeSnippetOpts.onStdout,"stdout"):void 0,(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe(p,this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):void 0),this.codeSnippet={run:(s,i={})=>o(this,void 0,void 0,(function*(){var t,e;const o=yield this.call(p,"run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>o(this,void 0,void 0,(function*(){var s,i;const t=yield this.call(p,"stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this.filesystem={listAllFiles:s=>o(this,void 0,void 0,(function*(){return yield this.call(f,"listAllFiles",[s])})),removeFile:s=>o(this,void 0,void 0,(function*(){yield this.call(f,"removeFile",[s])})),writeFile:(s,i)=>o(this,void 0,void 0,(function*(){yield this.call(f,"writeFile",[s,i])})),readFile:s=>o(this,void 0,void 0,(function*(){return yield this.call(f,"readFile",[s])}))},this.terminal={killProcess:s=>o(this,void 0,void 0,(function*(){yield this.call(v,"killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:t,terminalID:e=y(12)})=>o(this,void 0,void 0,(function*(){const[n,r]=yield this.handleSubscriptions(this.subscribe(v,s,"onData",e),i?this.subscribe(v,i,"onChildProcessesChange",e):void 0);try{yield this.call(v,"start",[e,t.cols,t.rows])}catch(s){const i=d(yield Promise.allSettled([this.unsubscribe(n),r?this.unsubscribe(r):void 0]));throw i&&this.logger.error(i),s}return{terminalID:e,destroy:()=>o(this,void 0,void 0,(function*(){!function(s){if(s.some((s=>"rejected"===s.status)))throw new Error(d(s));s.filter(c).map((s=>s.value))}(yield Promise.allSettled([this.unsubscribe(n),r?this.unsubscribe(r):void 0,yield this.call(v,"destroy",[e])]))})),sendData:s=>o(this,void 0,void 0,(function*(){yield this.call(v,"data",[e,s])})),resize:({cols:s,rows:i})=>o(this,void 0,void 0,(function*(){yield this.call(v,"resize",[e,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:t,onExit:e,envVars:n={},rootdir:r="/",processID:l=y(12)})=>o(this,void 0,void 0,(function*(){const{promise:c,resolve:u}=h(),[a,p,g]=yield this.handleSubscriptions(this.subscribe(b,u,"onExit",l),i?this.subscribe(b,i,"onStdout",l):void 0,t?this.subscribe(b,t,"onStderr",l):void 0),{promise:v,resolve:f}=h();c.then((()=>o(this,void 0,void 0,(function*(){const s=d(yield Promise.allSettled([this.unsubscribe(a),p?this.unsubscribe(p):void 0,g?this.unsubscribe(g):void 0]));s&&this.logger.error(s),null==e||e(),f()}))));try{yield this.call(b,"start",[l,s,n,r])}catch(s){throw u(),yield v,s}return{processID:l,kill:()=>o(this,void 0,void 0,(function*(){try{yield this.call(b,"kill",[l])}finally{u(),yield v}})),sendStdin:s=>o(this,void 0,void 0,(function*(){yield this.call(b,"stdin",[l,s])}))}}))}}))}},s.api=n,Object.defineProperty(s,"__esModule",{value:!0})}));
!function(s,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("rpc-websocket-client"),require("cross-fetch/polyfill"),require("openapi-typescript-fetch")):"function"==typeof define&&define.amd?define(["exports","rpc-websocket-client","cross-fetch/polyfill","openapi-typescript-fetch"],i):i((s="undefined"!=typeof globalThis?globalThis:s||self)["@devbookhq/sdk"]={},s.rpcWebsocketClient,null,s.openapiTypescriptFetch)}(this,(function(s,i,t,e){"use strict";function o(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const n=e.Fetcher.for();function r(s){return new Promise((i=>setTimeout(i,s)))}n.configure({baseUrl:"https://ondevbook.com"});class l{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[${this.id()}]`,...s)}error(...s){console.error(`[${this.id()} ERROR]`,...s)}}function c(s){return"fulfilled"===s.status}function d(s){if(!s.every((s=>"fulfilled"===s.status)))return s.reduce(((s,i,t)=>"rejected"===i.status?s+"\n"+`[${t}]: `+`${JSON.stringify(i)}`:s),"errors:\n")}function h(){let s,i;const t=new Promise(((t,e)=>{s=t,i=e}));return{resolve:s,reject:i,promise:t}}const u=n.path("/sessions").method("post").create({api_key:!0}),a=n.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});const p="codeSnippet";var v;s.CodeSnippetExecState=void 0,(v=s.CodeSnippetExecState||(s.CodeSnippetExecState={})).Running="Running",v.Stopped="Stopped";const g="terminal",f="filesystem",b="process";function y(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}var S;s.OutType=void 0,(S=s.OutType||(s.OutType={})).Stdout="Stdout",S.Stderr="Stderr",s.Session=class extends class{constructor(s){this.opts=s,this.isOpen=!1,this.rpc=new i.RpcWebSocketClient,this.subscribers=[],this.logger=new l("Session",s.debug),this.logger.log(`Session for code snippet "${s.id}" initialized`)}call(s,i,t){return o(this,void 0,void 0,(function*(){return this.rpc.call(`${s}_${i}`,t)}))}handleSubscriptions(...s){return o(this,void 0,void 0,(function*(){const i=yield Promise.allSettled(s);if(i.every((s=>"fulfilled"===s.status)))return i.map((s=>"fulfilled"===s.status?s.value:void 0));throw yield Promise.all(i.filter(c).map((s=>s.value?this.unsubscribe(s.value):void 0))),new Error(d(i))}))}unsubscribe(s){return o(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subID===s));i&&(yield this.call(i.service,"unsubscribe",[i.subID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.service}"`))}))}subscribe(s,i,t,...e){return o(this,void 0,void 0,(function*(){const o=yield this.call(s,"subscribe",[t,...e]);if("string"!=typeof o)throw new Error(`Cannot subscribe to ${s}_${t}${e.length>0?" with params ["+e.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(o)}`);return this.subscribers.push({subID:o,handler:i,service:s}),this.logger.log(`Subscribed to "${s}_${t}"${e.length>0?" with params ["+e.join(", ")+"] and":""} with id "${o}"`),o}))}getHostname(s){if(this.opts.__debug_hostname)return s&&"remote"===this.opts.__debug_devEnv?`${s}-${this.opts.__debug_hostname}`:s?`${this.opts.__debug_hostname}:${s}`:this.opts.__debug_hostname;if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,t;return o(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(t=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===t||t.call(i),this.logger.log("Disconected from the session")}}))}open(){return o(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");if(this.isOpen=!0,!this.opts.__debug_hostname)try{const s=yield u({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof u.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`${"local"===this.opts.__debug_devEnv?"ws":"wss"}://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let t,e,n=!1;const l=new Promise(((s,i)=>{t=()=>{n||(n=!0,s())},e=()=>{n||(n=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==t||t()})),this.rpc.onClose((s=>o(this,void 0,void 0,(function*(){var t,o,n,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(o=(t=this.opts).onDisconnect)||void 0===o||o.call(t),yield r(100),this.logger.log("Reconnecting to session:",this.session);try{this.subscribers=[],yield this.rpc.connect(i),null===(l=(n=this.opts).onReconnect)||void 0===l||l.call(n),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==e||e()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return o(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield r(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield a({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof a.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,t,e,n;return o(this,void 0,void 0,(function*(){yield s.open.call(this),yield this.handleSubscriptions((null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe(p,this.codeSnippetOpts.onStateChange,"state"):void 0,(null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStderr)?this.subscribe(p,this.codeSnippetOpts.onStderr,"stderr"):void 0,(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStdout)?this.subscribe(p,this.codeSnippetOpts.onStdout,"stdout"):void 0,(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe(p,this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):void 0),this.codeSnippet={run:(s,i={})=>o(this,void 0,void 0,(function*(){var t,e;const o=yield this.call(p,"run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>o(this,void 0,void 0,(function*(){var s,i;const t=yield this.call(p,"stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this.filesystem={listAllFiles:s=>o(this,void 0,void 0,(function*(){return yield this.call(f,"listAllFiles",[s])})),removeFile:s=>o(this,void 0,void 0,(function*(){yield this.call(f,"removeFile",[s])})),writeFile:(s,i)=>o(this,void 0,void 0,(function*(){yield this.call(f,"writeFile",[s,i])})),readFile:s=>o(this,void 0,void 0,(function*(){return yield this.call(f,"readFile",[s])}))},this.terminal={killProcess:s=>o(this,void 0,void 0,(function*(){yield this.call(g,"killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:t,onExit:e,terminalID:n=y(12)})=>o(this,void 0,void 0,(function*(){const{promise:r,resolve:l}=h(),[c,u,a]=yield this.handleSubscriptions(this.subscribe(g,s,"onData",n),this.subscribe(g,l,"onExit",n),i?this.subscribe(g,i,"onChildProcessesChange",n):void 0),{promise:p,resolve:v}=h();r.then((()=>o(this,void 0,void 0,(function*(){const s=d(yield Promise.allSettled([this.unsubscribe(u),this.unsubscribe(c),a?this.unsubscribe(a):void 0]));s&&this.logger.error(s),null==e||e(),v()}))));try{yield this.call(g,"start",[n,t.cols,t.rows])}catch(s){throw l(),yield p,s}return{terminalID:n,destroy:()=>o(this,void 0,void 0,(function*(){try{yield this.call(g,"destroy",[n])}finally{l(),yield p}})),sendData:s=>o(this,void 0,void 0,(function*(){yield this.call(g,"data",[n,s])})),resize:({cols:s,rows:i})=>o(this,void 0,void 0,(function*(){yield this.call(g,"resize",[n,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:t,onExit:e,envVars:n={},rootdir:r="/",processID:l=y(12)})=>o(this,void 0,void 0,(function*(){const{promise:c,resolve:u}=h(),[a,p,v]=yield this.handleSubscriptions(this.subscribe(b,u,"onExit",l),i?this.subscribe(b,i,"onStdout",l):void 0,t?this.subscribe(b,t,"onStderr",l):void 0),{promise:g,resolve:f}=h();c.then((()=>o(this,void 0,void 0,(function*(){const s=d(yield Promise.allSettled([this.unsubscribe(a),p?this.unsubscribe(p):void 0,v?this.unsubscribe(v):void 0]));s&&this.logger.error(s),null==e||e(),f()}))));try{yield this.call(b,"start",[l,s,n,r])}catch(s){throw u(),yield g,s}return{processID:l,kill:()=>o(this,void 0,void 0,(function*(){try{yield this.call(b,"kill",[l])}finally{u(),yield g}})),sendStdin:s=>o(this,void 0,void 0,(function*(){yield this.call(b,"stdin",[l,s])}))}}))}}))}},s.api=n,Object.defineProperty(s,"__esModule",{value:!0})}));
//# sourceMappingURL=index.js.map

@@ -18,4 +18,5 @@ export declare const terminalService = "terminal";

readonly createSession: (opts: {
onExit?: () => void;
onData: (data: string) => void;
onChildProcessesChange: ((cps: ChildProcess[]) => void) | undefined;
onChildProcessesChange?: (cps: ChildProcess[]) => void;
size: {

@@ -22,0 +23,0 @@ cols: number;

export declare function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T>;
export declare function assertRejected<T>(item: PromiseSettledResult<T>): item is PromiseRejectedResult;
export declare function formatSettledErrors<T>(settled: PromiseSettledResult<T>[]): string | undefined;
export declare function evaluateSettledPromises<T>(settled: PromiseSettledResult<T>[]): T[];
export declare function createDeferredPromise<T = void>(): {

@@ -6,0 +5,0 @@ resolve: (value: T) => void;

{
"name": "@devbookhq/sdk",
"version": "2.5.0",
"version": "2.5.1",
"description": "Devbook allows visitors of your docs to interact with and execute any code snippet or shell command in a private VM",

@@ -5,0 +5,0 @@ "homepage": "https://usedevbook.com",

@@ -29,3 +29,2 @@ import SessionConnection, {

createDeferredPromise,
evaluateSettledPromises,
formatSettledErrors,

@@ -58,3 +57,2 @@ } from '../utils/promise'

async open() {

@@ -117,16 +115,28 @@ await super.open()

size,
onExit,
terminalID = id(12),
}) => {
const {
promise: terminalExited,
resolve: triggerExit,
} = createDeferredPromise()
const [
onDataSubID,
onExitSubID,
onChildProcessesChangeSubID,
] = await this.handleSubscriptions(
this.subscribe(terminalService, onData, 'onData', terminalID),
this.subscribe(terminalService, triggerExit, 'onExit', terminalID),
onChildProcessesChange ? this.subscribe(terminalService, onChildProcessesChange, 'onChildProcessesChange', terminalID) : undefined,
)
try {
await this.call(terminalService, 'start', [terminalID, size.cols, size.rows])
} catch (err) {
const {
promise: unsubscribing,
resolve: handleFinishUnsubscribing,
} = createDeferredPromise()
terminalExited.then(async () => {
const results = await Promise.allSettled([
this.unsubscribe(onExitSubID),
this.unsubscribe(onDataSubID),

@@ -141,2 +151,12 @@ onChildProcessesChangeSubID ? this.unsubscribe(onChildProcessesChangeSubID) : undefined,

onExit?.()
handleFinishUnsubscribing()
})
try {
await this.call(terminalService, 'start', [terminalID, size.cols, size.rows])
} catch (err) {
triggerExit()
await unsubscribing
throw err

@@ -148,9 +168,8 @@ }

destroy: async () => {
const results = await Promise.allSettled([
this.unsubscribe(onDataSubID),
onChildProcessesChangeSubID ? this.unsubscribe(onChildProcessesChangeSubID) : undefined,
try {
await this.call(terminalService, 'destroy', [terminalID])
])
evaluateSettledPromises(results)
} finally {
triggerExit()
await unsubscribing
}
},

@@ -157,0 +176,0 @@ sendData: async (data) => {

@@ -75,3 +75,2 @@ import {

protected async call(service: Service, method: string, params?: any[]) {
this.logger.log(`${service}_${method}`, params)
return this.rpc.call(`${service}_${method}`, params)

@@ -78,0 +77,0 @@ }

@@ -18,4 +18,5 @@ export const terminalService = 'terminal'

readonly createSession: (opts: {
onExit?: () => void,
onData: (data: string) => void,
onChildProcessesChange: ((cps: ChildProcess[]) => void) | undefined,
onChildProcessesChange?: (cps: ChildProcess[]) => void,
size: { cols: number, rows: number },

@@ -22,0 +23,0 @@ terminalID?: string,

@@ -21,10 +21,2 @@ export function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T> {

export function evaluateSettledPromises<T>(settled: PromiseSettledResult<T>[]) {
if (settled.some(s => s.status === 'rejected')) {
throw new Error(formatSettledErrors(settled))
}
return settled.filter(assertFulfilled).map(s => s.value)
}
export function createDeferredPromise<T = void>() {

@@ -31,0 +23,0 @@ let resolve: ((value: T) => void)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc