Skip to content

Commit

Permalink
JS version
Browse files Browse the repository at this point in the history
  • Loading branch information
mlejva committed Oct 12, 2023
1 parent df594dc commit 6dd6123
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 13 deletions.
3 changes: 3 additions & 0 deletions packages/js-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,11 @@
"typescript"
],
"dependencies": {
"@types/node-fetch": "^2.6.5",
"bufferutil": "^4.0.7",
"cross-fetch": "^3.1.5",
"form-data": "^4.0.0",
"node-fetch": "^2.7.0",
"normalize-path": "^3.0.0",
"openapi-typescript-fetch": "^1.1.3",
"platform": "^1.3.6",
Expand Down
2 changes: 1 addition & 1 deletion packages/js-sdk/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ export const WS_RECONNECT_INTERVAL = 600 // 600ms
export const TIMEOUT = 60_000 // 60s

export const SESSION_DOMAIN = 'ondevbook.com'
export const WS_PORT = 49982
export const ENVD_PORT = 49982
export const WS_ROUTE = '/ws'
55 changes: 55 additions & 0 deletions packages/js-sdk/src/session/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import normalizePath from 'normalize-path'
import FormData from 'form-data'
import fetch from 'node-fetch'

import {
ENVD_PORT,
} from '../constants'
import { components } from '../api'
import { id } from '../utils/id'
import { createDeferredPromise, formatSettledErrors, withTimeout } from '../utils/promise'
Expand Down Expand Up @@ -354,6 +359,19 @@ export class Session extends SessionConnection {
resolvePath(path, this.cwd, this.logger)
}

/**
* URL that can be used to download or upload file to the session via a multipart/form-data POST request.
* This is useful if you're uploading files directly from the browser.
* The file will be uploaded to the user's home directory with the same name.
* If a file with the same name already exists, it will be overwritten.
*/
public get fileURL() {
const hostname = this.getHostname(this.opts.__debug_port)
console.log('HOSTNAME', hostname)
const protocol = this.opts.__debug_devEnv === 'local' ? 'http' : 'https'
return `${protocol}://${ENVD_PORT}-${hostname}/file`
}

static async create(opts: SessionOpts) {
return new Session(opts).open({ timeout: opts?.timeout }).then(async session => {
if (opts.cwd) {
Expand All @@ -380,4 +398,41 @@ export class Session extends SessionConnection {

return this
}

/**
* Uploads a file to the session.
* The file will be uploaded to the user's home directory with the same name.
* If a file with the same name already exists, it will be overwritten.
*
* **Use this method only in the non-browser environment.
* In the browser environment, use the `uploadURL()` method and upload the file driectly via POST multipart/form-data**
*
*/
async uploadFile(file: Buffer | Blob, filename: string, contentType?: string) {
const formData = new FormData()
formData.append('file', file, {
filename,
contentType: contentType || 'application/octet-stream',
})

console.log(this.fileURL)
const response = await fetch(this.fileURL, {
method: 'POST',
body: formData,
})

if (!response.ok) {
const text = await response.text()
throw new Error(`Failed to upload file: ${text}`)
}
}

async downloadFile(remotePath: string) {
const response = await fetch(`${this.fileURL}?path=${remotePath}`)
if (!response.ok) {
const text = await response.text()
throw new Error(`Failed to download file '${remotePath}': ${text}`)
}
return response
}
}
4 changes: 2 additions & 2 deletions packages/js-sdk/src/session/sessionConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import api, { components } from '../api'
import {
SESSION_DOMAIN,
SESSION_REFRESH_PERIOD,
WS_PORT,
ENVD_PORT,
WS_RECONNECT_INTERVAL,
WS_ROUTE,
} from '../constants'
Expand Down Expand Up @@ -208,7 +208,7 @@ export class SessionConnection {
}
}

const hostname = this.getHostname(this.opts.__debug_port || WS_PORT)
const hostname = this.getHostname(this.opts.__debug_port || ENVD_PORT)

if (!hostname) {
throw new Error("Cannot get session's hostname")
Expand Down
26 changes: 25 additions & 1 deletion packages/js-sdk/test/run.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
import { runCode } from '../dist/cjs/index.js'
import fs from 'fs'
import { Session, runCode } from '../dist/cjs/index.js'

async function localSession() {
return await Session.create({
id: 'Nodejs',
apiKey: process.env.E2B_API_KEY,
// __debug_hostname: 'localhost',
// __debug_port: 49982,
// __debug_devEnv: 'local',
})
}

async function main() {
const session = await localSession()

const f = fs.readFileSync('./package.json')
await session.uploadFile(f, 'package.json')

const content = await session.filesystem.list('/home/user')
content.forEach(c => console.log(c.name))
process.exit()

const response = await session.downloadFile('/.dbkenv')
const text = await response.text()
console.log('text', text)
process.exit()
// const session = await Session.create({
// id: 'Nodejs',
// apiKey: process.env.E2B_API_KEY,
Expand Down
25 changes: 16 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 6dd6123

Please sign in to comment.