@daytona/sdk 0.175.1-alpha.1 → 0.180.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 (93) hide show
  1. package/cjs/CodeInterpreter.d.ts +3 -2
  2. package/cjs/CodeInterpreter.js.map +1 -1
  3. package/cjs/ComputerUse.d.ts +104 -2
  4. package/cjs/ComputerUse.js +851 -763
  5. package/cjs/ComputerUse.js.map +1 -1
  6. package/cjs/Daytona.d.ts +10 -12
  7. package/cjs/Daytona.js +460 -442
  8. package/cjs/Daytona.js.map +1 -1
  9. package/cjs/FileSystem.d.ts +2 -2
  10. package/cjs/FileSystem.js +491 -521
  11. package/cjs/FileSystem.js.map +1 -1
  12. package/cjs/Git.d.ts +2 -1
  13. package/cjs/Git.js +287 -310
  14. package/cjs/Git.js.map +1 -1
  15. package/cjs/LspServer.d.ts +2 -1
  16. package/cjs/LspServer.js +209 -226
  17. package/cjs/LspServer.js.map +1 -1
  18. package/cjs/ObjectStorage.js +170 -166
  19. package/cjs/ObjectStorage.js.map +1 -1
  20. package/cjs/Process.d.ts +4 -3
  21. package/cjs/Process.js +562 -600
  22. package/cjs/Process.js.map +1 -1
  23. package/cjs/PtyHandle.d.ts +2 -2
  24. package/cjs/PtyHandle.js +327 -338
  25. package/cjs/PtyHandle.js.map +1 -1
  26. package/cjs/Sandbox.d.ts +103 -13
  27. package/cjs/Sandbox.js +769 -825
  28. package/cjs/Sandbox.js.map +1 -1
  29. package/cjs/Snapshot.d.ts +3 -2
  30. package/cjs/Snapshot.js +203 -213
  31. package/cjs/Snapshot.js.map +1 -1
  32. package/cjs/Volume.d.ts +2 -1
  33. package/cjs/Volume.js +90 -92
  34. package/cjs/Volume.js.map +1 -1
  35. package/cjs/errors/DaytonaError.d.ts +8 -3
  36. package/cjs/errors/DaytonaError.js +6 -2
  37. package/cjs/errors/DaytonaError.js.map +1 -1
  38. package/cjs/index.d.ts +4 -3
  39. package/cjs/index.js +4 -1
  40. package/cjs/index.js.map +1 -1
  41. package/cjs/types/CodeInterpreter.d.ts +1 -1
  42. package/cjs/utils/Binary.js +14 -2
  43. package/cjs/utils/Binary.js.map +1 -1
  44. package/cjs/utils/otel.decorator.d.ts +7 -8
  45. package/cjs/utils/otel.decorator.js +24 -30
  46. package/cjs/utils/otel.decorator.js.map +1 -1
  47. package/esm/CodeInterpreter.d.ts +3 -2
  48. package/esm/CodeInterpreter.js.map +1 -1
  49. package/esm/ComputerUse.d.ts +104 -2
  50. package/esm/ComputerUse.js +857 -763
  51. package/esm/ComputerUse.js.map +1 -1
  52. package/esm/Daytona.d.ts +10 -12
  53. package/esm/Daytona.js +462 -443
  54. package/esm/Daytona.js.map +1 -1
  55. package/esm/FileSystem.d.ts +2 -2
  56. package/esm/FileSystem.js +493 -522
  57. package/esm/FileSystem.js.map +1 -1
  58. package/esm/Git.d.ts +2 -1
  59. package/esm/Git.js +289 -311
  60. package/esm/Git.js.map +1 -1
  61. package/esm/LspServer.d.ts +2 -1
  62. package/esm/LspServer.js +211 -227
  63. package/esm/LspServer.js.map +1 -1
  64. package/esm/ObjectStorage.js +172 -167
  65. package/esm/ObjectStorage.js.map +1 -1
  66. package/esm/Process.d.ts +4 -3
  67. package/esm/Process.js +564 -601
  68. package/esm/Process.js.map +1 -1
  69. package/esm/PtyHandle.d.ts +2 -2
  70. package/esm/PtyHandle.js +329 -339
  71. package/esm/PtyHandle.js.map +1 -1
  72. package/esm/Sandbox.d.ts +103 -13
  73. package/esm/Sandbox.js +772 -827
  74. package/esm/Sandbox.js.map +1 -1
  75. package/esm/Snapshot.d.ts +3 -2
  76. package/esm/Snapshot.js +206 -215
  77. package/esm/Snapshot.js.map +1 -1
  78. package/esm/Volume.d.ts +2 -1
  79. package/esm/Volume.js +92 -93
  80. package/esm/Volume.js.map +1 -1
  81. package/esm/errors/DaytonaError.d.ts +8 -3
  82. package/esm/errors/DaytonaError.js +6 -2
  83. package/esm/errors/DaytonaError.js.map +1 -1
  84. package/esm/index.d.ts +4 -3
  85. package/esm/index.js +2 -2
  86. package/esm/index.js.map +1 -1
  87. package/esm/types/CodeInterpreter.d.ts +1 -1
  88. package/esm/utils/Binary.js +14 -2
  89. package/esm/utils/Binary.js.map +1 -1
  90. package/esm/utils/otel.decorator.d.ts +7 -8
  91. package/esm/utils/otel.decorator.js +26 -32
  92. package/esm/utils/otel.decorator.js.map +1 -1
  93. package/package.json +3 -3
package/cjs/Daytona.js CHANGED
@@ -61,474 +61,492 @@ var CodeLanguage;
61
61
  * });
62
62
  * @class
63
63
  */
