@daytona/sdk 0.161.0-alpha.1

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.
Files changed (95) hide show
  1. package/README.md +180 -0
  2. package/package.json +56 -0
  3. package/src/CodeInterpreter.d.ts +94 -0
  4. package/src/CodeInterpreter.js +297 -0
  5. package/src/CodeInterpreter.js.map +1 -0
  6. package/src/ComputerUse.d.ts +538 -0
  7. package/src/ComputerUse.js +808 -0
  8. package/src/ComputerUse.js.map +1 -0
  9. package/src/Daytona.d.ts +340 -0
  10. package/src/Daytona.js +538 -0
  11. package/src/Daytona.js.map +1 -0
  12. package/src/FileSystem.d.ts +326 -0
  13. package/src/FileSystem.js +412 -0
  14. package/src/FileSystem.js.map +1 -0
  15. package/src/Git.d.ts +202 -0
  16. package/src/Git.js +326 -0
  17. package/src/Git.js.map +1 -0
  18. package/src/Image.d.ts +264 -0
  19. package/src/Image.js +546 -0
  20. package/src/Image.js.map +1 -0
  21. package/src/LspServer.d.ts +171 -0
  22. package/src/LspServer.js +258 -0
  23. package/src/LspServer.js.map +1 -0
  24. package/src/ObjectStorage.d.ts +78 -0
  25. package/src/ObjectStorage.js +199 -0
  26. package/src/ObjectStorage.js.map +1 -0
  27. package/src/Process.d.ts +490 -0
  28. package/src/Process.js +790 -0
  29. package/src/Process.js.map +1 -0
  30. package/src/PtyHandle.d.ts +154 -0
  31. package/src/PtyHandle.js +416 -0
  32. package/src/PtyHandle.js.map +1 -0
  33. package/src/Sandbox.d.ts +425 -0
  34. package/src/Sandbox.js +776 -0
  35. package/src/Sandbox.js.map +1 -0
  36. package/src/Snapshot.d.ts +139 -0
  37. package/src/Snapshot.js +248 -0
  38. package/src/Snapshot.js.map +1 -0
  39. package/src/Volume.d.ts +83 -0
  40. package/src/Volume.js +119 -0
  41. package/src/Volume.js.map +1 -0
  42. package/src/code-toolbox/SandboxJsCodeToolbox.d.ts +5 -0
  43. package/src/code-toolbox/SandboxJsCodeToolbox.js +20 -0
  44. package/src/code-toolbox/SandboxJsCodeToolbox.js.map +1 -0
  45. package/src/code-toolbox/SandboxPythonCodeToolbox.d.ts +11 -0
  46. package/src/code-toolbox/SandboxPythonCodeToolbox.js +359 -0
  47. package/src/code-toolbox/SandboxPythonCodeToolbox.js.map +1 -0
  48. package/src/code-toolbox/SandboxTsCodeToolbox.d.ts +5 -0
  49. package/src/code-toolbox/SandboxTsCodeToolbox.js +29 -0
  50. package/src/code-toolbox/SandboxTsCodeToolbox.js.map +1 -0
  51. package/src/errors/DaytonaError.d.ts +31 -0
  52. package/src/errors/DaytonaError.js +51 -0
  53. package/src/errors/DaytonaError.js.map +1 -0
  54. package/src/index.d.ts +21 -0
  55. package/src/index.js +45 -0
  56. package/src/index.js.map +1 -0
  57. package/src/types/Charts.d.ts +151 -0
  58. package/src/types/Charts.js +46 -0
  59. package/src/types/Charts.js.map +1 -0
  60. package/src/types/CodeInterpreter.d.ts +76 -0
  61. package/src/types/CodeInterpreter.js +7 -0
  62. package/src/types/CodeInterpreter.js.map +1 -0
  63. package/src/types/ExecuteResponse.d.ts +25 -0
  64. package/src/types/ExecuteResponse.js +7 -0
  65. package/src/types/ExecuteResponse.js.map +1 -0
  66. package/src/types/Pty.d.ts +47 -0
  67. package/src/types/Pty.js +7 -0
  68. package/src/types/Pty.js.map +1 -0
  69. package/src/utils/ArtifactParser.d.ts +13 -0
  70. package/src/utils/ArtifactParser.js +55 -0
  71. package/src/utils/ArtifactParser.js.map +1 -0
  72. package/src/utils/Binary.d.ts +38 -0
  73. package/src/utils/Binary.js +168 -0
  74. package/src/utils/Binary.js.map +1 -0
  75. package/src/utils/FileTransfer.d.ts +14 -0
  76. package/src/utils/FileTransfer.js +216 -0
  77. package/src/utils/FileTransfer.js.map +1 -0
  78. package/src/utils/Import.d.ts +97 -0
  79. package/src/utils/Import.js +79 -0
  80. package/src/utils/Import.js.map +1 -0
  81. package/src/utils/Multipart.d.ts +26 -0
  82. package/src/utils/Multipart.js +113 -0
  83. package/src/utils/Multipart.js.map +1 -0
  84. package/src/utils/Runtime.d.ts +43 -0
  85. package/src/utils/Runtime.js +95 -0
  86. package/src/utils/Runtime.js.map +1 -0
  87. package/src/utils/Stream.d.ts +19 -0
  88. package/src/utils/Stream.js +364 -0
  89. package/src/utils/Stream.js.map +1 -0
  90. package/src/utils/WebSocket.d.ts +9 -0
  91. package/src/utils/WebSocket.js +26 -0
  92. package/src/utils/WebSocket.js.map +1 -0
  93. package/src/utils/otel.decorator.d.ts +82 -0
  94. package/src/utils/otel.decorator.js +141 -0
  95. package/src/utils/otel.decorator.js.map +1 -0
