@e2b/code-interpreter 2.0.0-rc.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -349,19 +349,19 @@ interface RunCodeOpts {
349
349
  /**
350
350
  * Callback for handling stdout messages.
351
351
  */
352
- onStdout?: (output: OutputMessage) => (Promise<any> | any);
352
+ onStdout?: (output: OutputMessage) => Promise<any> | any;
353
353
  /**
354
354
  * Callback for handling stderr messages.
355
355
  */
356
- onStderr?: (output: OutputMessage) => (Promise<any> | any);
356
+ onStderr?: (output: OutputMessage) => Promise<any> | any;
357
357
  /**
358
358
  * Callback for handling the final execution result.
359
359
  */
360
- onResult?: (data: Result) => (Promise<any> | any);
360
+ onResult?: (data: Result) => Promise<any> | any;
361
361
  /**
362
362
  * Callback for handling the `ExecutionError` object.
363
363
  */
364
- onError?: (error: ExecutionError) => (Promise<any> | any);
364
+ onError?: (error: ExecutionError) => Promise<any> | any;
365
365
  /**
366
366
  * Custom environment variables for code execution.
367
367
  *
package/dist/index.d.ts CHANGED
@@ -349,19 +349,19 @@ interface RunCodeOpts {
349
349
  /**
350
350
  * Callback for handling stdout messages.
351
351
  */
352
- onStdout?: (output: OutputMessage) => (Promise<any> | any);
352
+ onStdout?: (output: OutputMessage) => Promise<any> | any;
353
353
  /**
354
354
  * Callback for handling stderr messages.
355
355
  */
356
- onStderr?: (output: OutputMessage) => (Promise<any> | any);
356
+ onStderr?: (output: OutputMessage) => Promise<any> | any;
357
357
  /**
358
358
  * Callback for handling the final execution result.
359
359
  */
360
- onResult?: (data: Result) => (Promise<any> | any);
360
+ onResult?: (data: Result) => Promise<any> | any;
361
361
  /**
362
362
  * Callback for handling the `ExecutionError` object.
363
363
  */
364
- onError?: (error: ExecutionError) => (Promise<any> | any);
364
+ onError?: (error: ExecutionError) => Promise<any> | any;
365
365
  /**
366
366
  * Custom environment variables for code execution.
367
367
  *
package/dist/index.js CHANGED
@@ -317,19 +317,25 @@ var Sandbox = class extends import_e2b3.Sandbox {
317
317
  async runCode(code, opts) {
318
318
  var _a, _b, _c;
319
319
  if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
320
- throw new import_e2b3.InvalidArgumentError("You can provide context or language, but not both at the same time.");
320
+ throw new import_e2b3.InvalidArgumentError(
321
+ "You can provide context or language, but not both at the same time."
322
+ );
321
323
  }
322
324
  const controller = new AbortController();
323
325
  const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
324
326
  const reqTimer = requestTimeout ? setTimeout(() => {
325
327
  controller.abort();
326
328
  }, requestTimeout) : void 0;
329
+ const headers = {
330
+ "Content-Type": "application/json"
331
+ };
332
+ if (this.envdAccessToken) {
333
+ headers["X-Access-Token"] = this.envdAccessToken;
334
+ }
327
335
  try {
328
336
  const res = await fetch(`${this.jupyterUrl}/execute`, {
329
337
  method: "POST",
330
- headers: {
331
- "Content-Type": "application/json"
332
- },
338
+ headers,
333
339
  body: JSON.stringify({
334
340
  code,
335
341
  context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
@@ -344,7 +350,9 @@ var Sandbox = class extends import_e2b3.Sandbox {
344
350
  throw error2;
345
351
  }
346
352
  if (!res.body) {
347
- throw new Error(`Not response body: ${res.statusText} ${await (res == null ? void 0 : res.text())}`);
353
+ throw new Error(
354
+ `Not response body: ${res.statusText} ${await (res == null ? void 0 : res.text())}`
355
+ );
348
356
  }
349
357
  clearTimeout(reqTimer);
350
358
  const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
@@ -356,7 +364,14 @@ var Sandbox = class extends import_e2b3.Sandbox {
356
364
  try {
357
365
  for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
358
366
  const chunk = temp.value;
359
- await parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError);
367
+ await parseOutput(
368
+ execution,
369
+ chunk,
370
+ opts == null ? void 0 : opts.onStdout,
371
+ opts == null ? void 0 : opts.onStderr,
372
+ opts == null ? void 0 : opts.onResult,
373
+ opts == null ? void 0 : opts.onError
374
+ );
360
375
  }
361
376
  } catch (temp) {
362
377
  error = [temp];
@@ -382,16 +397,16 @@ var Sandbox = class extends import_e2b3.Sandbox {
382
397
  * Creates a new context to run code in.
383
398
  *
384
399
  * @param opts options for creating the context.
385
- *
400
+ *
386
401
  * @returns context object.
387
402
  */
388
403
  async createCodeContext(opts) {
389
404
  try {
390
405
  const res = await fetch(`${this.jupyterUrl}/contexts`, {
391
406
  method: "POST",
392
- headers: {
407
+ headers: __spreadValues({
393
408
  "Content-Type": "application/json"
394
- },
409
+ }, this.connectionConfig.headers),
395
410
  body: JSON.stringify({
396
411
  language: opts == null ? void 0 : opts.language,
397
412
  cwd: opts == null ? void 0 : opts.cwd
@@ -409,7 +424,9 @@ var Sandbox = class extends import_e2b3.Sandbox {
409
424
  }
410
425
  }
411
426
  get jupyterUrl() {
412
- return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`;
427
+ return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(
428
+ JUPYTER_PORT
429
+ )}`;
413
430
  }
414
431
  };
415
432
  Sandbox.defaultTemplate = "code-interpreter-v1";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => (Promise<any> | any),\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => (Promise<any> | any),\n /**\n * Custom environment variables for code execution.\n * \n * @default {}\n */\n envs?: Record<string, string>,\n /**\n * Timeout for the code execution in **milliseconds**.\n * \n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n * \n * @default /home/user\n */\n cwd?: string,\n /**\n * Language for the context.\n * \n * @default python\n */\n language?: string,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: 'python',\n },\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: string,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n * \n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string,\n context?: Context,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n * \n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,gBAAd;;;ACAA,IAAAA,cAA6D;;;ACA7D,iBAA0D;AAG1D,eAAsB,aAAa,KAAe;AAChD,MAAI,IAAI,IAAI;AACV;AAAA,EACF;AAEA,U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;AACd,cAAM,4BAA4BA,MAAK;AAAA,MACzC,UAAE;AACA,qBAAa,SAAS;AAAA,MACxB;AAEA,aAAO;AAAA,IACT,SAASA,QAAO;AACd,YAAM,0BAA0BA,MAAK;AAAA,IACvC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,kBAAkB,MAAgD;AACtE,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,GAAG,KAAK,UAAU,aAAa;AAAA,QACrD,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAClB;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,UAAU,6BAAM;AAAA,UAChB,KAAK,6BAAM;AAAA,QACb,CAAC;AAAA,QACD,WAAW;AAAA,QACX,QAAQ,KAAK,iBAAiB,UAAU,6BAAM,gBAAgB;AAAA,MAChE,CAAC;AAED,YAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,UAAI,OAAO;AACT,cAAM;AAAA,MACR;AAEA,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,SAAS,OAAO;AACd,YAAM,0BAA0B,KAAK;AAAA,IACvC;AAAA,EACF;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAO,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,EAC1F;AACF;AArLa,QACwB,kBAA0B;;;AD/E/D,IAAO,cAAQ;","names":["import_e2b","import_e2b","BaseSandbox","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport {\n Result,\n Execution,\n OutputMessage,\n parseOutput,\n extractError,\n ExecutionError,\n} from './messaging'\nimport {\n formatExecutionTimeoutError,\n formatRequestTimeoutError,\n readLines,\n} from './utils'\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => Promise<any> | any\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => Promise<any> | any\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => Promise<any> | any\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => Promise<any> | any\n /**\n * Custom environment variables for code execution.\n *\n * @default {}\n */\n envs?: Record<string, string>\n /**\n * Timeout for the code execution in **milliseconds**.\n *\n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number\n /**\n * Timeout for the request in **milliseconds**.\n *\n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n *\n * @default /home/user\n */\n cwd?: string\n /**\n * Language for the context.\n *\n * @default python\n */\n language?: string\n /**\n * Timeout for the request in **milliseconds**.\n *\n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string =\n 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n *\n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n *\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n *\n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n *\n * If not defined, the default Python context is used.\n */\n language?: 'python'\n }\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n *\n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n *\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n *\n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n *\n * If not defined, the default Python context is used.\n */\n language?: string\n }\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n *\n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n *\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n *\n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context\n }\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string\n context?: Context\n }\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\n 'You can provide context or language, but not both at the same time.'\n )\n }\n\n const controller = new AbortController()\n\n const requestTimeout =\n opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout\n ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (this.envdAccessToken) {\n headers['X-Access-Token'] = this.envdAccessToken\n }\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(\n `Not response body: ${res.statusText} ${await res?.text()}`\n )\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(\n execution,\n chunk,\n opts?.onStdout,\n opts?.onStderr,\n opts?.onResult,\n opts?.onError\n )\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n *\n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.connectionConfig.headers,\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(\n JUPYTER_PORT\n )}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,g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+294,25 @@ var Sandbox = class extends BaseSandbox {
294
294
  async runCode(code, opts) {
295
295
  var _a, _b, _c;
296
296
  if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
297
- throw new InvalidArgumentError("You can provide context or language, but not both at the same time.");
297
+ throw new InvalidArgumentError(
298
+ "You can provide context or language, but not both at the same time."
299
+ );
298
300
  }
299
301
  const controller = new AbortController();
300
302
  const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
301
303
  const reqTimer = requestTimeout ? setTimeout(() => {
302
304
  controller.abort();
303
305
  }, requestTimeout) : void 0;
306
+ const headers = {
307
+ "Content-Type": "application/json"
308
+ };
309
+ if (this.envdAccessToken) {
310
+ headers["X-Access-Token"] = this.envdAccessToken;
311
+ }
304
312
  try {
305
313
  const res = await fetch(`${this.jupyterUrl}/execute`, {
306
314
  method: "POST",
307
- headers: {
308
- "Content-Type": "application/json"
309
- },
315
+ headers,
310
316
  body: JSON.stringify({
311
317
  code,
312
318
  context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
@@ -321,7 +327,9 @@ var Sandbox = class extends BaseSandbox {
321
327
  throw error2;
322
328
  }
323
329
  if (!res.body) {
324
- throw new Error(`Not response body: ${res.statusText} ${await (res == null ? void 0 : res.text())}`);
330
+ throw new Error(
331
+ `Not response body: ${res.statusText} ${await (res == null ? void 0 : res.text())}`
332
+ );
325
333
  }
326
334
  clearTimeout(reqTimer);
327
335
  const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
@@ -333,7 +341,14 @@ var Sandbox = class extends BaseSandbox {
333
341
  try {
334
342
  for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
335
343
  const chunk = temp.value;
336
- await parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError);
344
+ await parseOutput(
345
+ execution,
346
+ chunk,
347
+ opts == null ? void 0 : opts.onStdout,
348
+ opts == null ? void 0 : opts.onStderr,
349
+ opts == null ? void 0 : opts.onResult,
350
+ opts == null ? void 0 : opts.onError
351
+ );
337
352
  }
338
353
  } catch (temp) {
339
354
  error = [temp];
@@ -359,16 +374,16 @@ var Sandbox = class extends BaseSandbox {
359
374
  * Creates a new context to run code in.
360
375
  *
361
376
  * @param opts options for creating the context.
362
- *
377
+ *
363
378
  * @returns context object.
364
379
  */
365
380
  async createCodeContext(opts) {
366
381
  try {
367
382
  const res = await fetch(`${this.jupyterUrl}/contexts`, {
368
383
  method: "POST",
369
- headers: {
384
+ headers: __spreadValues({
370
385
  "Content-Type": "application/json"
371
- },
386
+ }, this.connectionConfig.headers),
372
387
  body: JSON.stringify({
373
388
  language: opts == null ? void 0 : opts.language,
374
389
  cwd: opts == null ? void 0 : opts.cwd
@@ -386,7 +401,9 @@ var Sandbox = class extends BaseSandbox {
386
401
  }
387
402
  }
388
403
  get jupyterUrl() {
389
- return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`;
404
+ return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(
405
+ JUPYTER_PORT
406
+ )}`;
390
407
  }
391
408
  };
392
409
  Sandbox.defaultTemplate = "code-interpreter-v1";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => (Promise<any> | any),\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => (Promise<any> | any),\n /**\n * Custom environment variables for code execution.\n * \n * @default {}\n */\n envs?: Record<string, string>,\n /**\n * Timeout for the code execution in **milliseconds**.\n * \n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n * \n * @default /home/user\n */\n cwd?: string,\n /**\n * Language for the context.\n * \n * @default python\n */\n language?: string,\n /**\n * Timeout for the request in **milliseconds**.\n * \n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number,\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: 'python',\n },\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n * \n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n * \n * If not defined, the default Python context is used.\n */\n language?: string,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * \n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * \n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n * \n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string,\n context?: Context,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n * \n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,cAAc;;;ACAd,SAAS,WAAW,aAAa,4BAA4B;;;ACA7D,SAAS,eAAe,cAAc,oBAAoB;AAG1D,eAAsB,aAAa,KAAe;AAChD,MAAI,IAAI,IAAI;AACV;AAAA,EACF;AAEA,UAAQ,IAAI,QAAQ;AAAA,IAClB,KAAK;AACH,aAAO,IAAI;AAAA,QACT,GAAG,MAAM,IAAI,KAAK,CAAC;AAAA,MACrB;A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;AACd,YAAM,0BAA0BA,MAAK;AAAA,IACvC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,kBAAkB,MAAgD;AACtE,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,GAAG,KAAK,UAAU,aAAa;AAAA,QACrD,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAClB;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,UAAU,6BAAM;AAAA,UAChB,KAAK,6BAAM;AAAA,QACb,CAAC;AAAA,QACD,WAAW;AAAA,QACX,QAAQ,KAAK,iBAAiB,UAAU,6BAAM,gBAAgB;AAAA,MAChE,CAAC;AAED,YAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,UAAI,OAAO;AACT,cAAM;AAAA,MACR;AAEA,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,SAAS,OAAO;AACd,YAAM,0BAA0B,KAAK;AAAA,IACvC;AAAA,EACF;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAO,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,EAC1F;AACF;AArLa,QACwB,kBAA0B;;;AD/E/D,IAAO,cAAQ;","names":["TimeoutError","TimeoutError","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context, RunCodeOpts, CreateCodeContextOpts } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n ChartType,\n ChartTypes,\n Chart,\n BarChart,\n BarData,\n LineChart,\n ScatterChart,\n BoxAndWhiskerChart,\n BoxAndWhiskerData,\n PieChart,\n PieData,\n SuperChart,\n PointData,\n} from './charts'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport {\n Result,\n Execution,\n OutputMessage,\n parseOutput,\n extractError,\n ExecutionError,\n} from './messaging'\nimport {\n formatExecutionTimeoutError,\n formatRequestTimeoutError,\n readLines,\n} from './utils'\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\n\n/**\n * Represents a context for code execution.\n */\nexport type Context = {\n /**\n * The ID of the context.\n */\n id: string\n /**\n * The language of the context.\n */\n language: string\n /**\n * The working directory of the context.\n */\n cwd: string\n}\n\n/**\n * Options for running code.\n */\nexport interface RunCodeOpts {\n /**\n * Callback for handling stdout messages.\n */\n onStdout?: (output: OutputMessage) => Promise<any> | any\n /**\n * Callback for handling stderr messages.\n */\n onStderr?: (output: OutputMessage) => Promise<any> | any\n /**\n * Callback for handling the final execution result.\n */\n onResult?: (data: Result) => Promise<any> | any\n /**\n * Callback for handling the `ExecutionError` object.\n */\n onError?: (error: ExecutionError) => Promise<any> | any\n /**\n * Custom environment variables for code execution.\n *\n * @default {}\n */\n envs?: Record<string, string>\n /**\n * Timeout for the code execution in **milliseconds**.\n *\n * @default 60_000 // 60 seconds\n */\n timeoutMs?: number\n /**\n * Timeout for the request in **milliseconds**.\n *\n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number\n}\n\n/**\n * Options for creating a code context.\n */\nexport interface CreateCodeContextOpts {\n /**\n * Working directory for the context.\n *\n * @default /home/user\n */\n cwd?: string\n /**\n * Language for the context.\n *\n * @default python\n */\n language?: string\n /**\n * Timeout for the request in **milliseconds**.\n *\n * @default 30_000 // 30 seconds\n */\n requestTimeoutMs?: number\n}\n\n/**\n * E2B cloud sandbox is a secure and isolated cloud environment.\n *\n * The sandbox allows you to:\n * - Access Linux OS\n * - Create, list, and delete files and directories\n * - Run commands\n * - Run isolated code\n * - Access the internet\n *\n * Check docs [here](https://e2b.dev/docs).\n *\n * Use {@link Sandbox.create} to create a new sandbox.\n *\n * @example\n * ```ts\n * import { Sandbox } from '@e2b/code-interpreter'\n *\n * const sandbox = await Sandbox.create()\n * ```\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string =\n 'code-interpreter-v1'\n\n /**\n * Run the code as Python.\n *\n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n *\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n *\n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n *\n * If not defined, the default Python context is used.\n */\n language?: 'python'\n }\n ): Promise<Execution>\n /**\n * Run the code for the specified language.\n *\n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n * If no language is specified, Python is used.\n *\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code.\n *\n * @returns `Execution` result object.\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Language to use for code execution.\n *\n * If not defined, the default Python context is used.\n */\n language?: string\n }\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n *\n * Specify the `language` or `context` option to run the code as a different language or in a different `Context`.\n *\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code code to execute.\n * @param opts options for executing the code\n *\n * @returns `Execution` result object\n */\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n /**\n * Context to run the code in.\n */\n context?: Context\n }\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: RunCodeOpts & {\n language?: string\n context?: Context\n }\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\n 'You can provide context or language, but not both at the same time.'\n )\n }\n\n const controller = new AbortController()\n\n const requestTimeout =\n opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout\n ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n }\n if (this.envdAccessToken) {\n headers['X-Access-Token'] = this.envdAccessToken\n }\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(\n `Not response body: ${res.statusText} ${await res?.text()}`\n )\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(\n execution,\n chunk,\n opts?.onStdout,\n opts?.onStderr,\n opts?.onResult,\n opts?.onError\n )\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param opts options for creating the context.\n *\n * @returns context object.\n */\n async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {\n try {\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...this.connectionConfig.headers,\n },\n body: JSON.stringify({\n language: opts?.language,\n cwd: opts?.cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(\n JUPYTER_PORT\n )}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { ChartTypes } from './charts'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\n/**\n * Represents an output message from the sandbox code execution.\n */\nexport class OutputMessage {\n constructor(\n /**\n * The output line.\n */\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds.\n */\n public readonly timestamp: number,\n /**\n * Whether the output is an error.\n */\n public readonly error: boolean\n ) { }\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) { }\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\n\ntype E2BData = {\n data: Record<string, unknown>\n chart: ChartTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the chart data.\n */\n readonly chart?: ChartTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.chart = data['chart']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'chart',\n 'extra',\n \"text\"\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) { }\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any,\n onError?: (error: ExecutionError) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n if (onError) {\n await onError(execution.error)\n }\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,cAAc;;;ACAd,SAAS,WAAW,aAAa,4BAA4B;;;ACA7D,SAAS,eAAe,cAAc,oBAAoB;AAG1D,eAAsB,aAAa,KAAe;AAChD,MAAI,IAAI,IAAI;AACV;AAAA,EACF;AAEA,UAAQ,IAAI,QAAQ;AAAA,IAClB,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BATA,MArQR;AAqQQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAUF,SAASA,QAAO;AACd,cAAM,4BAA4BA,MAAK;AAAA,MACzC,UAAE;AACA,qBAAa,SAAS;AAAA,MACxB;AAEA,aAAO;AAAA,IACT,SAASA,QAAO;AACd,YAAM,0BAA0BA,MAAK;AAAA,IACvC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,kBAAkB,MAAgD;AACtE,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,GAAG,KAAK,UAAU,aAAa;AAAA,QACrD,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,WACb,KAAK,iBAAiB;AAAA,QAE3B,MAAM,KAAK,UAAU;AAAA,UACnB,UAAU,6BAAM;AAAA,UAChB,KAAK,6BAAM;AAAA,QACb,CAAC;AAAA,QACD,WAAW;AAAA,QACX,QAAQ,KAAK,iBAAiB,UAAU,6BAAM,gBAAgB;AAAA,MAChE,CAAC;AAED,YAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,UAAI,OAAO;AACT,cAAM;AAAA,MACR;AAEA,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,SAAS,OAAO;AACd,YAAM,0BAA0B,KAAK;AAAA,IACvC;AAAA,EACF;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAO,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK;AAAA,MACjE;AAAA,IACF,CAAC;AAAA,EACH;AACF;AA1Ma,QACwB,kBACjC;;;AD3FJ,IAAO,cAAQ;","names":["TimeoutError","TimeoutError","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/code-interpreter",
3
- "version": "2.0.0-rc.1",
3
+ "version": "2.0.0",
4
4
  "description": "E2B Code Interpreter - Stateful code execution",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",
@@ -52,7 +52,7 @@
52
52
  "vm"
53
53
  ],
54
54
  "dependencies": {
55
- "e2b": "^2.0.0-rc.3"
55
+ "e2b": "^2.0.1"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">=18"