64
- class Daytona {
65
- clientConfig;
66
- sandboxApi;
67
- objectStorageApi;
68
- configApi;
69
- target;
70
- apiKey;
71
- jwtToken;
72
- organizationId;
73
- apiUrl;
74
- otelSdk;
75
- volume;
76
- snapshot;
77
- /**
78
- * Creates a new Daytona client instance.
79
- *
80
- * @param {DaytonaConfig} [config] - Configuration options
81
- * @throws {DaytonaAuthenticationError} When no credentials are provided (neither API key nor JWT token)
82
- * @throws {DaytonaAuthenticationError} When JWT token is provided without an organization ID
83
- */
84
- constructor(config) {
85
- let apiUrl;
86
- if (config) {
87
- this.apiKey = !config?.apiKey && config?.jwtToken ? undefined : config?.apiKey;
88
- this.jwtToken = config?.jwtToken;
89
- this.organizationId = config?.organizationId;
90
- apiUrl = config?.apiUrl || config?.serverUrl;
91
- this.target = config?.target;
64
+ let Daytona = (() => {
65
+ let _instanceExtraInitializers = [];
66
+ let _create_decorators;
67
+ let _get_decorators;
68
+ let _start_decorators;
69
+ let _stop_decorators;
70
+ let __experimental_fork_decorators;
71
+ let _delete_decorators;
72
+ return class Daytona {
73
+ static {
74
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
75
+ _create_decorators = [(0, otel_decorator_1.WithInstrumentation)()];
76
+ _get_decorators = [(0, otel_decorator_1.WithInstrumentation)()];
77
+ _start_decorators = [(0, otel_decorator_1.WithInstrumentation)()];
78
+ _stop_decorators = [(0, otel_decorator_1.WithInstrumentation)()];
79
+ __experimental_fork_decorators = [(0, otel_decorator_1.WithInstrumentation)()];
80
+ _delete_decorators = [(0, otel_decorator_1.WithInstrumentation)()];
81
+ tslib_1.__esDecorate(this, null, _create_decorators, { kind: "method", name: "create", static: false, private: false, access: { has: obj => "create" in obj, get: obj => obj.create }, metadata: _metadata }, null, _instanceExtraInitializers);
82
+ tslib_1.__esDecorate(this, null, _get_decorators, { kind: "method", name: "get", static: false, private: false, access: { has: obj => "get" in obj, get: obj => obj.get }, metadata: _metadata }, null, _instanceExtraInitializers);
83
+ tslib_1.__esDecorate(this, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: obj => "start" in obj, get: obj => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers);
84
+ tslib_1.__esDecorate(this, null, _stop_decorators, { kind: "method", name: "stop", static: false, private: false, access: { has: obj => "stop" in obj, get: obj => obj.stop }, metadata: _metadata }, null, _instanceExtraInitializers);
85
+ tslib_1.__esDecorate(this, null, __experimental_fork_decorators, { kind: "method", name: "_experimental_fork", static: false, private: false, access: { has: obj => "_experimental_fork" in obj, get: obj => obj._experimental_fork }, metadata: _metadata }, null, _instanceExtraInitializers);
86
+ tslib_1.__esDecorate(this, null, _delete_decorators, { kind: "method", name: "delete", static: false, private: false, access: { has: obj => "delete" in obj, get: obj => obj.delete }, metadata: _metadata }, null, _instanceExtraInitializers);
87
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
92
88
  }
93
- let _envReader;
94
- const envReader = () => {
95
- if (_envReader === undefined) {
96
- _envReader = Runtime_1.RUNTIME !== Runtime_1.Runtime.BROWSER ? new Runtime_1.DaytonaEnvReader() : null;
89
+ clientConfig = tslib_1.__runInitializers(this, _instanceExtraInitializers);
90
+ sandboxApi;
91
+ objectStorageApi;
92
+ configApi;
93
+ target;
94
+ apiKey;
95
+ jwtToken;
96
+ organizationId;
97
+ apiUrl;
98
+ otelSdk;
99
+ volume;
100
+ snapshot;
101
+ /**
102
+ * Creates a new Daytona client instance.
103
+ *
104
+ * @param {DaytonaConfig} [config] - Configuration options
105
+ * @throws {DaytonaAuthenticationError} When no credentials are provided (neither API key nor JWT token)
106
+ * @throws {DaytonaAuthenticationError} When JWT token is provided without an organization ID
107
+ */
108
+ constructor(config) {
109
+ let apiUrl;
110
+ if (config) {
111
+ this.apiKey = !config?.apiKey && config?.jwtToken ? undefined : config?.apiKey;
112
+ this.jwtToken = config?.jwtToken;
113
+ this.organizationId = config?.organizationId;
114
+ apiUrl = config?.apiUrl || config?.serverUrl;
115
+ this.target = config?.target;
97
116
  }
98
- return _envReader;
99
- };
100
- if (!config ||
101
- (!(this.apiKey && apiUrl && this.target) && !(this.jwtToken && this.organizationId && apiUrl && this.target))) {
102
- const reader = envReader();
103
- if (reader) {
104
- this.apiKey = this.apiKey || (this.jwtToken ? undefined : reader.get('DAYTONA_API_KEY'));
105
- this.jwtToken = this.jwtToken || reader.get('DAYTONA_JWT_TOKEN');
106
- this.organizationId = this.organizationId || reader.get('DAYTONA_ORGANIZATION_ID');
107
- apiUrl = apiUrl || reader.get('DAYTONA_API_URL') || reader.get('DAYTONA_SERVER_URL');
108
- this.target = this.target || reader.get('DAYTONA_TARGET');
109
- if (reader.get('DAYTONA_SERVER_URL') && !reader.get('DAYTONA_API_URL')) {
110
- console.warn('[Deprecation Warning] Environment variable `DAYTONA_SERVER_URL` is deprecated and will be removed in future versions. Use `DAYTONA_API_URL` instead.');
117
+ let _envReader;
118
+ const envReader = () => {
119
+ if (_envReader === undefined) {
120
+ _envReader = Runtime_1.RUNTIME !== Runtime_1.Runtime.BROWSER ? new Runtime_1.DaytonaEnvReader() : null;
121
+ }
122
+ return _envReader;
123
+ };
124
+ if (!config ||
125
+ (!(this.apiKey && apiUrl && this.target) && !(this.jwtToken && this.organizationId && apiUrl && this.target))) {
126
+ const reader = envReader();
127
+ if (reader) {
128
+ this.apiKey = this.apiKey || (this.jwtToken ? undefined : reader.get('DAYTONA_API_KEY'));
129
+ this.jwtToken = this.jwtToken || reader.get('DAYTONA_JWT_TOKEN');
130
+ this.organizationId = this.organizationId || reader.get('DAYTONA_ORGANIZATION_ID');
131
+ apiUrl = apiUrl || reader.get('DAYTONA_API_URL') || reader.get('DAYTONA_SERVER_URL');
132
+ this.target = this.target || reader.get('DAYTONA_TARGET');
133
+ if (reader.get('DAYTONA_SERVER_URL') && !reader.get('DAYTONA_API_URL')) {
134
+ console.warn('[Deprecation Warning] Environment variable `DAYTONA_SERVER_URL` is deprecated and will be removed in future versions. Use `DAYTONA_API_URL` instead.');
135
+ }
111
136
  }
112
137
  }
113
- }
114
- this.apiUrl = apiUrl || 'https://app.daytona.io/api';
115
- if (!this.apiKey && !this.jwtToken) {
116
- throw new DaytonaError_1.DaytonaAuthenticationError('Authentication credentials not found. Set DAYTONA_API_KEY, or both DAYTONA_JWT_TOKEN and DAYTONA_ORGANIZATION_ID.' +
117
- ' These can also be provided via DaytonaConfig.');
118
- }
119
- const orgHeader = {};
120
- if (!this.apiKey) {
121
- if (!this.organizationId) {
122
- throw new DaytonaError_1.DaytonaAuthenticationError('DAYTONA_ORGANIZATION_ID is required when authenticating with DAYTONA_JWT_TOKEN.' +
123
- ' It can also be provided via DaytonaConfig.');
138
+ this.apiUrl = apiUrl || 'https://app.daytona.io/api';
139
+ if (!this.apiKey && !this.jwtToken) {
140
+ throw new DaytonaError_1.DaytonaAuthenticationError('Authentication credentials not found. Set DAYTONA_API_KEY, or both DAYTONA_JWT_TOKEN and DAYTONA_ORGANIZATION_ID.' +
141
+ ' These can also be provided via DaytonaConfig.');
124
142
  }
125
- orgHeader['X-Daytona-Organization-ID'] = this.organizationId;
126
- }
127
- const isLegacyPackage = packageJson.name === '@daytonaio/sdk';
128
- const sdkLabel = isLegacyPackage ? 'sdk-typescript-legacy' : 'sdk-typescript';
129
- const configuration = new api_client_1.Configuration({
130
- basePath: this.apiUrl,
131
- baseOptions: {
132
- headers: {
133
- Authorization: `Bearer ${this.apiKey || this.jwtToken}`,
134
- 'X-Daytona-Source': sdkLabel,
135
- 'X-Daytona-SDK-Version': packageJson.version,
136
- 'User-Agent': `${sdkLabel}/${packageJson.version}`,
137
- ...orgHeader,
143
+ const orgHeader = {};
144
+ if (!this.apiKey) {
145
+ if (!this.organizationId) {
146
+ throw new DaytonaError_1.DaytonaAuthenticationError('DAYTONA_ORGANIZATION_ID is required when authenticating with DAYTONA_JWT_TOKEN.' +
147
+ ' It can also be provided via DaytonaConfig.');
148
+ }
149
+ orgHeader['X-Daytona-Organization-ID'] = this.organizationId;
150
+ }
151
+ const isLegacyPackage = packageJson.name === '@daytonaio/sdk';
152
+ const sdkLabel = isLegacyPackage ? 'sdk-typescript-legacy' : 'sdk-typescript';
153
+ const configuration = new api_client_1.Configuration({
154
+ basePath: this.apiUrl,
155
+ baseOptions: {
156
+ headers: {
157
+ Authorization: `Bearer ${this.apiKey || this.jwtToken}`,
158
+ 'X-Daytona-Source': sdkLabel,
159
+ 'X-Daytona-SDK-Version': packageJson.version,
160
+ 'User-Agent': `${sdkLabel}/${packageJson.version}`,
161
+ ...orgHeader,
162
+ },
138
163
  },
139
- },
140
- });
141
- const axiosInstance = Daytona.createAxiosInstance();
142
- this.sandboxApi = new api_client_1.SandboxApi(configuration, '', axiosInstance);
143
- this.objectStorageApi = new api_client_1.ObjectStorageApi(configuration, '', axiosInstance);
144
- this.configApi = new api_client_1.ConfigApi(configuration, '', axiosInstance);
145
- this.volume = new Volume_1.VolumeService(new api_client_1.VolumesApi(configuration, '', axiosInstance));
146
- this.snapshot = new Snapshot_1.SnapshotService(configuration, new api_client_1.SnapshotsApi(configuration, '', axiosInstance), this.objectStorageApi, this.target);
147
- this.clientConfig = configuration;
148
- const env = envReader();
149
- const otelEnabled = config?.otelEnabled ||
150
- config?._experimental?.otelEnabled ||
151
- env?.get('DAYTONA_OTEL_ENABLED') === 'true' ||
152
- env?.get('DAYTONA_EXPERIMENTAL_OTEL_ENABLED') === 'true';
153
- if (!otelEnabled) {
154
- return;
155
- }
156
- const errPrefix = 'OpenTelemetry instrumentation is not supported: ';
157
- const { diag, DiagConsoleLogger, DiagLogLevel } = (0, Import_1.dynamicRequire)('@opentelemetry/api', errPrefix);
158
- const { NodeSDK } = (0, Import_1.dynamicRequire)('@opentelemetry/sdk-node', errPrefix);
159
- const { HttpInstrumentation } = (0, Import_1.dynamicRequire)('@opentelemetry/instrumentation-http', errPrefix);
160
- const { BatchSpanProcessor } = (0, Import_1.dynamicRequire)('@opentelemetry/sdk-trace-base', errPrefix);
161
- const { OTLPTraceExporter } = (0, Import_1.dynamicRequire)('@opentelemetry/exporter-trace-otlp-http', errPrefix);
162
- const { CompressionAlgorithm } = (0, Import_1.dynamicRequire)('@opentelemetry/otlp-exporter-base', errPrefix);
163
- const { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } = (0, Import_1.dynamicRequire)('@opentelemetry/semantic-conventions', errPrefix);
164
- const { resourceFromAttributes } = (0, Import_1.dynamicRequire)('@opentelemetry/resources', errPrefix);
165
- diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
166
- this.otelSdk = new NodeSDK({
167
- resource: resourceFromAttributes({
168
- [ATTR_SERVICE_VERSION]: packageJson.version,
169
- [ATTR_SERVICE_NAME]: 'daytona-typescript-sdk',
170
- }),
171
- instrumentations: [
172
- new HttpInstrumentation({
173
- requireParentforOutgoingSpans: false,
164
+ });
165
+ const axiosInstance = Daytona.createAxiosInstance();
166
+ this.sandboxApi = new api_client_1.SandboxApi(configuration, '', axiosInstance);
167
+ this.objectStorageApi = new api_client_1.ObjectStorageApi(configuration, '', axiosInstance);
168
+ this.configApi = new api_client_1.ConfigApi(configuration, '', axiosInstance);
169
+ this.volume = new Volume_1.VolumeService(new api_client_1.VolumesApi(configuration, '', axiosInstance));
170
+ this.snapshot = new Snapshot_1.SnapshotService(configuration, new api_client_1.SnapshotsApi(configuration, '', axiosInstance), this.objectStorageApi, this.target);
171
+ this.clientConfig = configuration;
172
+ const env = envReader();
173
+ const otelEnabled = config?.otelEnabled ||
174
+ config?._experimental?.otelEnabled ||
175
+ env?.get('DAYTONA_OTEL_ENABLED') === 'true' ||
176
+ env?.get('DAYTONA_EXPERIMENTAL_OTEL_ENABLED') === 'true';
177
+ if (!otelEnabled) {
178
+ return;
179
+ }
180
+ const errPrefix = 'OpenTelemetry instrumentation is not supported: ';
181
+ const { diag, DiagConsoleLogger, DiagLogLevel } = (0, Import_1.dynamicRequire)('@opentelemetry/api', errPrefix);
182
+ const { NodeSDK } = (0, Import_1.dynamicRequire)('@opentelemetry/sdk-node', errPrefix);
183
+ const { HttpInstrumentation } = (0, Import_1.dynamicRequire)('@opentelemetry/instrumentation-http', errPrefix);
184
+ const { BatchSpanProcessor } = (0, Import_1.dynamicRequire)('@opentelemetry/sdk-trace-base', errPrefix);
185
+ const { OTLPTraceExporter } = (0, Import_1.dynamicRequire)('@opentelemetry/exporter-trace-otlp-http', errPrefix);
186
+ const { CompressionAlgorithm } = (0, Import_1.dynamicRequire)('@opentelemetry/otlp-exporter-base', errPrefix);
187
+ const { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } = (0, Import_1.dynamicRequire)('@opentelemetry/semantic-conventions', errPrefix);
188
+ const { resourceFromAttributes } = (0, Import_1.dynamicRequire)('@opentelemetry/resources', errPrefix);
189
+ diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
190
+ this.otelSdk = new NodeSDK({
191
+ resource: resourceFromAttributes({
192
+ [ATTR_SERVICE_VERSION]: packageJson.version,
193
+ [ATTR_SERVICE_NAME]: 'daytona-typescript-sdk',
174
194
  }),
175
- ],
176
- spanProcessors: [
177
- new BatchSpanProcessor(new OTLPTraceExporter({
178
- compression: CompressionAlgorithm.GZIP,
179
- })),
180
- ],
181
- });
182
- this.otelSdk.start();
183
- // Flush and shutdown OTEL on process exit
184
- process.on('SIGTERM', async () => {
185
- await this.otelSdk?.shutdown();
186
- });
187
- }
188
- async [Symbol.asyncDispose]() {
189
- if (!this.otelSdk) {
190
- return;
191
- }
192
- await this.otelSdk.shutdown();
193
- }
194
- async create(params, options = { timeout: 60 }) {
195
- const startTime = Date.now();
196
- options = typeof options === 'number' ? { timeout: options } : { ...options };
197
- if (options.timeout == undefined || options.timeout == null) {
198
- options.timeout = 60;
199
- }
200
- if (params == null) {
201
- params = { language: 'python' };
202
- }
203
- if (!params.language) {
204
- params.language = 'python';
195
+ instrumentations: [
196
+ new HttpInstrumentation({
197
+ requireParentforOutgoingSpans: false,
198
+ }),
199
+ ],
200
+ spanProcessors: [
201
+ new BatchSpanProcessor(new OTLPTraceExporter({
202
+ compression: CompressionAlgorithm.GZIP,
203
+ })),
204
+ ],
205
+ });
206
+ this.otelSdk.start();
207
+ // Flush and shutdown OTEL on process exit
208
+ process.on('SIGTERM', async () => {
209
+ await this.otelSdk?.shutdown();
210
+ });
205
211
  }
206
- const labels = params.labels || {};
207
- if (params.language) {
208
- const validLanguages = Object.values(CodeLanguage);
209
- if (!validLanguages.includes(params.language)) {
210
- throw new DaytonaError_1.DaytonaValidationError(`Invalid ${exports.CODE_TOOLBOX_LANGUAGE_LABEL}: ${params.language}. Supported languages: ${validLanguages.join(', ')}`);
212
+ async [Symbol.asyncDispose]() {
213
+ if (!this.otelSdk) {
214
+ return;
211
215
  }
212
- labels[exports.CODE_TOOLBOX_LANGUAGE_LABEL] = params.language;
216
+ await this.otelSdk.shutdown();
213
217
  }
214
- if (options.timeout < 0) {
215
- throw new DaytonaError_1.DaytonaValidationError('Timeout must be a non-negative number');
216
- }
217
- if (params.autoStopInterval !== undefined &&
218
- (!Number.isInteger(params.autoStopInterval) || params.autoStopInterval < 0)) {
219
- throw new DaytonaError_1.DaytonaValidationError('autoStopInterval must be a non-negative integer');
220
- }
221
- if (params.ephemeral) {
222
- if (params.autoDeleteInterval !== undefined && params.autoDeleteInterval !== 0) {
223
- console.warn("'ephemeral' and 'autoDeleteInterval' cannot be used together. If ephemeral is true, autoDeleteInterval will be ignored and set to 0.");
218
+ async create(params, options = { timeout: 60 }) {
219
+ const startTime = Date.now();
220
+ options = typeof options === 'number' ? { timeout: options } : { ...options };
221
+ if (options.timeout == undefined || options.timeout == null) {
222
+ options.timeout = 60;
224
223
  }
225
- params.autoDeleteInterval = 0;
226
- }
227
- if (params.autoArchiveInterval !== undefined &&
228
- (!Number.isInteger(params.autoArchiveInterval) || params.autoArchiveInterval < 0)) {
229
- throw new DaytonaError_1.DaytonaValidationError('autoArchiveInterval must be a non-negative integer');
230
- }
231
- try {
232
- let buildInfo;
233
- let snapshot;
234
- let resources;
235
- if ('snapshot' in params) {
236
- snapshot = params.snapshot;
224
+ if (params == null) {
225
+ params = { language: 'python' };
237
226
  }
238
- if ('image' in params) {
239
- if (typeof params.image === 'string') {
240
- buildInfo = {
241
- dockerfileContent: Image_1.Image.base(params.image).dockerfile,
242
- };
227
+ if (!params.language) {
228
+ params.language = 'python';
229
+ }
230
+ const labels = params.labels || {};
231
+ if (params.language) {
232
+ const validLanguages = Object.values(CodeLanguage);
233
+ if (!validLanguages.includes(params.language)) {
234
+ throw new DaytonaError_1.DaytonaValidationError(`Invalid ${exports.CODE_TOOLBOX_LANGUAGE_LABEL}: ${params.language}. Supported languages: ${validLanguages.join(', ')}`);
243
235
  }
244
- else if (params.image instanceof Image_1.Image) {
245
- const contextHashes = await Snapshot_1.SnapshotService.processImageContext(this.objectStorageApi, params.image);
246
- buildInfo = {
247
- contextHashes,
248
- dockerfileContent: params.image.dockerfile,
249
- };
236
+ labels[exports.CODE_TOOLBOX_LANGUAGE_LABEL] = params.language;
237
+ }
238
+ if (options.timeout < 0) {
239
+ throw new DaytonaError_1.DaytonaValidationError('Timeout must be a non-negative number');
240
+ }
241
+ if (params.autoStopInterval !== undefined &&
242
+ (!Number.isInteger(params.autoStopInterval) || params.autoStopInterval < 0)) {
243
+ throw new DaytonaError_1.DaytonaValidationError('autoStopInterval must be a non-negative integer');
244
+ }
245
+ if (params.ephemeral) {
246
+ if (params.autoDeleteInterval !== undefined && params.autoDeleteInterval !== 0) {
247
+ console.warn("'ephemeral' and 'autoDeleteInterval' cannot be used together. If ephemeral is true, autoDeleteInterval will be ignored and set to 0.");
250
248
  }
249
+ params.autoDeleteInterval = 0;
251
250
  }
252
- if ('resources' in params) {
253
- resources = params.resources;
251
+ if (params.autoArchiveInterval !== undefined &&
252
+ (!Number.isInteger(params.autoArchiveInterval) || params.autoArchiveInterval < 0)) {
253
+ throw new DaytonaError_1.DaytonaValidationError('autoArchiveInterval must be a non-negative integer');
254
254
  }
255
- const response = await this.sandboxApi.createSandbox({
256
- name: params.name,
257
- snapshot: snapshot,
258
- buildInfo,
259
- user: params.user,
260
- env: params.envVars || {},
261
- labels: labels,
262
- public: params.public,
263
- target: this.target,
264
- cpu: resources?.cpu,
265
- gpu: resources?.gpu,
266
- memory: resources?.memory,
267
- disk: resources?.disk,
268
- autoStopInterval: params.autoStopInterval,
269
- autoArchiveInterval: params.autoArchiveInterval,
270
- autoDeleteInterval: params.autoDeleteInterval,
271
- volumes: params.volumes,
272
- networkBlockAll: params.networkBlockAll,
273
- networkAllowList: params.networkAllowList,
274
- }, undefined, {
275
- timeout: options.timeout * 1000,
276
- });
277
- let sandboxInstance = response.data;
278
- if (sandboxInstance.state === api_client_1.SandboxState.PENDING_BUILD && options.onSnapshotCreateLogs) {
279
- const terminalStates = [
280
- api_client_1.SandboxState.STARTED,
281
- api_client_1.SandboxState.STARTING,
282
- api_client_1.SandboxState.ERROR,
283
- api_client_1.SandboxState.BUILD_FAILED,
284
- ];
285
- while (sandboxInstance.state === api_client_1.SandboxState.PENDING_BUILD) {
286
- if (options.timeout) {
287
- const elapsed = (Date.now() - startTime) / 1000;
288
- if (elapsed > options.timeout) {
289
- throw new DaytonaError_1.DaytonaTimeoutError(`Sandbox build has been pending for more than ${options.timeout} seconds. Please check the sandbox state again later.`);
290
- }
255
+ try {
256
+ let buildInfo;
257
+ let snapshot;
258
+ let resources;
259
+ if ('snapshot' in params) {
260
+ snapshot = params.snapshot;
261
+ }
262
+ if ('image' in params) {
263
+ if (typeof params.image === 'string') {
264
+ buildInfo = {
265
+ dockerfileContent: Image_1.Image.base(params.image).dockerfile,
266
+ };
267
+ }
268
+ else if (params.image instanceof Image_1.Image) {
269
+ const contextHashes = await Snapshot_1.SnapshotService.processImageContext(this.objectStorageApi, params.image);
270
+ buildInfo = {
271
+ contextHashes,
272
+ dockerfileContent: params.image.dockerfile,
273
+ };
291
274
  }
292
- await new Promise((resolve) => setTimeout(resolve, 1000));
293
- sandboxInstance = (await this.sandboxApi.getSandbox(sandboxInstance.id)).data;
294
275
  }
295
- const response = await this.sandboxApi.getBuildLogsUrl(sandboxInstance.id);
296
- await (0, Stream_1.processStreamingResponse)(() => fetch(response.data.url + '?follow=true', {
297
- method: 'GET',
298
- headers: this.clientConfig.baseOptions.headers,
299
- }), (chunk) => options.onSnapshotCreateLogs?.(chunk.trimEnd()), async () => {
300
- sandboxInstance = (await this.sandboxApi.getSandbox(sandboxInstance.id)).data;
301
- return sandboxInstance.state !== undefined && terminalStates.includes(sandboxInstance.state);
276
+ if ('resources' in params) {
277
+ resources = params.resources;
278
+ }
279
+ const response = await this.sandboxApi.createSandbox({
280
+ name: params.name,
281
+ snapshot: snapshot,
282
+ buildInfo,
283
+ user: params.user,
284
+ env: params.envVars || {},
285
+ labels: labels,
286
+ public: params.public,
287
+ target: this.target,
288
+ cpu: resources?.cpu,
289
+ gpu: resources?.gpu,
290
+ memory: resources?.memory,
291
+ disk: resources?.disk,
292
+ autoStopInterval: params.autoStopInterval,
293
+ autoArchiveInterval: params.autoArchiveInterval,
294
+ autoDeleteInterval: params.autoDeleteInterval,
295
+ volumes: params.volumes,
296
+ networkBlockAll: params.networkBlockAll,
297
+ networkAllowList: params.networkAllowList,
298
+ }, undefined, {
299
+ timeout: options.timeout * 1000,
302
300
  });
301
+ let sandboxInstance = response.data;
302
+ if (sandboxInstance.state === api_client_1.SandboxState.PENDING_BUILD && options.onSnapshotCreateLogs) {
303
+ const terminalStates = [
304
+ api_client_1.SandboxState.STARTED,
305
+ api_client_1.SandboxState.STARTING,
306
+ api_client_1.SandboxState.ERROR,
307
+ api_client_1.SandboxState.BUILD_FAILED,
308
+ ];
309
+ while (sandboxInstance.state === api_client_1.SandboxState.PENDING_BUILD) {
310
+ if (options.timeout) {
311
+ const elapsed = (Date.now() - startTime) / 1000;
312
+ if (elapsed > options.timeout) {
313
+ throw new DaytonaError_1.DaytonaTimeoutError(`Sandbox build has been pending for more than ${options.timeout} seconds. Please check the sandbox state again later.`);
314
+ }
315
+ }
316
+ await new Promise((resolve) => setTimeout(resolve, 1000));
317
+ sandboxInstance = (await this.sandboxApi.getSandbox(sandboxInstance.id)).data;
318
+ }
319
+ const response = await this.sandboxApi.getBuildLogsUrl(sandboxInstance.id);
320
+ await (0, Stream_1.processStreamingResponse)(() => fetch(response.data.url + '?follow=true', {
321
+ method: 'GET',
322
+ headers: this.clientConfig.baseOptions.headers,
323
+ }), (chunk) => options.onSnapshotCreateLogs?.(chunk.trimEnd()), async () => {
324
+ sandboxInstance = (await this.sandboxApi.getSandbox(sandboxInstance.id)).data;
325
+ return sandboxInstance.state !== undefined && terminalStates.includes(sandboxInstance.state);
326
+ });
327
+ }
328
+ const sandbox = new Sandbox_1.Sandbox(sandboxInstance, new api_client_1.Configuration(structuredClone(this.clientConfig)), Daytona.createAxiosInstance(), this.sandboxApi);
329
+ if (sandbox.state !== 'started') {
330
+ const timeElapsed = Date.now() - startTime;
331
+ await sandbox.waitUntilStarted(options.timeout ? Math.max(0.001, options.timeout - timeElapsed / 1000) : options.timeout);
332
+ }
333
+ return sandbox;
303
334
  }
304
- const sandbox = new Sandbox_1.Sandbox(sandboxInstance, new api_client_1.Configuration(structuredClone(this.clientConfig)), Daytona.createAxiosInstance(), this.sandboxApi);
305
- if (sandbox.state !== 'started') {
306
- const timeElapsed = Date.now() - startTime;
307
- await sandbox.waitUntilStarted(options.timeout ? Math.max(0.001, options.timeout - timeElapsed / 1000) : options.timeout);
335
+ catch (error) {
336
+ if (error instanceof DaytonaError_1.DaytonaTimeoutError) {
337
+ const errMsg = `Failed to create and start sandbox within ${options.timeout} seconds. Operation timed out.`;
338
+ throw new DaytonaError_1.DaytonaTimeoutError(errMsg, error.statusCode, error.headers, error.errorCode);
339
+ }
340
+ throw error;
308
341
  }
309
- return sandbox;
310
342
  }
311
- catch (error) {
312
- if (error instanceof DaytonaError_1.DaytonaTimeoutError) {
313
- const errMsg = `Failed to create and start sandbox within ${options.timeout} seconds. Operation timed out.`;
314
- throw new DaytonaError_1.DaytonaTimeoutError(errMsg, error.statusCode, error.headers, error.errorCode);
315
- }
316
- throw error;
343
+ /**
344
+ * Gets a Sandbox by its ID or name.
345
+ *
346
+ * @param {string} sandboxIdOrName - The ID or name of the Sandbox to retrieve
347
+ * @returns {Promise<Sandbox>} The Sandbox
348
+ *
349
+ * @example
350
+ * const sandbox = await daytona.get('my-sandbox-id-or-name');
351
+ * console.log(`Sandbox state: ${sandbox.state}`);
352
+ */
353
+ async get(sandboxIdOrName) {
354
+ const response = await this.sandboxApi.getSandbox(sandboxIdOrName);
355
+ const sandboxInstance = response.data;
356
+ return new Sandbox_1.Sandbox(sandboxInstance, structuredClone(this.clientConfig), Daytona.createAxiosInstance(), this.sandboxApi);
317
357
  }
318
- }
319
- /**
320
- * Gets a Sandbox by its ID or name.
321
- *
322
- * @param {string} sandboxIdOrName - The ID or name of the Sandbox to retrieve
323
- * @returns {Promise<Sandbox>} The Sandbox
324
- *
325
- * @example
326
- * const sandbox = await daytona.get('my-sandbox-id-or-name');
327
- * console.log(`Sandbox state: ${sandbox.state}`);
328
- */
329
- async get(sandboxIdOrName) {
330
- const response = await this.sandboxApi.getSandbox(sandboxIdOrName);
331
- const sandboxInstance = response.data;
332
- return new Sandbox_1.Sandbox(sandboxInstance, structuredClone(this.clientConfig), Daytona.createAxiosInstance(), this.sandboxApi);
333
- }
334
- /**
335
- * Returns paginated list of Sandboxes filtered by labels.
336
- *
337
- * @param {Record<string, string>} [labels] - Labels to filter Sandboxes
338
- * @param {number} [page] - Page number for pagination (starting from 1)
339
- * @param {number} [limit] - Maximum number of items per page
340
- * @returns {Promise<PaginatedSandboxes>} Paginated list of Sandboxes that match the labels.
341
- *
342
- * @example
343
- * const result = await daytona.list({ 'my-label': 'my-value' }, 2, 10);
344
- * for (const sandbox of result.items) {
345
- * console.log(`${sandbox.id}: ${sandbox.state}`);
346
- * }
347
- */
348
- async list(labels, page, limit) {
349
- const response = await this.sandboxApi.listSandboxesPaginated(undefined, page, limit, undefined, undefined, labels ? JSON.stringify(labels) : undefined);
350
- return {
351
- items: response.data.items.map((sandbox) => {
352
- return new Sandbox_1.Sandbox(sandbox, structuredClone(this.clientConfig), Daytona.createAxiosInstance(), this.sandboxApi);
353
- }),
354
- total: response.data.total,
355
- page: response.data.page,
356
- totalPages: response.data.totalPages,
357
- };
358
- }
359
- /**
360
- * Starts a Sandbox and waits for it to be ready.
361
- *
362
- * @param {Sandbox} sandbox - The Sandbox to start
363
- * @param {number} [timeout] - Optional timeout in seconds (0 means no timeout)
364
- * @returns {Promise<void>}
365
- *
366
- * @example
367
- * const sandbox = await daytona.get('my-sandbox-id');
368
- * // Wait up to 60 seconds for the sandbox to start
369
- * await daytona.start(sandbox, 60);
370
- */
371
- async start(sandbox, timeout) {
372
- await sandbox.start(timeout);
373
- }
374
- /**
375
- * Stops a Sandbox.
376
- *
377
- * @param {Sandbox} sandbox - The Sandbox to stop
378
- * @returns {Promise<void>}
379
- *
380
- * @example
381
- * const sandbox = await daytona.get('my-sandbox-id');
382
- * await daytona.stop(sandbox);
383
- */
384
- async stop(sandbox) {
385
- await sandbox.stop();
386
- }
387
- /**
388
- * Forks a Sandbox, creating a new Sandbox with an identical filesystem.
389
- *
390
- * @param {Sandbox} sandbox - The Sandbox to fork
391
- * @param {object} [params] - Fork parameters
392
- * @param {string} [params.name] - Optional name for the forked Sandbox
393
- * @param {number} [timeout] - Timeout in seconds (0 means no timeout, default is 60)
394
- * @returns {Promise<Sandbox>} The forked Sandbox
395
- *
396
- * @example
397
- * const sandbox = await daytona.get('my-sandbox-id');
398
- * const forked = await daytona._experimental_fork(sandbox, { name: 'my-fork' });
399
- * console.log(`Forked sandbox: ${forked.id}`);
400
- */
401
- async _experimental_fork(sandbox, params, timeout = 60) {
402
- return await sandbox._experimental_fork(params, timeout);
403
- }
404
- /**
405
- * Deletes a Sandbox.
406
- *
407
- * @param {Sandbox} sandbox - The Sandbox to delete
408
- * @param {number} timeout - Timeout in seconds (0 means no timeout, default is 60)
409
- * @returns {Promise<void>}
410
- *
411
- * @example
412
- * const sandbox = await daytona.get('my-sandbox-id');
413
- * await daytona.delete(sandbox);
414
- */
415
- async delete(sandbox, timeout = 60) {
416
- await sandbox.delete(timeout);
417
- }
418
- /**
419
- * @hidden
420
- */
421
- static createAxiosInstance() {
422
- const axiosInstance = axios_1.default.create({
423
- timeout: 24 * 60 * 60 * 1000, // 24 hours
424
- });
425
- // Request interceptor: Inject trace context into headers
426
- axiosInstance.interceptors.request.use((requestConfig) => {
427
- // Get the current active context (which may contain an active span)
428
- const currentContext = api_1.context.active();
429
- // Inject trace context into HTTP headers using W3C Trace Context propagation
430
- // This adds headers like 'traceparent' and 'tracestate'
431
- api_1.propagation.inject(currentContext, requestConfig.headers);
432
- requestConfig.metadata = { startTime: Date.now() };
433
- return requestConfig;
434
- }, (error) => {
435
- return Promise.reject(error);
436
- });
437
- axiosInstance.interceptors.response.use((response) => {
438
- return response;
439
- }, (error) => {
440
- if (error instanceof axios_1.AxiosError) {
441
- throw (0, DaytonaError_1.createAxiosDaytonaError)(error);
442
- }
443
- throw new DaytonaError_1.DaytonaError(error instanceof Error ? error.message : String(error));
444
- });
445
- axiosInstance.interceptors.response.use((response) => {
446
- const startTime = response.config.metadata?.startTime;
447
- if (startTime) {
448
- const duration = Date.now() - startTime;
449
- // Get the active span to add attributes
450
- const activeSpan = api_1.trace.getActiveSpan();
451
- // Only modify the span if it's still recording (not ended)
452
- if (activeSpan && activeSpan.isRecording()) {
453
- // Add response metadata to the span
454
- activeSpan.setAttributes({
455
- 'http.response.status_code': response.status,
456
- 'http.response.duration_ms': duration,
457
- // 'http.response.size_bytes': JSON.stringify(response.data).length,
458
- });
358
+ /**
359
+ * Iterates over Sandboxes matching the given query.
360
+ *
361
+ * @param {ListSandboxesQuery} [query] - Optional filters, sorting, and per-page size.
362
+ * @returns {AsyncIterableIterator<Sandbox>}
363
+ *
364
+ * @example
365
+ * for await (const sandbox of daytona.list({ labels: { env: 'dev' } })) {
366
+ * console.log(sandbox.id)
367
+ * }
368
+ */
369
+ list(query) {
370
+ const { sandboxApi, clientConfig } = this;
371
+ const tracer = api_1.trace.getTracer('');
372
+ // Clone once per list() call — the config is read-only after construction
373
+ // and each Sandbox holds its own reference; cloning per page or per item
374
+ // would be wasteful.
375
+ const clonedConfig = structuredClone(clientConfig);
376
+ async function* generator() {
377
+ let cursor = undefined;
378
+ let firstPage = true;
379
+ while (true) {
380
+ // Stop only when we've fetched at least one page and there's no further cursor.
381
+ if (!firstPage && !cursor) {
382
+ break;
383
+ }
384
+ const span = tracer.startSpan('Daytona.list.fetchPage', {
385
+ attributes: {
386
+ component: 'Daytona',
387
+ method: 'list',
388
+ },
389
+ }, api_1.context.active());
390
+ let response;
391
+ try {
392
+ response = await api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => sandboxApi.listSandboxes(undefined, cursor, query?.limit, query?.id, query?.name, query?.labels ? JSON.stringify(query.labels) : undefined, undefined, query?.states, query?.snapshots, query?.targets, query?.minCpu, query?.maxCpu, query?.minMemoryGib, query?.maxMemoryGib, query?.minDiskGib, query?.maxDiskGib, query?.isPublic, query?.isRecoverable, query?.createdAtAfter, query?.createdAtBefore, query?.lastActivityAfter, query?.lastActivityBefore, query?.sort, query?.order));
393
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
394
+ }
395
+ catch (error) {
396
+ span.setStatus({
397
+ code: api_1.SpanStatusCode.ERROR,
398
+ message: error instanceof Error ? error.message : String(error),
399
+ });
400
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
401
+ throw error;
402
+ }
403
+ finally {
404
+ span.end();
405
+ }
406
+ firstPage = false;
407
+ for (const sandbox of response.data.items) {
408
+ yield new Sandbox_1.Sandbox(sandbox, clonedConfig, Daytona.createAxiosInstance(), sandboxApi);
409
+ }
410
+ cursor = response.data.nextCursor ?? undefined;
411
+ if (!cursor) {
412
+ break;
413
+ }
459
414
  }
460
415
  }
461
- return response;
462
- }, (error) => {
463
- const startTime = error.config?.metadata?.startTime;
464
- if (startTime) {
465
- const duration = Date.now() - startTime;
466
- // Get the active span to record the error
467
- const activeSpan = api_1.trace.getActiveSpan();
468
- // Only modify the span if it's still recording (not ended)
469
- if (activeSpan && activeSpan.isRecording()) {
470
- activeSpan.setStatus({
471
- code: api_1.SpanStatusCode.ERROR,
472
- message: error.message,
473
- });
474
- activeSpan.setAttributes({
475
- 'http.response.duration_ms': duration,
476
- 'error.type': error.name,
477
- 'error.message': error.message,
478
- });
479
- if (error.response) {
480
- activeSpan.setAttribute('http.response.status_code', error.response.status);
416
+ return generator();
417
+ }
418
+ /**
419
+ * Starts a Sandbox and waits for it to be ready.
420
+ *
421
+ * @param {Sandbox} sandbox - The Sandbox to start
422
+ * @param {number} [timeout] - Optional timeout in seconds (0 means no timeout)
423
+ * @returns {Promise<void>}
424
+ *
425
+ * @example
426
+ * const sandbox = await daytona.get('my-sandbox-id');
427
+ * // Wait up to 60 seconds for the sandbox to start
428
+ * await daytona.start(sandbox, 60);
429
+ */
430
+ async start(sandbox, timeout) {
431
+ await sandbox.start(timeout);
432
+ }
433
+ /**
434
+ * Stops a Sandbox.
435
+ *
436
+ * @param {Sandbox} sandbox - The Sandbox to stop
437
+ * @returns {Promise<void>}
438
+ *
439
+ * @example
440
+ * const sandbox = await daytona.get('my-sandbox-id');
441
+ * await daytona.stop(sandbox);
442
+ */
443
+ async stop(sandbox) {
444
+ await sandbox.stop();
445
+ }
446
+ /**
447
+ * Forks a Sandbox, creating a new Sandbox with an identical filesystem.
448
+ *
449
+ * @param {Sandbox} sandbox - The Sandbox to fork
450
+ * @param {object} [params] - Fork parameters
451
+ * @param {string} [params.name] - Optional name for the forked Sandbox
452
+ * @param {number} [timeout] - Timeout in seconds (0 means no timeout, default is 60)
453
+ * @returns {Promise<Sandbox>} The forked Sandbox
454
+ *
455
+ * @example
456
+ * const sandbox = await daytona.get('my-sandbox-id');
457
+ * const forked = await daytona._experimental_fork(sandbox, { name: 'my-fork' });
458
+ * console.log(`Forked sandbox: ${forked.id}`);
459
+ */
460
+ async _experimental_fork(sandbox, params, timeout = 60) {
461
+ return await sandbox._experimental_fork(params, timeout);
462
+ }
463
+ /**
464
+ * Deletes a Sandbox.
465
+ *
466
+ * @param {Sandbox} sandbox - The Sandbox to delete
467
+ * @param {number} timeout - Timeout in seconds (0 means no timeout, default is 60)
468
+ * @returns {Promise<void>}
469
+ *
470
+ * @example
471
+ * const sandbox = await daytona.get('my-sandbox-id');
472
+ * await daytona.delete(sandbox);
473
+ */
474
+ async delete(sandbox, timeout = 60) {
475
+ await sandbox.delete(timeout);
476
+ }
477
+ /**
478
+ * @hidden
479
+ */
480
+ static createAxiosInstance() {
481
+ const axiosInstance = axios_1.default.create({
482
+ timeout: 24 * 60 * 60 * 1000, // 24 hours
483
+ });
484
+ // Request interceptor: Inject trace context into headers
485
+ axiosInstance.interceptors.request.use((requestConfig) => {
486
+ // Get the current active context (which may contain an active span)
487
+ const currentContext = api_1.context.active();
488
+ // Inject trace context into HTTP headers using W3C Trace Context propagation
489
+ // This adds headers like 'traceparent' and 'tracestate'
490
+ api_1.propagation.inject(currentContext, requestConfig.headers);
491
+ requestConfig.metadata = { startTime: Date.now() };
492
+ return requestConfig;
493
+ }, (error) => {
494
+ return Promise.reject(error);
495
+ });
496
+ axiosInstance.interceptors.response.use((response) => {
497
+ return response;
498
+ }, (error) => {
499
+ if (error instanceof axios_1.AxiosError) {
500
+ throw (0, DaytonaError_1.createAxiosDaytonaError)(error);
501
+ }
502
+ throw new DaytonaError_1.DaytonaError(error instanceof Error ? error.message : String(error));
503
+ });
504
+ axiosInstance.interceptors.response.use((response) => {
505
+ const startTime = response.config.metadata?.startTime;
506
+ if (startTime) {
507
+ const duration = Date.now() - startTime;
508
+ // Get the active span to add attributes
509
+ const activeSpan = api_1.trace.getActiveSpan();
510
+ // Only modify the span if it's still recording (not ended)
511
+ if (activeSpan && activeSpan.isRecording()) {
512
+ // Add response metadata to the span
513
+ activeSpan.setAttributes({
514
+ 'http.response.status_code': response.status,
515
+ 'http.response.duration_ms': duration,
516
+ // 'http.response.size_bytes': JSON.stringify(response.data).length,
517
+ });
481
518
  }
482
- // Record the exception on the span
483
- activeSpan.recordException(error);
484
519
  }
485
- }
486
- return Promise.reject(error);
487
- });
488
- return axiosInstance;
489
- }
490
- }
520
+ return response;
521
+ }, (error) => {
522
+ const startTime = error.config?.metadata?.startTime;
523
+ if (startTime) {
524
+ const duration = Date.now() - startTime;
525
+ // Get the active span to record the error
526
+ const activeSpan = api_1.trace.getActiveSpan();
527
+ // Only modify the span if it's still recording (not ended)
528
+ if (activeSpan && activeSpan.isRecording()) {
529
+ activeSpan.setStatus({
530
+ code: api_1.SpanStatusCode.ERROR,
531
+ message: error.message,
532
+ });
533
+ activeSpan.setAttributes({
534
+ 'http.response.duration_ms': duration,
535
+ 'error.type': error.name,
536
+ 'error.message': error.message,
537
+ });
538
+ if (error.response) {
539
+ activeSpan.setAttribute('http.response.status_code', error.response.status);
540
+ }
541
+ // Record the exception on the span
542
+ activeSpan.recordException(error);
543
+ }
544
+ }
545
+ return Promise.reject(error);
546
+ });
547
+ return axiosInstance;
548
+ }
549
+ };
550
+ })();
491
551
  exports.Daytona = Daytona;
492
- tslib_1.__decorate([
493
- (0, otel_decorator_1.WithInstrumentation)(),
494
- tslib_1.__metadata("design:type", Function),
495
- tslib_1.__metadata("design:paramtypes", [Object, Object]),
496
- tslib_1.__metadata("design:returntype", Promise)
497
- ], Daytona.prototype, "create", null);
498
- tslib_1.__decorate([
499
- (0, otel_decorator_1.WithInstrumentation)(),
500
- tslib_1.__metadata("design:type", Function),
501
- tslib_1.__metadata("design:paramtypes", [String]),
502
- tslib_1.__metadata("design:returntype", Promise)
503
- ], Daytona.prototype, "get", null);
504
- tslib_1.__decorate([
505
- (0, otel_decorator_1.WithInstrumentation)(),
506
- tslib_1.__metadata("design:type", Function),
507
- tslib_1.__metadata("design:paramtypes", [Object, Number, Number]),
508
- tslib_1.__metadata("design:returntype", Promise)
509
- ], Daytona.prototype, "list", null);
510
- tslib_1.__decorate([
511
- (0, otel_decorator_1.WithInstrumentation)(),
512
- tslib_1.__metadata("design:type", Function),
513
- tslib_1.__metadata("design:paramtypes", [Sandbox_1.Sandbox, Number]),
514
- tslib_1.__metadata("design:returntype", Promise)
515
- ], Daytona.prototype, "start", null);
516
- tslib_1.__decorate([
517
- (0, otel_decorator_1.WithInstrumentation)(),
518
- tslib_1.__metadata("design:type", Function),
519
- tslib_1.__metadata("design:paramtypes", [Sandbox_1.Sandbox]),
520
- tslib_1.__metadata("design:returntype", Promise)
521
- ], Daytona.prototype, "stop", null);
522
- tslib_1.__decorate([
523
- (0, otel_decorator_1.WithInstrumentation)(),
524
- tslib_1.__metadata("design:type", Function),
525
- tslib_1.__metadata("design:paramtypes", [Sandbox_1.Sandbox, Object, Object]),
526
- tslib_1.__metadata("design:returntype", Promise)
527
- ], Daytona.prototype, "_experimental_fork", null);
528
- tslib_1.__decorate([
529
- (0, otel_decorator_1.WithInstrumentation)(),
530
- tslib_1.__metadata("design:type", Function),
531
- tslib_1.__metadata("design:paramtypes", [Sandbox_1.Sandbox, Object]),
532
- tslib_1.__metadata("design:returntype", Promise)
533
- ], Daytona.prototype, "delete", null);
534
552
  //# sourceMappingURL=Daytona.js.map