package/src/Sandbox.js ADDED
@@ -0,0 +1,776 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2025 Daytona Platforms Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.Sandbox = void 0;
8
+ const tslib_1 = require("tslib");
9
+ const api_client_1 = require("@daytonaio/api-client");
10
+ const toolbox_api_client_1 = require("@daytonaio/toolbox-api-client");
11
+ const FileSystem_1 = require("./FileSystem");
12
+ const Git_1 = require("./Git");
13
+ const Process_1 = require("./Process");
14
+ const LspServer_1 = require("./LspServer");
15
+ const DaytonaError_1 = require("./errors/DaytonaError");
16
+ const ComputerUse_1 = require("./ComputerUse");
17
+ const CodeInterpreter_1 = require("./CodeInterpreter");
18
+ const otel_decorator_1 = require("./utils/otel.decorator");
19
+ /**
20
+ * Represents a Daytona Sandbox.
21
+ *
22
+ * @property {FileSystem} fs - File system operations interface
23
+ * @property {Git} git - Git operations interface
24
+ * @property {Process} process - Process execution interface
25
+ * @property {CodeInterpreter} codeInterpreter - Stateful interpreter interface for executing code.
26
+ * Currently supports only Python. For other languages, use the `process.codeRun` method.
27
+ * @property {ComputerUse} computerUse - Computer use operations interface for desktop automation
28
+ * @property {string} id - Unique identifier for the Sandbox
29
+ * @property {string} organizationId - Organization ID of the Sandbox
30
+ * @property {string} [snapshot] - Daytona snapshot used to create the Sandbox
31
+ * @property {string} user - OS user running in the Sandbox
32
+ * @property {Record<string, string>} env - Environment variables set in the Sandbox
33
+ * @property {Record<string, string>} labels - Custom labels attached to the Sandbox
34
+ * @property {boolean} public - Whether the Sandbox is publicly accessible
35
+ * @property {string} target - Target location of the runner where the Sandbox runs
36
+ * @property {number} cpu - Number of CPUs allocated to the Sandbox
37
+ * @property {number} gpu - Number of GPUs allocated to the Sandbox
38
+ * @property {number} memory - Amount of memory allocated to the Sandbox in GiB
39
+ * @property {number} disk - Amount of disk space allocated to the Sandbox in GiB
40
+ * @property {SandboxState} state - Current state of the Sandbox (e.g., "started", "stopped")
41
+ * @property {string} [errorReason] - Error message if Sandbox is in error state
42
+ * @property {boolean} [recoverable] - Whether the Sandbox error is recoverable.
43
+ * @property {SandboxBackupStateEnum} [backupState] - Current state of Sandbox backup
44
+ * @property {string} [backupCreatedAt] - When the backup was created
45
+ * @property {number} [autoStopInterval] - Auto-stop interval in minutes
46
+ * @property {number} [autoArchiveInterval] - Auto-archive interval in minutes
47
+ * @property {number} [autoDeleteInterval] - Auto-delete interval in minutes
48
+ * @property {Array<SandboxVolume>} [volumes] - Volumes attached to the Sandbox
49
+ * @property {BuildInfo} [buildInfo] - Build information for the Sandbox if it was created from dynamic build
50
+ * @property {string} [createdAt] - When the Sandbox was created
51
+ * @property {string} [updatedAt] - When the Sandbox was last updated
52
+ * @property {boolean} networkBlockAll - Whether to block all network access for the Sandbox
53
+ * @property {string} [networkAllowList] - Comma-separated list of allowed CIDR network addresses for the Sandbox
54
+ *
55
+ * @class
56
+ */
57
+ class Sandbox {
58
+ clientConfig;
59
+ axiosInstance;
60
+ sandboxApi;
61
+ codeToolbox;
62
+ fs;
63
+ git;
64
+ process;
65
+ computerUse;
66
+ codeInterpreter;
67
+ id;
68
+ name;
69
+ organizationId;
70
+ snapshot;
71
+ user;
72
+ env;
73
+ labels;
74
+ public;
75
+ target;
76
+ cpu;
77
+ gpu;
78
+ memory;
79
+ disk;
80
+ state;
81
+ errorReason;
82
+ recoverable;
83
+ backupState;
84
+ backupCreatedAt;
85
+ autoStopInterval;
86
+ autoArchiveInterval;
87
+ autoDeleteInterval;
88
+ volumes;
89
+ buildInfo;
90
+ createdAt;
91
+ updatedAt;
92
+ networkBlockAll;
93
+ networkAllowList;
94
+ toolboxProxyUrl;
95
+ infoApi;
96
+ /**
97
+ * Creates a new Sandbox instance
98
+ *
99
+ * @param {SandboxDto} sandboxDto - The API Sandbox instance
100
+ * @param {SandboxApi} sandboxApi - API client for Sandbox operations
101
+ * @param {InfoApi} infoApi - API client for info operations
102
+ * @param {SandboxCodeToolbox} codeToolbox - Language-specific toolbox implementation
103
+ */
104
+ constructor(sandboxDto, clientConfig, axiosInstance, sandboxApi, codeToolbox) {
105
+ this.clientConfig = clientConfig;
106
+ this.axiosInstance = axiosInstance;
107
+ this.sandboxApi = sandboxApi;
108
+ this.codeToolbox = codeToolbox;
109
+ this.processSandboxDto(sandboxDto);
110
+ // Set the toolbox base URL
111
+ let baseUrl = this.toolboxProxyUrl;
112
+ if (!baseUrl.endsWith('/')) {
113
+ baseUrl += '/';
114
+ }
115
+ this.axiosInstance.defaults.baseURL = baseUrl + this.id;
116
+ this.clientConfig.basePath = this.axiosInstance.defaults.baseURL;
117
+ // Initialize Services
118
+ const getPreviewToken = async () => (await this.getPreviewLink(1)).token;
119
+ this.fs = new FileSystem_1.FileSystem(this.clientConfig, new toolbox_api_client_1.FileSystemApi(this.clientConfig, '', this.axiosInstance));
120
+ this.git = new Git_1.Git(new toolbox_api_client_1.GitApi(this.clientConfig, '', this.axiosInstance));
121
+ this.process = new Process_1.Process(this.clientConfig, this.codeToolbox, new toolbox_api_client_1.ProcessApi(this.clientConfig, '', this.axiosInstance), getPreviewToken);
122
+ this.codeInterpreter = new CodeInterpreter_1.CodeInterpreter(this.clientConfig, new toolbox_api_client_1.InterpreterApi(this.clientConfig, '', this.axiosInstance), getPreviewToken);
123
+ this.computerUse = new ComputerUse_1.ComputerUse(new toolbox_api_client_1.ComputerUseApi(this.clientConfig, '', this.axiosInstance));
124
+ this.infoApi = new toolbox_api_client_1.InfoApi(this.clientConfig, '', this.axiosInstance);
125
+ }
126
+ /**
127
+ * Gets the user's home directory path for the logged in user inside the Sandbox.
128
+ *
129
+ * @returns {Promise<string | undefined>} The absolute path to the Sandbox user's home directory for the logged in user
130
+ *
131
+ * @example
132
+ * const userHomeDir = await sandbox.getUserHomeDir();
133
+ * console.log(`Sandbox user home: ${userHomeDir}`);
134
+ */
135
+ async getUserHomeDir() {
136
+ const response = await this.infoApi.getUserHomeDir();
137
+ return response.data.dir;
138
+ }
139
+ /**
140
+ * @deprecated Use `getUserHomeDir` instead. This method will be removed in a future version.
141
+ */
142
+ async getUserRootDir() {
143
+ return this.getUserHomeDir();
144
+ }
145
+ /**
146
+ * Gets the working directory path inside the Sandbox.
147
+ *
148
+ * @returns {Promise<string | undefined>} The absolute path to the Sandbox working directory. Uses the WORKDIR specified
149
+ * in the Dockerfile if present, or falling back to the user's home directory if not.
150
+ *
151
+ * @example
152
+ * const workDir = await sandbox.getWorkDir();
153
+ * console.log(`Sandbox working directory: ${workDir}`);
154
+ */
155
+ async getWorkDir() {
156
+ const response = await this.infoApi.getWorkDir();
157
+ return response.data.dir;
158
+ }
159
+ /**
160
+ * Creates a new Language Server Protocol (LSP) server instance.
161
+ *
162
+ * The LSP server provides language-specific features like code completion,
163
+ * diagnostics, and more.
164
+ *
165
+ * @param {LspLanguageId} languageId - The language server type (e.g., "typescript")
166
+ * @param {string} pathToProject - Path to the project root directory. Relative paths are resolved based on the sandbox working directory.
167
+ * @returns {LspServer} A new LSP server instance configured for the specified language
168
+ *
169
+ * @example
170
+ * const lsp = await sandbox.createLspServer('typescript', 'workspace/project');
171
+ */
172
+ async createLspServer(languageId, pathToProject) {
173
+ return new LspServer_1.LspServer(languageId, pathToProject, new toolbox_api_client_1.LspApi(this.clientConfig, '', this.axiosInstance));
174
+ }
175
+ /**
176
+ * Sets labels for the Sandbox.
177
+ *
178
+ * Labels are key-value pairs that can be used to organize and identify Sandboxes.
179
+ *
180
+ * @param {Record<string, string>} labels - Dictionary of key-value pairs representing Sandbox labels
181
+ * @returns {Promise<void>}
182
+ *
183
+ * @example
184
+ * // Set sandbox labels
185
+ * await sandbox.setLabels({
186
+ * project: 'my-project',
187
+ * environment: 'development',
188
+ * team: 'backend'
189
+ * });
190
+ */
191
+ async setLabels(labels) {
192
+ this.labels = (await this.sandboxApi.replaceLabels(this.id, { labels })).data.labels;
193
+ return this.labels;
194
+ }
195
+ /**
196
+ * Start the Sandbox.
197
+ *
198
+ * This method starts the Sandbox and waits for it to be ready.
199
+ *
200
+ * @param {number} [timeout] - Maximum time to wait in seconds. 0 means no timeout.
201
+ * Defaults to 60-second timeout.
202
+ * @returns {Promise<void>}
203
+ * @throws {DaytonaError} - `DaytonaError` - If Sandbox fails to start or times out
204
+ *
205
+ * @example
206
+ * const sandbox = await daytona.getCurrentSandbox('my-sandbox');
207
+ * await sandbox.start(40); // Wait up to 40 seconds
208
+ * console.log('Sandbox started successfully');
209
+ */
210
+ async start(timeout = 60) {
211
+ if (timeout < 0) {
212
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
213
+ }
214
+ const startTime = Date.now();
215
+ const response = await this.sandboxApi.startSandbox(this.id, undefined, { timeout: timeout * 1000 });
216
+ this.processSandboxDto(response.data);
217
+ const timeElapsed = Date.now() - startTime;
218
+ await this.waitUntilStarted(timeout ? Math.max(0.001, timeout - timeElapsed / 1000) : timeout);
219
+ }
220
+ /**
221
+ * Recover the Sandbox from a recoverable error and wait for it to be ready.
222
+ *
223
+ * @param {number} [timeout] - Maximum time to wait in seconds. 0 means no timeout.
224
+ * Defaults to 60-second timeout.
225
+ * @returns {Promise<void>}
226
+ * @throws {DaytonaError} - `DaytonaError` - If Sandbox fails to recover or times out
227
+ *
228
+ * @example
229
+ * const sandbox = await daytona.get('my-sandbox-id');
230
+ * await sandbox.recover();
231
+ * console.log('Sandbox recovered successfully');
232
+ */
233
+ async recover(timeout = 60) {
234
+ if (timeout < 0) {
235
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
236
+ }
237
+ const startTime = Date.now();
238
+ const response = await this.sandboxApi.recoverSandbox(this.id, undefined, { timeout: timeout * 1000 });
239
+ this.processSandboxDto(response.data);
240
+ const timeElapsed = Date.now() - startTime;
241
+ await this.waitUntilStarted(timeout ? Math.max(0.001, timeout - timeElapsed / 1000) : timeout);
242
+ }
243
+ /**
244
+ * Stops the Sandbox.
245
+ *
246
+ * This method stops the Sandbox and waits for it to be fully stopped.
247
+ *
248
+ * @param {number} [timeout] - Maximum time to wait in seconds. 0 means no timeout.
249
+ * Defaults to 60-second timeout.
250
+ * @param {boolean} [force] - If true, uses SIGKILL instead of SIGTERM. Defaults to false.
251
+ * @returns {Promise<void>}
252
+ *
253
+ * @example
254
+ * const sandbox = await daytona.get('my-sandbox-id');
255
+ * await sandbox.stop();
256
+ * console.log('Sandbox stopped successfully');
257
+ */
258
+ async stop(timeout = 60, force = false) {
259
+ if (timeout < 0) {
260
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
261
+ }
262
+ const startTime = Date.now();
263
+ await this.sandboxApi.stopSandbox(this.id, undefined, force, { timeout: timeout * 1000 });
264
+ await this.refreshDataSafe();
265
+ const timeElapsed = Date.now() - startTime;
266
+ await this.waitUntilStopped(timeout ? Math.max(0.001, timeout - timeElapsed / 1000) : timeout);
267
+ }
268
+ /**
269
+ * Deletes the Sandbox.
270
+ * @returns {Promise<void>}
271
+ */
272
+ async delete(timeout = 60) {
273
+ await this.sandboxApi.deleteSandbox(this.id, undefined, { timeout: timeout * 1000 });
274
+ this.refreshDataSafe();
275
+ }
276
+ /**
277
+ * Waits for the Sandbox to reach the 'started' state.
278
+ *
279
+ * This method polls the Sandbox status until it reaches the 'started' state
280
+ * or encounters an error.
281
+ *
282
+ * @param {number} [timeout] - Maximum time to wait in seconds. 0 means no timeout.
283
+ * Defaults to 60 seconds.
284
+ * @returns {Promise<void>}
285
+ * @throws {DaytonaError} - `DaytonaError` - If the sandbox ends up in an error state or fails to start within the timeout period.
286
+ */
287
+ async waitUntilStarted(timeout = 60) {
288
+ if (timeout < 0) {
289
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
290
+ }
291
+ let checkInterval = 100;
292
+ const startTime = Date.now();
293
+ while (this.state !== 'started') {
294
+ await this.refreshData();
295
+ // @ts-expect-error this.refreshData() can modify this.state so this check is fine
296
+ if (this.state === 'started') {
297
+ return;
298
+ }
299
+ if (this.state === 'error') {
300
+ const errMsg = `Sandbox ${this.id} failed to start with status: ${this.state}, error reason: ${this.errorReason}`;
301
+ throw new DaytonaError_1.DaytonaError(errMsg);
302
+ }
303
+ if (timeout !== 0 && Date.now() - startTime > timeout * 1000) {
304
+ throw new DaytonaError_1.DaytonaError('Sandbox failed to become ready within the timeout period');
305
+ }
306
+ await new Promise((resolve) => setTimeout(resolve, checkInterval));
307
+ if (Date.now() - startTime > 5000) {
308
+ checkInterval = Math.min(checkInterval * 1.1, 1000);
309
+ }
310
+ }
311
+ }
312
+ /**
313
+ * Wait for Sandbox to reach 'stopped' state.
314
+ *
315
+ * This method polls the Sandbox status until it reaches the 'stopped' state
316
+ * or encounters an error.
317
+ *
318
+ * @param {number} [timeout] - Maximum time to wait in seconds. 0 means no timeout.
319
+ * Defaults to 60 seconds.
320
+ * @returns {Promise<void>}
321
+ * @throws {DaytonaError} - `DaytonaError` - If the sandbox fails to stop within the timeout period.
322
+ */
323
+ async waitUntilStopped(timeout = 60) {
324
+ if (timeout < 0) {
325
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
326
+ }
327
+ let checkInterval = 100;
328
+ const startTime = Date.now();
329
+ // Treat destroyed as stopped to cover ephemeral sandboxes that are automatically deleted after stopping
330
+ while (this.state !== 'stopped' && this.state !== 'destroyed') {
331
+ this.refreshDataSafe();
332
+ // @ts-expect-error this.refreshData() can modify this.state so this check is fine
333
+ if (this.state === 'stopped' || this.state === 'destroyed') {
334
+ return;
335
+ }
336
+ if (this.state === 'error') {
337
+ const errMsg = `Sandbox failed to stop with status: ${this.state}, error reason: ${this.errorReason}`;
338
+ throw new DaytonaError_1.DaytonaError(errMsg);
339
+ }
340
+ if (timeout !== 0 && Date.now() - startTime > timeout * 1000) {
341
+ throw new DaytonaError_1.DaytonaError('Sandbox failed to become stopped within the timeout period');
342
+ }
343
+ await new Promise((resolve) => setTimeout(resolve, checkInterval));
344
+ if (Date.now() - startTime > 5000) {
345
+ checkInterval = Math.min(checkInterval * 1.1, 1000);
346
+ }
347
+ }
348
+ }
349
+ /**
350
+ * Refreshes the Sandbox data from the API.
351
+ *
352
+ * @returns {Promise<void>}
353
+ *
354
+ * @example
355
+ * await sandbox.refreshData();
356
+ * console.log(`Sandbox ${sandbox.id}:`);
357
+ * console.log(`State: ${sandbox.state}`);
358
+ * console.log(`Resources: ${sandbox.cpu} CPU, ${sandbox.memory} GiB RAM`);
359
+ */
360
+ async refreshData() {
361
+ const response = await this.sandboxApi.getSandbox(this.id);
362
+ this.processSandboxDto(response.data);
363
+ }
364
+ /**
365
+ * Refreshes the sandbox activity to reset the timer for automated lifecycle management actions.
366
+ *
367
+ * This method updates the sandbox's last activity timestamp without changing its state.
368
+ * It is useful for keeping long-running sessions alive while there is still user activity.
369
+ *
370
+ * @returns {Promise<void>}
371
+ *
372
+ * @example
373
+ * // Keep sandbox activity alive
374
+ * await sandbox.refreshActivity();
375
+ */
376
+ async refreshActivity() {
377
+ await this.sandboxApi.updateLastActivity(this.id);
378
+ }
379
+ /**
380
+ * Set the auto-stop interval for the Sandbox.
381
+ *
382
+ * The Sandbox will automatically stop after being idle (no new events) for the specified interval.
383
+ * Events include any state changes or interactions with the Sandbox through the sdk.
384
+ * Interactions using Sandbox Previews are not included.
385
+ *
386
+ * @param {number} interval - Number of minutes of inactivity before auto-stopping.
387
+ * Set to 0 to disable auto-stop. Default is 15 minutes.
388
+ * @returns {Promise<void>}
389
+ * @throws {DaytonaError} - `DaytonaError` - If interval is not a non-negative integer
390
+ *
391
+ * @example
392
+ * // Auto-stop after 1 hour
393
+ * await sandbox.setAutostopInterval(60);
394
+ * // Or disable auto-stop
395
+ * await sandbox.setAutostopInterval(0);
396
+ */
397
+ async setAutostopInterval(interval) {
398
+ if (!Number.isInteger(interval) || interval < 0) {
399
+ throw new DaytonaError_1.DaytonaError('autoStopInterval must be a non-negative integer');
400
+ }
401
+ await this.sandboxApi.setAutostopInterval(this.id, interval);
402
+ this.autoStopInterval = interval;
403
+ }
404
+ /**
405
+ * Set the auto-archive interval for the Sandbox.
406
+ *
407
+ * The Sandbox will automatically archive after being continuously stopped for the specified interval.
408
+ *
409
+ * @param {number} interval - Number of minutes after which a continuously stopped Sandbox will be auto-archived.
410
+ * Set to 0 for the maximum interval. Default is 7 days.
411
+ * @returns {Promise<void>}
412
+ * @throws {DaytonaError} - `DaytonaError` - If interval is not a non-negative integer
413
+ *
414
+ * @example
415
+ * // Auto-archive after 1 hour
416
+ * await sandbox.setAutoArchiveInterval(60);
417
+ * // Or use the maximum interval
418
+ * await sandbox.setAutoArchiveInterval(0);
419
+ */
420
+ async setAutoArchiveInterval(interval) {
421
+ if (!Number.isInteger(interval) || interval < 0) {
422
+ throw new DaytonaError_1.DaytonaError('autoArchiveInterval must be a non-negative integer');
423
+ }
424
+ await this.sandboxApi.setAutoArchiveInterval(this.id, interval);
425
+ this.autoArchiveInterval = interval;
426
+ }
427
+ /**
428
+ * Set the auto-delete interval for the Sandbox.
429
+ *
430
+ * The Sandbox will automatically delete after being continuously stopped for the specified interval.
431
+ *
432
+ * @param {number} interval - Number of minutes after which a continuously stopped Sandbox will be auto-deleted.
433
+ * Set to negative value to disable auto-delete. Set to 0 to delete immediately upon stopping.
434
+ * By default, auto-delete is disabled.
435
+ * @returns {Promise<void>}
436
+ *
437
+ * @example
438
+ * // Auto-delete after 1 hour
439
+ * await sandbox.setAutoDeleteInterval(60);
440
+ * // Or delete immediately upon stopping
441
+ * await sandbox.setAutoDeleteInterval(0);
442
+ * // Or disable auto-delete
443
+ * await sandbox.setAutoDeleteInterval(-1);
444
+ */
445
+ async setAutoDeleteInterval(interval) {
446
+ await this.sandboxApi.setAutoDeleteInterval(this.id, interval);
447
+ this.autoDeleteInterval = interval;
448
+ }
449
+ /**
450
+ * Retrieves the preview link for the sandbox at the specified port. If the port is closed,
451
+ * it will be opened automatically. For private sandboxes, a token is included to grant access
452
+ * to the URL.
453
+ *
454
+ * @param {number} port - The port to open the preview link on.
455
+ * @returns {PortPreviewUrl} The response object for the preview link, which includes the `url`
456
+ * and the `token` (to access private sandboxes).
457
+ *
458
+ * @example
459
+ * const previewLink = await sandbox.getPreviewLink(3000);
460
+ * console.log(`Preview URL: ${previewLink.url}`);
461
+ * console.log(`Token: ${previewLink.token}`);
462
+ */
463
+ async getPreviewLink(port) {
464
+ return (await this.sandboxApi.getPortPreviewUrl(this.id, port)).data;
465
+ }
466
+ /**
467
+ * Retrieves a signed preview url for the sandbox at the specified port.
468
+ *
469
+ * @param {number} port - The port to open the preview link on.
470
+ * @param {number} [expiresInSeconds] - The number of seconds the signed preview url will be valid for. Defaults to 60 seconds.
471
+ * @returns {Promise<SignedPortPreviewUrl>} The response object for the signed preview url.
472
+ */
473
+ async getSignedPreviewUrl(port, expiresInSeconds) {
474
+ return (await this.sandboxApi.getSignedPortPreviewUrl(this.id, port, undefined, expiresInSeconds)).data;
475
+ }
476
+ /**
477
+ * Expires a signed preview url for the sandbox at the specified port.
478
+ *
479
+ * @param {number} port - The port to expire the signed preview url on.
480
+ * @param {string} token - The token to expire the signed preview url on.
481
+ * @returns {Promise<void>}
482
+ */
483
+ async expireSignedPreviewUrl(port, token) {
484
+ await this.sandboxApi.expireSignedPortPreviewUrl(this.id, port, token);
485
+ }
486
+ /**
487
+ * Archives the sandbox, making it inactive and preserving its state. When sandboxes are archived, the entire filesystem
488
+ * state is moved to cost-effective object storage, making it possible to keep sandboxes available for an extended period.
489
+ * The tradeoff between archived and stopped states is that starting an archived sandbox takes more time, depending on its size.
490
+ * Sandbox must be stopped before archiving.
491
+ */
492
+ async archive() {
493
+ await this.sandboxApi.archiveSandbox(this.id);
494
+ await this.refreshData();
495
+ }
496
+ /**
497
+ * Resizes the Sandbox resources.
498
+ *
499
+ * Changes the CPU, memory, or disk allocation for the Sandbox. Hot resize (on running
500
+ * sandbox) only allows CPU/memory increases. Disk resize requires a stopped sandbox.
501
+ *
502
+ * @param {Resources} resources - New resource configuration. Only specified fields will be updated.
503
+ * - cpu: Number of CPU cores (minimum: 1). For hot resize, can only be increased.
504
+ * - memory: Memory in GiB (minimum: 1). For hot resize, can only be increased.
505
+ * - disk: Disk space in GiB (can only be increased, requires stopped sandbox).
506
+ * @param {number} [timeout=60] - Timeout in seconds for the resize operation. 0 means no timeout.
507
+ * @returns {Promise<void>}
508
+ * @throws {DaytonaError} - If hot resize constraints are violated, disk resize attempted on running sandbox,
509
+ * disk size decrease is attempted, no resource changes are specified, or resize operation times out.
510
+ *
511
+ * @example
512
+ * // Increase CPU/memory on running sandbox (hot resize)
513
+ * await sandbox.resize({ cpu: 4, memory: 8 });
514
+ *
515
+ * // Change disk (sandbox must be stopped)
516
+ * await sandbox.stop();
517
+ * await sandbox.resize({ cpu: 2, memory: 4, disk: 30 });
518
+ */
519
+ async resize(resources, timeout = 60) {
520
+ if (timeout < 0) {
521
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
522
+ }
523
+ const startTime = Date.now();
524
+ const resizeRequest = {
525
+ cpu: resources.cpu,
526
+ memory: resources.memory,
527
+ disk: resources.disk,
528
+ };
529
+ const response = await this.sandboxApi.resizeSandbox(this.id, resizeRequest, this.organizationId, {
530
+ timeout: timeout * 1000,
531
+ });
532
+ this.processSandboxDto(response.data);
533
+ const timeElapsed = Date.now() - startTime;
534
+ await this.waitForResizeComplete(timeout ? Math.max(0.001, timeout - timeElapsed / 1000) : timeout);
535
+ }
536
+ /**
537
+ * Waits for the Sandbox resize operation to complete.
538
+ *
539
+ * This method polls the Sandbox status until the state is no longer 'resizing'.
540
+ *
541
+ * @param {number} [timeout=60] - Maximum time to wait in seconds. 0 means no timeout.
542
+ * @returns {Promise<void>}
543
+ * @throws {DaytonaError} - If the sandbox ends up in an error state or resize times out.
544
+ */
545
+ async waitForResizeComplete(timeout = 60) {
546
+ if (timeout < 0) {
547
+ throw new DaytonaError_1.DaytonaError('Timeout must be a non-negative number');
548
+ }
549
+ let checkInterval = 100;
550
+ const startTime = Date.now();
551
+ while (this.state === api_client_1.SandboxState.RESIZING) {
552
+ await this.refreshData();
553
+ // @ts-expect-error this.refreshData() can modify this.state so this check is fine
554
+ if (this.state === api_client_1.SandboxState.ERROR || this.state === api_client_1.SandboxState.BUILD_FAILED) {
555
+ throw new DaytonaError_1.DaytonaError(`Sandbox ${this.id} resize failed with state: ${this.state}, error reason: ${this.errorReason}`);
556
+ }
557
+ if (this.state !== api_client_1.SandboxState.RESIZING) {
558
+ return;
559
+ }
560
+ if (timeout !== 0 && Date.now() - startTime > timeout * 1000) {
561
+ throw new DaytonaError_1.DaytonaError('Sandbox resize did not complete within the timeout period');
562
+ }
563
+ await new Promise((resolve) => setTimeout(resolve, checkInterval));
564
+ if (Date.now() - startTime > 5000) {
565
+ checkInterval = Math.min(checkInterval * 1.1, 1000);
566
+ }
567
+ }
568
+ }
569
+ /**
570
+ * Creates an SSH access token for the sandbox.
571
+ *
572
+ * @param {number} expiresInMinutes - The number of minutes the SSH access token will be valid for.
573
+ * @returns {Promise<SshAccessDto>} The SSH access token.
574
+ */
575
+ async createSshAccess(expiresInMinutes) {
576
+ return (await this.sandboxApi.createSshAccess(this.id, undefined, expiresInMinutes)).data;
577
+ }
578
+ /**
579
+ * Revokes an SSH access token for the sandbox.
580
+ *
581
+ * @param {string} token - The token to revoke.
582
+ * @returns {Promise<void>}
583
+ */
584
+ async revokeSshAccess(token) {
585
+ await this.sandboxApi.revokeSshAccess(this.id, undefined, token);
586
+ }
587
+ /**
588
+ * Validates an SSH access token for the sandbox.
589
+ *
590
+ * @param {string} token - The token to validate.
591
+ * @returns {Promise<SshAccessValidationDto>} The SSH access validation result.
592
+ */
593
+ async validateSshAccess(token) {
594
+ return (await this.sandboxApi.validateSshAccess(token)).data;
595
+ }
596
+ /**
597
+ * Assigns the API sandbox data to the Sandbox object.
598
+ *
599
+ * @param {SandboxDto} sandboxDto - The API sandbox instance to assign data from
600
+ * @returns {void}
601
+ */
602
+ processSandboxDto(sandboxDto) {
603
+ this.id = sandboxDto.id;
604
+ this.name = sandboxDto.name;
605
+ this.organizationId = sandboxDto.organizationId;
606
+ this.snapshot = sandboxDto.snapshot;
607
+ this.user = sandboxDto.user;
608
+ this.env = sandboxDto.env;
609
+ this.labels = sandboxDto.labels;
610
+ this.public = sandboxDto.public;
611
+ this.target = sandboxDto.target;
612
+ this.cpu = sandboxDto.cpu;
613
+ this.gpu = sandboxDto.gpu;
614
+ this.memory = sandboxDto.memory;
615
+ this.disk = sandboxDto.disk;
616
+ this.state = sandboxDto.state;
617
+ this.errorReason = sandboxDto.errorReason;
618
+ this.recoverable = sandboxDto.recoverable;
619
+ this.backupState = sandboxDto.backupState;
620
+ this.backupCreatedAt = sandboxDto.backupCreatedAt;
621
+ this.autoStopInterval = sandboxDto.autoStopInterval;
622
+ this.autoArchiveInterval = sandboxDto.autoArchiveInterval;
623
+ this.autoDeleteInterval = sandboxDto.autoDeleteInterval;
624
+ this.volumes = sandboxDto.volumes;
625
+ this.buildInfo = sandboxDto.buildInfo;
626
+ this.createdAt = sandboxDto.createdAt;
627
+ this.updatedAt = sandboxDto.updatedAt;
628
+ this.networkBlockAll = sandboxDto.networkBlockAll;
629
+ this.networkAllowList = sandboxDto.networkAllowList;
630
+ this.toolboxProxyUrl = sandboxDto.toolboxProxyUrl;
631
+ }
632
+ /**
633
+ * Refreshes the Sandbox data from the API, but does not throw an error if the sandbox has been deleted.
634
+ * Instead, it sets the state to destroyed.
635
+ *
636
+ * @returns {Promise<void>}
637
+ */
638
+ async refreshDataSafe() {
639
+ try {
640
+ await this.refreshData();
641
+ }
642
+ catch (error) {
643
+ if (error instanceof DaytonaError_1.DaytonaNotFoundError) {
644
+ this.state = api_client_1.SandboxState.DESTROYED;
645
+ }
646
+ }
647
+ }
648
+ }
649
+ exports.Sandbox = Sandbox;
650
+ tslib_1.__decorate([
651
+ (0, otel_decorator_1.WithInstrumentation)(),
652
+ tslib_1.__metadata("design:type", Function),
653
+ tslib_1.__metadata("design:paramtypes", []),
654
+ tslib_1.__metadata("design:returntype", Promise)
655
+ ], Sandbox.prototype, "getUserHomeDir", null);
656
+ tslib_1.__decorate([
657
+ (0, otel_decorator_1.WithInstrumentation)(),
658
+ tslib_1.__metadata("design:type", Function),
659
+ tslib_1.__metadata("design:paramtypes", []),
660
+ tslib_1.__metadata("design:returntype", Promise)
661
+ ], Sandbox.prototype, "getUserRootDir", null);
662
+ tslib_1.__decorate([
663
+ (0, otel_decorator_1.WithInstrumentation)(),
664
+ tslib_1.__metadata("design:type", Function),
665
+ tslib_1.__metadata("design:paramtypes", []),
666
+ tslib_1.__metadata("design:returntype", Promise)
667
+ ], Sandbox.prototype, "getWorkDir", null);
668
+ tslib_1.__decorate([
669
+ (0, otel_decorator_1.WithInstrumentation)(),
670
+ tslib_1.__metadata("design:type", Function),
671
+ tslib_1.__metadata("design:paramtypes", [String, String]),
672
+ tslib_1.__metadata("design:returntype", Promise)
673
+ ], Sandbox.prototype, "createLspServer", null);
674
+ tslib_1.__decorate([
675
+ (0, otel_decorator_1.WithInstrumentation)(),
676
+ tslib_1.__metadata("design:type", Function),
677
+ tslib_1.__metadata("design:paramtypes", [Object]),
678
+ tslib_1.__metadata("design:returntype", Promise)
679
+ ], Sandbox.prototype, "setLabels", null);
680
+ tslib_1.__decorate([
681
+ (0, otel_decorator_1.WithInstrumentation)(),
682
+ tslib_1.__metadata("design:type", Function),
683
+ tslib_1.__metadata("design:paramtypes", [Object]),
684
+ tslib_1.__metadata("design:returntype", Promise)
685
+ ], Sandbox.prototype, "start", null);
686
+ tslib_1.__decorate([
687
+ (0, otel_decorator_1.WithInstrumentation)(),
688
+ tslib_1.__metadata("design:type", Function),
689
+ tslib_1.__metadata("design:paramtypes", [Object, Object]),
690
+ tslib_1.__metadata("design:returntype", Promise)
691
+ ], Sandbox.prototype, "stop", null);
692
+ tslib_1.__decorate([
693
+ (0, otel_decorator_1.WithInstrumentation)(),
694
+ tslib_1.__metadata("design:type", Function),
695
+ tslib_1.__metadata("design:paramtypes", [Object]),
696
+ tslib_1.__metadata("design:returntype", Promise)
697
+ ], Sandbox.prototype, "delete", null);
698
+ tslib_1.__decorate([
699
+ (0, otel_decorator_1.WithInstrumentation)(),
700
+ tslib_1.__metadata("design:type", Function),
701
+ tslib_1.__metadata("design:paramtypes", [Object]),
702
+ tslib_1.__metadata("design:returntype", Promise)
703
+ ], Sandbox.prototype, "waitUntilStarted", null);
704
+ tslib_1.__decorate([
705
+ (0, otel_decorator_1.WithInstrumentation)(),
706
+ tslib_1.__metadata("design:type", Function),
707
+ tslib_1.__metadata("design:paramtypes", [Object]),
708
+ tslib_1.__metadata("design:returntype", Promise)
709
+ ], Sandbox.prototype, "waitUntilStopped", null);
710
+ tslib_1.__decorate([
711
+ (0, otel_decorator_1.WithInstrumentation)(),
712
+ tslib_1.__metadata("design:type", Function),
713
+ tslib_1.__metadata("design:paramtypes", []),
714
+ tslib_1.__metadata("design:returntype", Promise)
715
+ ], Sandbox.prototype, "refreshData", null);
716
+ tslib_1.__decorate([
717
+ (0, otel_decorator_1.WithInstrumentation)(),
718
+ tslib_1.__metadata("design:type", Function),
719
+ tslib_1.__metadata("design:paramtypes", [Number]),
720
+ tslib_1.__metadata("design:returntype", Promise)
721
+ ], Sandbox.prototype, "setAutostopInterval", null);
722
+ tslib_1.__decorate([
723
+ (0, otel_decorator_1.WithInstrumentation)(),
724
+ tslib_1.__metadata("design:type", Function),
725
+ tslib_1.__metadata("design:paramtypes", [Number]),
726
+ tslib_1.__metadata("design:returntype", Promise)
727
+ ], Sandbox.prototype, "setAutoArchiveInterval", null);
728
+ tslib_1.__decorate([
729
+ (0, otel_decorator_1.WithInstrumentation)(),
730
+ tslib_1.__metadata("design:type", Function),
731
+ tslib_1.__metadata("design:paramtypes", [Number]),
732
+ tslib_1.__metadata("design:returntype", Promise)
733
+ ], Sandbox.prototype, "setAutoDeleteInterval", null);
734
+ tslib_1.__decorate([
735
+ (0, otel_decorator_1.WithInstrumentation)(),
736
+ tslib_1.__metadata("design:type", Function),
737
+ tslib_1.__metadata("design:paramtypes", [Number]),
738
+ tslib_1.__metadata("design:returntype", Promise)
739
+ ], Sandbox.prototype, "getPreviewLink", null);
740
+ tslib_1.__decorate([
741
+ (0, otel_decorator_1.WithInstrumentation)(),
742
+ tslib_1.__metadata("design:type", Function),
743
+ tslib_1.__metadata("design:paramtypes", []),
744
+ tslib_1.__metadata("design:returntype", Promise)
745
+ ], Sandbox.prototype, "archive", null);
746
+ tslib_1.__decorate([
747
+ (0, otel_decorator_1.WithInstrumentation)(),
748
+ tslib_1.__metadata("design:type", Function),
749
+ tslib_1.__metadata("design:paramtypes", [Object, Object]),
750
+ tslib_1.__metadata("design:returntype", Promise)
751
+ ], Sandbox.prototype, "resize", null);
752
+ tslib_1.__decorate([
753
+ (0, otel_decorator_1.WithInstrumentation)(),
754
+ tslib_1.__metadata("design:type", Function),
755
+ tslib_1.__metadata("design:paramtypes", [Object]),
756
+ tslib_1.__metadata("design:returntype", Promise)
757
+ ], Sandbox.prototype, "waitForResizeComplete", null);
758
+ tslib_1.__decorate([
759
+ (0, otel_decorator_1.WithInstrumentation)(),
760
+ tslib_1.__metadata("design:type", Function),
761
+ tslib_1.__metadata("design:paramtypes", [Number]),
762
+ tslib_1.__metadata("design:returntype", Promise)
763
+ ], Sandbox.prototype, "createSshAccess", null);
764
+ tslib_1.__decorate([
765
+ (0, otel_decorator_1.WithInstrumentation)(),
766
+ tslib_1.__metadata("design:type", Function),
767
+ tslib_1.__metadata("design:paramtypes", [String]),
768
+ tslib_1.__metadata("design:returntype", Promise)
769
+ ], Sandbox.prototype, "revokeSshAccess", null);
770
+ tslib_1.__decorate([
771
+ (0, otel_decorator_1.WithInstrumentation)(),
772
+ tslib_1.__metadata("design:type", Function),
773
+ tslib_1.__metadata("design:paramtypes", [String]),
774
+ tslib_1.__metadata("design:returntype", Promise)
775
+ ], Sandbox.prototype, "validateSshAccess", null);
776
+ //# sourceMappingURL=Sandbox.js.map