@daytonaio/sdk 0.16.0-alpha.3 → 0.16.0-alpha.5

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/README.md CHANGED
@@ -127,7 +127,7 @@ await sandbox.git.add('path/to/repo', ['file1.txt', 'file2.txt'])
127
127
 
128
128
  ```typescript
129
129
  // Create and start a language server
130
- const lsp = sandbox.createLspServer('typescript', 'path/to/project')
130
+ const lsp = await sandbox.createLspServer('typescript', 'path/to/project')
131
131
  await lsp.start()
132
132
 
133
133
  // Notify the lsp for the file
package/dist/Daytona.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { CreateWorkspaceTargetEnum as SandboxTargetRegion } from '@daytonaio/api-client';
2
+ import { Image } from './Image';
2
3
  import { Sandbox, Sandbox as Workspace } from './Sandbox';
3
4
  /**
4
5
  * Configuration options for initializing the Daytona client.
@@ -76,7 +77,7 @@ export interface SandboxResources {
76
77
  * Parameters for creating a new Sandbox.
77
78
  *
78
79
  * @interface
79
- * @property {string} [image] - Optional Docker image to use for the Sandbox
80
+ * @property {string | Image} [image] - Optional Docker image to use for the Sandbox or an Image instance
80
81
  * @property {string} [user] - Optional os user to use for the Sandbox
81
82
  * @property {CodeLanguage | string} [language] - Programming language for direct code execution
82
83
  * @property {Record<string, string>} [envVars] - Optional environment variables to set in the Sandbox
@@ -101,8 +102,8 @@ export interface SandboxResources {
101
102
  * const sandbox = await daytona.create(params, 50);
102
103
  */
103
104
  export type CreateSandboxParams = {
104
- /** Optional Docker image to use for the Sandbox */
105
- image?: string;
105
+ /** Optional Docker image to use for the Sandbox or an Image instance */
106
+ image?: string | Image;
106
107
  /** Optional os user to use for the Sandbox */
107
108
  user?: string;
108
109
  /** Programming language for direct code execution */
@@ -165,6 +166,8 @@ export type SandboxFilter = {
165
166
  export declare class Daytona {
166
167
  private readonly sandboxApi;
167
168
  private readonly toolboxApi;
169
+ private readonly imagesApi;
170
+ private readonly objectStorageApi;
168
171
  private readonly target;
169
172
  private readonly apiKey?;
170
173
  private readonly jwtToken?;
@@ -300,6 +303,24 @@ export declare class Daytona {
300
303
  * console.log(`Current sandbox state: ${sandbox.instance.state}`);
301
304
  */
302
305
  getCurrentSandbox(sandboxId: string): Promise<Sandbox>;
306
+ /**
307
+ * Creates and registers a new image from the given Image definition.
308
+ *
309
+ * @param {string} name - The name of the image to create.
310
+ * @param {Image} image - The Image instance.
311
+ * @param {object} options - Options for the create operation.
312
+ * @param {boolean} options.verbose - Default is false. Whether to log progress information upon each state change of the image.
313
+ * @param {number} options.timeout - Default is no timeout. Timeout in seconds (0 means no timeout).
314
+ * @returns {Promise<void>}
315
+ *
316
+ * @example
317
+ * const image = Image.debianSlim('3.12').pipInstall('numpy');
318
+ * await daytona.createImage('my-python-image', image);
319
+ */
320
+ createImage(name: string, image: Image, options?: {
321
+ verbose?: boolean;
322
+ timeout?: number;
323
+ }): Promise<void>;
303
324
  /**
304
325
  * Gets the appropriate code toolbox based on language.
305
326
  *
@@ -309,4 +330,12 @@ export declare class Daytona {
309
330
  * @throws {DaytonaError} - `DaytonaError` - When an unsupported language is specified
310
331
  */
311
332
  private getCodeToolbox;
333
+ /**
334
+ * Processes the image contexts by uploading them to object storage
335
+ *
336
+ * @private
337
+ * @param {Image} image - The Image instance.
338
+ * @returns {Promise<string[]>} The list of context hashes stored in object storage.
339
+ */
340
+ private processImageContext;
312
341
  }
package/dist/Daytona.js CHANGED
@@ -43,6 +43,8 @@ const dotenv_1 = __importDefault(require("dotenv"));
43
43
  const SandboxPythonCodeToolbox_1 = require("./code-toolbox/SandboxPythonCodeToolbox");
44
44
  const SandboxTsCodeToolbox_1 = require("./code-toolbox/SandboxTsCodeToolbox");
45
45
  const DaytonaError_1 = require("./errors/DaytonaError");
46
+ const Image_1 = require("./Image");
47
+ const ObjectStorage_1 = require("./ObjectStorage");
46
48
  const Sandbox_1 = require("./Sandbox");
47
49
  /**
48
50
  * Supported programming languages for code execution
@@ -127,7 +129,9 @@ class Daytona {
127
129
  },
128
130
  },
129
131
  });
130
- const axiosInstance = axios_1.default.create();
132
+ const axiosInstance = axios_1.default.create({
133
+ timeout: 24 * 60 * 60 * 1000, // 24 hours
134
+ });
131
135
  axiosInstance.interceptors.response.use((response) => {
132
136
  return response;
133
137
  }, (error) => {
@@ -149,6 +153,8 @@ class Daytona {
149
153
  });
150
154
  this.sandboxApi = new api_client_1.WorkspaceApi(configuration, '', axiosInstance);
151
155
  this.toolboxApi = new api_client_1.ToolboxApi(configuration, '', axiosInstance);
156
+ this.imagesApi = new api_client_1.ImagesApi(configuration, '', axiosInstance);
157
+ this.objectStorageApi = new api_client_1.ObjectStorageApi(configuration, '', axiosInstance);
152
158
  }
153
159
  /**
154
160
  * Creates Sandboxes with default or custom configurations. You can specify various parameters,
@@ -180,8 +186,8 @@ class Daytona {
180
186
  * const sandbox = await daytona.create(params, 40);
181
187
  */
182
188
  async create(params, timeout = 60) {
183
- // const startTime = Date.now();
184
189
  var _a, _b, _c, _d;
190
+ const startTime = Date.now();
185
191
  if (params == null) {
186
192
  params = { language: 'python' };
187
193
  }
@@ -200,8 +206,22 @@ class Daytona {
200
206
  }
201
207
  const codeToolbox = this.getCodeToolbox(params.language);
202
208
  try {
209
+ // Handle Image instance if provided
210
+ let imageStr;
211
+ let buildInfo;
212
+ if (typeof params.image === 'string') {
213
+ imageStr = params.image;
214
+ }
215
+ else if (params.image instanceof Image_1.Image) {
216
+ const contextHashes = await this.processImageContext(params.image);
217
+ buildInfo = {
218
+ contextHashes,
219
+ dockerfileContent: params.image.dockerfile,
220
+ };
221
+ }
203
222
  const response = await this.sandboxApi.createWorkspace({
204
- image: params.image,
223
+ image: imageStr,
224
+ buildInfo,
205
225
  user: params.user,
206
226
  env: params.envVars || {},
207
227
  labels: params.labels,
@@ -222,10 +242,10 @@ class Daytona {
222
242
  name: '',
223
243
  };
224
244
  const sandbox = new Sandbox_1.Sandbox(sandboxInstance.id, sandboxInstance, this.sandboxApi, this.toolboxApi, codeToolbox);
225
- // if (!params.async) {
226
- // const timeElapsed = Date.now() - startTime;
227
- // await sandbox.waitUntilStarted(effectiveTimeout ? effectiveTimeout - (timeElapsed / 1000) : 0);
228
- // }
245
+ if (!params.async && sandbox.instance.state !== 'started') {
246
+ const timeElapsed = Date.now() - startTime;
247
+ await sandbox.waitUntilStarted(effectiveTimeout ? effectiveTimeout - timeElapsed / 1000 : 0);
248
+ }
229
249
  return sandbox;
230
250
  }
231
251
  catch (error) {
@@ -368,6 +388,48 @@ class Daytona {
368
388
  async getCurrentSandbox(sandboxId) {
369
389
  return await this.get(sandboxId);
370
390
  }
391
+ /**
392
+ * Creates and registers a new image from the given Image definition.
393
+ *
394
+ * @param {string} name - The name of the image to create.
395
+ * @param {Image} image - The Image instance.
396
+ * @param {object} options - Options for the create operation.
397
+ * @param {boolean} options.verbose - Default is false. Whether to log progress information upon each state change of the image.
398
+ * @param {number} options.timeout - Default is no timeout. Timeout in seconds (0 means no timeout).
399
+ * @returns {Promise<void>}
400
+ *
401
+ * @example
402
+ * const image = Image.debianSlim('3.12').pipInstall('numpy');
403
+ * await daytona.createImage('my-python-image', image);
404
+ */
405
+ async createImage(name, image, options = {}) {
406
+ const contextHashes = await this.processImageContext(image);
407
+ let builtImage = (await this.imagesApi.buildImage({
408
+ name,
409
+ buildInfo: {
410
+ contextHashes,
411
+ dockerfileContent: image.dockerfile,
412
+ },
413
+ }, undefined, {
414
+ timeout: (options.timeout || 0) * 1000,
415
+ })).data;
416
+ let previousState = null;
417
+ while (builtImage.state !== api_client_1.ImageState.ACTIVE && builtImage.state !== api_client_1.ImageState.ERROR) {
418
+ if (options.verbose && previousState !== builtImage.state) {
419
+ console.log(`Building image ${builtImage.name} (${builtImage.state})`);
420
+ previousState = builtImage.state;
421
+ }
422
+ await new Promise((resolve) => setTimeout(resolve, 1000));
423
+ const response = await this.imagesApi.getImage(builtImage.id);
424
+ builtImage = response.data;
425
+ }
426
+ if (builtImage.state === api_client_1.ImageState.ERROR) {
427
+ throw new DaytonaError_1.DaytonaError(`Failed to build image. Image ended in the ERROR state. name: ${builtImage.name}; error reason: ${builtImage.errorReason}`);
428
+ }
429
+ if (options.verbose) {
430
+ console.log(`Built image ${builtImage.name} (${builtImage.state})`);
431
+ }
432
+ }
371
433
  /**
372
434
  * Gets the appropriate code toolbox based on language.
373
435
  *
@@ -388,5 +450,31 @@ class Daytona {
388
450
  throw new DaytonaError_1.DaytonaError(`Unsupported language: ${language}, supported languages: ${Object.values(CodeLanguage).join(', ')}`);
389
451
  }
390
452
  }
453
+ /**
454
+ * Processes the image contexts by uploading them to object storage
455
+ *
456
+ * @private
457
+ * @param {Image} image - The Image instance.
458
+ * @returns {Promise<string[]>} The list of context hashes stored in object storage.
459
+ */
460
+ async processImageContext(image) {
461
+ if (!image.contextList || !image.contextList.length) {
462
+ return [];
463
+ }
464
+ const pushAccessCreds = (await this.objectStorageApi.getPushAccess()).data;
465
+ const objectStorage = new ObjectStorage_1.ObjectStorage({
466
+ endpointUrl: pushAccessCreds.storageUrl,
467
+ accessKeyId: pushAccessCreds.accessKey,
468
+ secretAccessKey: pushAccessCreds.secret,
469
+ sessionToken: pushAccessCreds.sessionToken,
470
+ bucketName: pushAccessCreds.bucket,
471
+ });
472
+ const contextHashes = [];
473
+ for (const context of image.contextList) {
474
+ const contextHash = await objectStorage.upload(context.sourcePath, pushAccessCreds.organizationId, context.archivePath);
475
+ contextHashes.push(contextHash);
476
+ }
477
+ return contextHashes;
478
+ }
391
479
  }
392
480
  exports.Daytona = Daytona;
@@ -0,0 +1,261 @@
1
+ declare const SUPPORTED_PYTHON_SERIES: readonly ["3.9", "3.10", "3.11", "3.12", "3.13"];
2
+ type SupportedPythonSeries = (typeof SUPPORTED_PYTHON_SERIES)[number];
3
+ /**
4
+ * Represents a context file to be added to the image.
5
+ *
6
+ * @interface
7
+ * @property {string} sourcePath - The path to the source file or directory.
8
+ * @property {string} archivePath - The path inside the archive file in object storage.
9
+ */
10
+ export interface Context {
11
+ sourcePath: string;
12
+ archivePath?: string;
13
+ }
14
+ /**
15
+ * Options for the pip install command.
16
+ *
17
+ * @interface
18
+ * @property {string[]} findLinks - The find-links to use for the pip install command.
19
+ * @property {string} indexUrl - The index URL to use for the pip install command.
20
+ * @property {string[]} extraIndexUrls - The extra index URLs to use for the pip install command.
21
+ * @property {boolean} pre - Whether to install pre-release versions.
22
+ * @property {string} extraOptions - The extra options to use for the pip install command. Given string is passed directly to the pip install command.
23
+ */
24
+ export interface PipInstallOptions {
25
+ findLinks?: string[];
26
+ indexUrl?: string;
27
+ extraIndexUrls?: string[];
28
+ pre?: boolean;
29
+ extraOptions?: string;
30
+ }
31
+ /**
32
+ * Options for the pip install command from a pyproject.toml file.
33
+ *
34
+ * @interface
35
+ * @property {string[]} optionalDependencies - The optional dependencies to install.
36
+ *
37
+ * @extends {PipInstallOptions}
38
+ */
39
+ export interface PyprojectOptions extends PipInstallOptions {
40
+ optionalDependencies?: string[];
41
+ }
42
+ /**
43
+ * Represents an image definition for a Daytona sandbox.
44
+ * Do not construct this class directly. Instead use one of its static factory methods,
45
+ * such as `Image.base()`, `Image.debianSlim()` or `Image.fromDockerfile()`.
46
+ *
47
+ * @class
48
+ * @property {string} dockerfile - The Dockerfile content.
49
+ * @property {Context[]} contextList - The list of context files to be added to the image.
50
+ */
51
+ export declare class Image {
52
+ private _dockerfile;
53
+ private _contextList;
54
+ private constructor();
55
+ get dockerfile(): string;
56
+ get contextList(): Context[];
57
+ /**
58
+ * Adds commands to install packages using pip.
59
+ *
60
+ * @param {string | string[]} packages - The packages to install.
61
+ * @param {Object} options - The options for the pip install command.
62
+ * @param {string[]} options.findLinks - The find-links to use for the pip install command.
63
+ * @returns {Image} The Image instance.
64
+ *
65
+ * @example
66
+ * const image = Image.debianSlim('3.12').pipInstall('numpy', { findLinks: ['https://pypi.org/simple'] })
67
+ */
68
+ pipInstall(packages: string | string[], options?: PipInstallOptions): Image;
69
+ /**
70
+ * Installs dependencies from a requirements.txt file.
71
+ *
72
+ * @param {string} requirementsTxt - The path to the requirements.txt file.
73
+ * @param {PipInstallOptions} options - The options for the pip install command.
74
+ * @returns {Image} The Image instance.
75
+ *
76
+ * @example
77
+ * const image = Image.debianSlim('3.12')
78
+ * image.pipInstallFromRequirements('requirements.txt', { findLinks: ['https://pypi.org/simple'] })
79
+ */
80
+ pipInstallFromRequirements(requirementsTxt: string, options?: PipInstallOptions): Image;
81
+ /**
82
+ * Installs dependencies from a pyproject.toml file.
83
+ *
84
+ * @param {string} pyprojectToml - The path to the pyproject.toml file.
85
+ * @param {PyprojectOptions} options - The options for the pip install command.
86
+ * @returns {Image} The Image instance.
87
+ *
88
+ * @example
89
+ * const image = Image.debianSlim('3.12')
90
+ * image.pipInstallFromPyproject('pyproject.toml', { optionalDependencies: ['dev'] })
91
+ */
92
+ pipInstallFromPyproject(pyprojectToml: string, options?: PyprojectOptions): Image;
93
+ /**
94
+ * Adds a local file to the image.
95
+ *
96
+ * @param {string} localPath - The path to the local file.
97
+ * @param {string} remotePath - The path of the file in the image.
98
+ * @returns {Image} The Image instance.
99
+ *
100
+ * @example
101
+ * const image = Image
102
+ * .debianSlim('3.12')
103
+ * .addLocalFile('requirements.txt', '/home/daytona/requirements.txt')
104
+ */
105
+ addLocalFile(localPath: string, remotePath: string): Image;
106
+ /**
107
+ * Adds a local directory to the image.
108
+ *
109
+ * @param {string} localPath - The path to the local directory.
110
+ * @param {string} remotePath - The path of the directory in the image.
111
+ * @returns {Image} The Image instance.
112
+ *
113
+ * @example
114
+ * const image = Image
115
+ * .debianSlim('3.12')
116
+ * .addLocalDir('src', '/home/daytona/src')
117
+ */
118
+ addLocalDir(localPath: string, remotePath: string): Image;
119
+ /**
120
+ * Runs commands in the image.
121
+ *
122
+ * @param {string | string[]} commands - The commands to run.
123
+ * @returns {Image} The Image instance.
124
+ *
125
+ * @example
126
+ * const image = Image
127
+ * .debianSlim('3.12')
128
+ * .runCommands('echo "Hello, world!"')
129
+ */
130
+ runCommands(...commands: (string | string[])[]): Image;
131
+ /**
132
+ * Sets environment variables in the image.
133
+ *
134
+ * @param {Record<string, string>} envVars - The environment variables to set.
135
+ * @returns {Image} The Image instance.
136
+ *
137
+ * @example
138
+ * const image = Image
139
+ * .debianSlim('3.12')
140
+ * .env({ FOO: 'bar' })
141
+ */
142
+ env(envVars: Record<string, string>): Image;
143
+ /**
144
+ * Sets the working directory in the image.
145
+ *
146
+ * @param {string} dirPath - The path to the working directory.
147
+ * @returns {Image} The Image instance.
148
+ *
149
+ * @example
150
+ * const image = Image
151
+ * .debianSlim('3.12')
152
+ * .workdir('/home/daytona')
153
+ */
154
+ workdir(dirPath: string): Image;
155
+ /**
156
+ * Sets the entrypoint for the image.
157
+ *
158
+ * @param {string[]} entrypointCommands - The commands to set as the entrypoint.
159
+ * @returns {Image} The Image instance.
160
+ *
161
+ * @example
162
+ * const image = Image
163
+ * .debianSlim('3.12')
164
+ * .entrypoint(['/bin/bash'])
165
+ */
166
+ entrypoint(entrypointCommands: string[]): Image;
167
+ /**
168
+ * Sets the default command for the image.
169
+ *
170
+ * @param {string[]} cmd - The command to set as the default command.
171
+ * @returns {Image} The Image instance.
172
+ *
173
+ * @example
174
+ * const image = Image
175
+ * .debianSlim('3.12')
176
+ * .cmd(['/bin/bash'])
177
+ */
178
+ cmd(cmd: string[]): Image;
179
+ /**
180
+ * Extends an image with arbitrary Dockerfile-like commands.
181
+ *
182
+ * @param {string | string[]} dockerfileCommands - The commands to add to the Dockerfile.
183
+ * @param {string} contextDir - The path to the context directory.
184
+ * @returns {Image} The Image instance.
185
+ *
186
+ * @example
187
+ * const image = Image
188
+ * .debianSlim('3.12')
189
+ * .dockerfileCommands(['RUN echo "Hello, world!"'])
190
+ */
191
+ dockerfileCommands(dockerfileCommands: (string | string[])[], contextDir?: string): Image;
192
+ /**
193
+ * Creates an Image from an existing Dockerfile.
194
+ *
195
+ * @param {string} path - The path to the Dockerfile.
196
+ * @returns {Image} The Image instance.
197
+ *
198
+ * @example
199
+ * const image = Image.fromDockerfile('Dockerfile')
200
+ */
201
+ static fromDockerfile(path: string): Image;
202
+ /**
203
+ * Creates an Image from an existing base image.
204
+ *
205
+ * @param {string} image - The base image to use.
206
+ * @returns {Image} The Image instance.
207
+ *
208
+ * @example
209
+ * const image = Image.base('python:3.12-slim-bookworm')
210
+ */
211
+ static base(image: string): Image;
212
+ /**
213
+ * Creates a Debian slim image based on the official Python Docker image.
214
+ *
215
+ * @param {string} pythonVersion - The Python version to use.
216
+ * @returns {Image} The Image instance.
217
+ *
218
+ * @example
219
+ * const image = Image.debianSlim('3.12')
220
+ */
221
+ static debianSlim(pythonVersion?: SupportedPythonSeries): Image;
222
+ /**
223
+ * Formats pip install arguments in a single string.
224
+ *
225
+ * @param {PipInstallOptions} options - The options for the pip install command.
226
+ * @returns {string} The formatted pip install arguments.
227
+ */
228
+ private formatPipInstallArgs;
229
+ /**
230
+ * Flattens a string argument.
231
+ *
232
+ * @param {string} functionName - The name of the function.
233
+ * @param {string} argName - The name of the argument.
234
+ * @param {any} args - The argument to flatten.
235
+ * @returns {string[]} The flattened argument.
236
+ */
237
+ private flattenStringArgs;
238
+ /**
239
+ * Processes the Python version.
240
+ *
241
+ * @param {string} pythonVersion - The Python version to use.
242
+ * @returns {string} The processed Python version.
243
+ */
244
+ private static processPythonVersion;
245
+ /**
246
+ * Extracts source files from COPY commands in a Dockerfile.
247
+ *
248
+ * @param {string} dockerfileContent - The content of the Dockerfile.
249
+ * @param {string} pathPrefix - The path prefix to use for the sources.
250
+ * @returns {Array<[string, string]>} The list of the actual file path and its corresponding COPY-command source path.
251
+ */
252
+ private static extractCopySources;
253
+ /**
254
+ * Parses a COPY command to extract sources and destination.
255
+ *
256
+ * @param {string} line - The line to parse.
257
+ * @returns {Object} The parsed sources and destination.
258
+ */
259
+ private static parseCopyCommand;
260
+ }
261
+ export {};