@daytona/sdk 0.175.1-alpha.1 → 0.179.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) 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 +4 -3
  7. package/cjs/Daytona.js +429 -443
  8. package/cjs/Daytona.js.map +1 -1
  9. package/cjs/FileSystem.d.ts +2 -2
  10. package/cjs/FileSystem.js +492 -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 +4 -3
  27. package/cjs/Sandbox.js +756 -821
  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 +2 -1
  36. package/cjs/errors/DaytonaError.js.map +1 -1
  37. package/cjs/index.d.ts +2 -2
  38. package/cjs/index.js +2 -1
  39. package/cjs/index.js.map +1 -1
  40. package/cjs/types/CodeInterpreter.d.ts +1 -1
  41. package/cjs/utils/Binary.js +14 -2
  42. package/cjs/utils/Binary.js.map +1 -1
  43. package/cjs/utils/FileTransfer.js +1 -1
  44. package/cjs/utils/FileTransfer.js.map +1 -1
  45. package/cjs/utils/otel.decorator.d.ts +7 -8
  46. package/cjs/utils/otel.decorator.js +24 -30
  47. package/cjs/utils/otel.decorator.js.map +1 -1
  48. package/esm/CodeInterpreter.d.ts +3 -2
  49. package/esm/CodeInterpreter.js.map +1 -1
  50. package/esm/ComputerUse.d.ts +104 -2
  51. package/esm/ComputerUse.js +857 -763
  52. package/esm/ComputerUse.js.map +1 -1
  53. package/esm/Daytona.d.ts +4 -3
  54. package/esm/Daytona.js +431 -444
  55. package/esm/Daytona.js.map +1 -1
  56. package/esm/FileSystem.d.ts +2 -2
  57. package/esm/FileSystem.js +494 -522
  58. package/esm/FileSystem.js.map +1 -1
  59. package/esm/Git.d.ts +2 -1
  60. package/esm/Git.js +289 -311
  61. package/esm/Git.js.map +1 -1
  62. package/esm/LspServer.d.ts +2 -1
  63. package/esm/LspServer.js +211 -227
  64. package/esm/LspServer.js.map +1 -1
  65. package/esm/ObjectStorage.js +172 -167
  66. package/esm/ObjectStorage.js.map +1 -1
  67. package/esm/Process.d.ts +4 -3
  68. package/esm/Process.js +564 -601
  69. package/esm/Process.js.map +1 -1
  70. package/esm/PtyHandle.d.ts +2 -2
  71. package/esm/PtyHandle.js +329 -339
  72. package/esm/PtyHandle.js.map +1 -1
  73. package/esm/Sandbox.d.ts +4 -3
  74. package/esm/Sandbox.js +759 -823
  75. package/esm/Sandbox.js.map +1 -1
  76. package/esm/Snapshot.d.ts +3 -2
  77. package/esm/Snapshot.js +206 -215
  78. package/esm/Snapshot.js.map +1 -1
  79. package/esm/Volume.d.ts +2 -1
  80. package/esm/Volume.js +92 -93
  81. package/esm/Volume.js.map +1 -1
  82. package/esm/errors/DaytonaError.d.ts +2 -1
  83. package/esm/errors/DaytonaError.js.map +1 -1
  84. package/esm/index.d.ts +2 -2
  85. package/esm/index.js +1 -1
  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/FileTransfer.js +1 -1
  91. package/esm/utils/FileTransfer.js.map +1 -1
  92. package/esm/utils/otel.decorator.d.ts +7 -8
  93. package/esm/utils/otel.decorator.js +26 -32
  94. package/esm/utils/otel.decorator.js.map +1 -1
  95. package/package.json +4 -4
package/esm/FileSystem.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Copyright 2025 Daytona Platforms Inc.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import { __decorate, __metadata } from "tslib";
5
+ import { __esDecorate, __runInitializers } from "tslib";
6
6
  import * as pathe from 'pathe';
7
7
  import axios from 'axios';
8
8
  import { dynamicImport } from './utils/Import.js';
@@ -21,551 +21,523 @@ function createFileDownloadError(error, errorDetails) {
21
21
  *
22
22
  * @class
23
23
  */
24
- export class FileSystem {
25
- clientConfig;
26
- apiClient;
27
- constructor(clientConfig, apiClient) {
28
- this.clientConfig = clientConfig;
29
- this.apiClient = apiClient;
30
- }
31
- /**
32
- * Create a new directory in the Sandbox with specified permissions.
33
- *
34
- * @param {string} path - Path where the directory should be created. Relative paths are resolved based on the sandbox working directory.
35
- * @param {string} mode - Directory permissions in octal format (e.g. "755")
36
- * @returns {Promise<void>}
37
- *
38
- * @example
39
- * // Create a directory with standard permissions
40
- * await fs.createFolder('app/data', '755');
41
- */
42
- async createFolder(path, mode) {
43
- const response = await this.apiClient.createFolder(path, mode);
44
- return response.data;
45
- }
46
- /**
47
- * Deletes a file or directory from the Sandbox.
48
- *
49
- * @param {string} path - Path to the file or directory to delete. Relative paths are resolved based on the sandbox working directory.
50
- * @param {boolean} [recursive] - If the file is a directory, this must be true to delete it.
51
- * @returns {Promise<void>}
52
- *
53
- * @example
54
- * // Delete a file
55
- * await fs.deleteFile('app/temp.log');
56
- */
57
- async deleteFile(path, recursive) {
58
- const response = await this.apiClient.deleteFile(path, recursive);
59
- return response.data;
60
- }
61
- async downloadFile(src, dst, timeout = 30 * 60) {
62
- const remotePath = src;
63
- if (typeof dst !== 'string') {
64
- if (dst) {
65
- timeout = dst;
66
- }
67
- const response = await this.downloadFiles([{ source: remotePath }], timeout);
68
- if (response[0].error) {
69
- throw createFileDownloadError(response[0].error, response[0].errorDetails);
70
- }
71
- return response[0].result;
72
- }
73
- const response = await this.downloadFiles([{ source: remotePath, destination: dst }], timeout);
74
- if (response[0].error) {
75
- throw createFileDownloadError(response[0].error, response[0].errorDetails);
24
+ let FileSystem = (() => {
25
+ let _instanceExtraInitializers = [];
26
+ let _createFolder_decorators;
27
+ let _deleteFile_decorators;
28
+ let _downloadFile_decorators;
29
+ let _downloadFileStream_decorators;
30
+ let _downloadFiles_decorators;
31
+ let _findFiles_decorators;
32
+ let _getFileDetails_decorators;
33
+ let _listFiles_decorators;
34
+ let _moveFiles_decorators;
35
+ let _replaceInFiles_decorators;
36
+ let _searchFiles_decorators;
37
+ let _setFilePermissions_decorators;
38
+ let _uploadFile_decorators;
39
+ let _uploadFileStream_decorators;
40
+ let _uploadFiles_decorators;
41
+ return class FileSystem {
42
+ static {
43
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
44
+ _createFolder_decorators = [WithInstrumentation()];
45
+ _deleteFile_decorators = [WithInstrumentation()];
46
+ _downloadFile_decorators = [WithInstrumentation()];
47
+ _downloadFileStream_decorators = [WithInstrumentation()];
48
+ _downloadFiles_decorators = [WithInstrumentation()];
49
+ _findFiles_decorators = [WithInstrumentation()];
50
+ _getFileDetails_decorators = [WithInstrumentation()];
51
+ _listFiles_decorators = [WithInstrumentation()];
52
+ _moveFiles_decorators = [WithInstrumentation()];
53
+ _replaceInFiles_decorators = [WithInstrumentation()];
54
+ _searchFiles_decorators = [WithInstrumentation()];
55
+ _setFilePermissions_decorators = [WithInstrumentation()];
56
+ _uploadFile_decorators = [WithInstrumentation()];
57
+ _uploadFileStream_decorators = [WithInstrumentation()];
58
+ _uploadFiles_decorators = [WithInstrumentation()];
59
+ __esDecorate(this, null, _createFolder_decorators, { kind: "method", name: "createFolder", static: false, private: false, access: { has: obj => "createFolder" in obj, get: obj => obj.createFolder }, metadata: _metadata }, null, _instanceExtraInitializers);
60
+ __esDecorate(this, null, _deleteFile_decorators, { kind: "method", name: "deleteFile", static: false, private: false, access: { has: obj => "deleteFile" in obj, get: obj => obj.deleteFile }, metadata: _metadata }, null, _instanceExtraInitializers);
61
+ __esDecorate(this, null, _downloadFile_decorators, { kind: "method", name: "downloadFile", static: false, private: false, access: { has: obj => "downloadFile" in obj, get: obj => obj.downloadFile }, metadata: _metadata }, null, _instanceExtraInitializers);
62
+ __esDecorate(this, null, _downloadFileStream_decorators, { kind: "method", name: "downloadFileStream", static: false, private: false, access: { has: obj => "downloadFileStream" in obj, get: obj => obj.downloadFileStream }, metadata: _metadata }, null, _instanceExtraInitializers);
63
+ __esDecorate(this, null, _downloadFiles_decorators, { kind: "method", name: "downloadFiles", static: false, private: false, access: { has: obj => "downloadFiles" in obj, get: obj => obj.downloadFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
64
+ __esDecorate(this, null, _findFiles_decorators, { kind: "method", name: "findFiles", static: false, private: false, access: { has: obj => "findFiles" in obj, get: obj => obj.findFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
65
+ __esDecorate(this, null, _getFileDetails_decorators, { kind: "method", name: "getFileDetails", static: false, private: false, access: { has: obj => "getFileDetails" in obj, get: obj => obj.getFileDetails }, metadata: _metadata }, null, _instanceExtraInitializers);
66
+ __esDecorate(this, null, _listFiles_decorators, { kind: "method", name: "listFiles", static: false, private: false, access: { has: obj => "listFiles" in obj, get: obj => obj.listFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
67
+ __esDecorate(this, null, _moveFiles_decorators, { kind: "method", name: "moveFiles", static: false, private: false, access: { has: obj => "moveFiles" in obj, get: obj => obj.moveFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
68
+ __esDecorate(this, null, _replaceInFiles_decorators, { kind: "method", name: "replaceInFiles", static: false, private: false, access: { has: obj => "replaceInFiles" in obj, get: obj => obj.replaceInFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
69
+ __esDecorate(this, null, _searchFiles_decorators, { kind: "method", name: "searchFiles", static: false, private: false, access: { has: obj => "searchFiles" in obj, get: obj => obj.searchFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
70
+ __esDecorate(this, null, _setFilePermissions_decorators, { kind: "method", name: "setFilePermissions", static: false, private: false, access: { has: obj => "setFilePermissions" in obj, get: obj => obj.setFilePermissions }, metadata: _metadata }, null, _instanceExtraInitializers);
71
+ __esDecorate(this, null, _uploadFile_decorators, { kind: "method", name: "uploadFile", static: false, private: false, access: { has: obj => "uploadFile" in obj, get: obj => obj.uploadFile }, metadata: _metadata }, null, _instanceExtraInitializers);
72
+ __esDecorate(this, null, _uploadFileStream_decorators, { kind: "method", name: "uploadFileStream", static: false, private: false, access: { has: obj => "uploadFileStream" in obj, get: obj => obj.uploadFileStream }, metadata: _metadata }, null, _instanceExtraInitializers);
73
+ __esDecorate(this, null, _uploadFiles_decorators, { kind: "method", name: "uploadFiles", static: false, private: false, access: { has: obj => "uploadFiles" in obj, get: obj => obj.uploadFiles }, metadata: _metadata }, null, _instanceExtraInitializers);
74
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
76
75
  }
77
- }
78
- async downloadFileStream(remotePath, timeoutOrOptions) {
79
- const options = typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : (timeoutOrOptions ?? {});
80
- const timeout = options.timeout ?? 30 * 60;
81
- const isNonStreamingRuntime = RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
82
- if (isNonStreamingRuntime) {
83
- throw new DaytonaError('downloadFileStream is not supported in browser or serverless environments. Use downloadFile instead.');
76
+ clientConfig = __runInitializers(this, _instanceExtraInitializers);
77
+ apiClient;
78
+ constructor(clientConfig, apiClient) {
79
+ this.clientConfig = clientConfig;
80
+ this.apiClient = apiClient;
84
81
  }
85
- if (options.signal?.aborted) {
86
- throw new DaytonaError('Download cancelled');
82
+ /**
83
+ * Create a new directory in the Sandbox with specified permissions.
84
+ *
85
+ * @param {string} path - Path where the directory should be created. Relative paths are resolved based on the sandbox working directory.
86
+ * @param {string} mode - Directory permissions in octal format (e.g. "755")
87
+ * @returns {Promise<void>}
88
+ *
89
+ * @example
90
+ * // Create a directory with standard permissions
91
+ * await fs.createFolder('app/data', '755');
92
+ */
93
+ async createFolder(path, mode) {
94
+ const response = await this.apiClient.createFolder(path, mode);
95
+ return response.data;
87
96
  }
88
- const toDownloadCancelledError = () => new DaytonaError('Download cancelled');
89
- const isCanceledError = (err) => {
90
- const error = err;
91
- return Boolean(axios.isCancel?.(err) || error?.name === 'CanceledError' || error?.code === 'ERR_CANCELED');
92
- };
93
- let response;
94
- try {
95
- response = await this.apiClient.downloadFiles({ paths: [remotePath] }, {
96
- responseType: 'stream',
97
- timeout: timeout * 1000,
98
- signal: options.signal,
99
- });
97
+ /**
98
+ * Deletes a file or directory from the Sandbox.
99
+ *
100
+ * @param {string} path - Path to the file or directory to delete. Relative paths are resolved based on the sandbox working directory.
101
+ * @param {boolean} [recursive] - If the file is a directory, this must be true to delete it.
102
+ * @returns {Promise<void>}
103
+ *
104
+ * @example
105
+ * // Delete a file
106
+ * await fs.deleteFile('app/temp.log');
107
+ */
108
+ async deleteFile(path, recursive) {
109
+ const response = await this.apiClient.deleteFile(path, recursive);
110
+ return response.data;
100
111
  }
101
- catch (err) {
102
- if (options.signal?.aborted || isCanceledError(err)) {
103
- throw toDownloadCancelledError();
112
+ async downloadFile(src, dst, timeout = 30 * 60) {
113
+ const remotePath = src;
114
+ if (typeof dst !== 'string') {
115
+ if (dst) {
116
+ timeout = dst;
117
+ }
118
+ const response = await this.downloadFiles([{ source: remotePath }], timeout);
119
+ if (response[0].error) {
120
+ throw createFileDownloadError(response[0].error, response[0].errorDetails);
121
+ }
122
+ return response[0].result;
123
+ }
124
+ const response = await this.downloadFiles([{ source: remotePath, destination: dst }], timeout);
125
+ if (response[0].error) {
126
+ throw createFileDownloadError(response[0].error, response[0].errorDetails);
104
127
  }
105
- throw err;
106
128
  }
107
- const responseStream = normalizeResponseStream(response.data);
108
- const metadataMap = new Map();
109
- metadataMap.set(remotePath, {});
110
- return new Promise((resolve, reject) => {
111
- let resolvedStream = null;
112
- processDownloadFilesResponseWithBusboy(responseStream, response.headers, metadataMap, (_source, fileStream, totalBytes) => {
113
- if (options.onProgress) {
114
- const { Transform } = require('stream');
115
- let bytesReceived = 0;
116
- const progress = new Transform({
117
- transform(chunk, _encoding, callback) {
118
- bytesReceived += chunk.length;
119
- options.onProgress({ bytesReceived, totalBytes });
120
- callback(null, chunk);
121
- },
122
- });
123
- fileStream.pipe(progress);
124
- fileStream.on('error', (err) => {
125
- if (!progress.destroyed)
126
- progress.destroy(err);
127
- });
128
- resolvedStream = progress;
129
- }
130
- else {
131
- resolvedStream = fileStream;
129
+ async downloadFileStream(remotePath, timeoutOrOptions) {
130
+ const options = typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : (timeoutOrOptions ?? {});
131
+ const timeout = options.timeout ?? 30 * 60;
132
+ const isNonStreamingRuntime = RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
133
+ if (isNonStreamingRuntime) {
134
+ throw new DaytonaError('downloadFileStream is not supported in browser or serverless environments. Use downloadFile instead.');
135
+ }
136
+ if (options.signal?.aborted) {
137
+ throw new DaytonaError('Download cancelled');
138
+ }
139
+ // Pre-resolve `stream` so the sync `onFileStream` callback below is await-free.
140
+ const { Transform } = await dynamicImport('stream', 'downloadFileStream progress tracking is not supported: ');
141
+ const toDownloadCancelledError = () => new DaytonaError('Download cancelled');
142
+ const isCanceledError = (err) => {
143
+ const error = err;
144
+ return Boolean(axios.isCancel?.(err) || error?.name === 'CanceledError' || error?.code === 'ERR_CANCELED');
145
+ };
146
+ let response;
147
+ try {
148
+ response = await this.apiClient.downloadFiles({ paths: [remotePath] }, {
149
+ responseType: 'stream',
150
+ timeout: timeout * 1000,
151
+ signal: options.signal,
152
+ });
153
+ }
154
+ catch (err) {
155
+ if (options.signal?.aborted || isCanceledError(err)) {
156
+ throw toDownloadCancelledError();
132
157
  }
133
- resolve(resolvedStream);
134
- })
135
- .then(() => {
136
- if (!resolvedStream) {
137
- const metadata = metadataMap.get(remotePath);
138
- if (metadata?.error) {
139
- reject(createFileDownloadError(metadata.error, metadata.errorDetails));
158
+ throw err;
159
+ }
160
+ const responseStream = normalizeResponseStream(response.data);
161
+ const metadataMap = new Map();
162
+ metadataMap.set(remotePath, {});
163
+ return new Promise((resolve, reject) => {
164
+ let resolvedStream = null;
165
+ processDownloadFilesResponseWithBusboy(responseStream, response.headers, metadataMap, (_source, fileStream, totalBytes) => {
166
+ if (options.onProgress) {
167
+ let bytesReceived = 0;
168
+ const progress = new Transform({
169
+ transform(chunk, _encoding, callback) {
170
+ bytesReceived += chunk.length;
171
+ options.onProgress({ bytesReceived, totalBytes });
172
+ callback(null, chunk);
173
+ },
174
+ });
175
+ fileStream.pipe(progress);
176
+ // busboy's teardown can emit 'error' on the file stream after 'end',
177
+ // even when every byte was delivered — ignore those late errors.
178
+ let fileStreamEnded = false;
179
+ fileStream.once('end', () => {
180
+ fileStreamEnded = true;
181
+ });
182
+ fileStream.on('error', (err) => {
183
+ if (fileStreamEnded)
184
+ return;
185
+ if (!progress.destroyed)
186
+ progress.destroy(err);
187
+ });
188
+ resolvedStream = progress;
140
189
  }
141
190
  else {
142
- reject(new DaytonaError(`No file data received for: ${remotePath}`));
191
+ resolvedStream = fileStream;
143
192
  }
193
+ resolve(resolvedStream);
194
+ })
195
+ .then(() => {
196
+ if (!resolvedStream) {
197
+ const metadata = metadataMap.get(remotePath);
198
+ if (metadata?.error) {
199
+ reject(createFileDownloadError(metadata.error, metadata.errorDetails));
200
+ }
201
+ else {
202
+ reject(new DaytonaError(`No file data received for: ${remotePath}`));
203
+ }
204
+ }
205
+ })
206
+ .catch((err) => {
207
+ const normalizedError = options.signal?.aborted || isCanceledError(err) ? toDownloadCancelledError() : err;
208
+ if (!resolvedStream) {
209
+ reject(normalizedError);
210
+ return;
211
+ }
212
+ const stream = resolvedStream;
213
+ if (stream.destroyed || stream.readableEnded) {
214
+ return;
215
+ }
216
+ stream.destroy(normalizedError instanceof Error ? normalizedError : new Error(String(normalizedError)));
217
+ });
218
+ });
219
+ }
220
+ /**
221
+ * Downloads multiple files from the Sandbox. If the files already exist locally, they will be overwritten.
222
+ *
223
+ * @param {FileDownloadRequest[]} files - Array of file download requests.
224
+ * @param {number} [timeoutSec] - Timeout for the download operation in seconds. 0 means no timeout.
225
+ * Default is 30 minutes.
226
+ * @returns {Promise<FileDownloadResponse[]>} Array of download results.
227
+ *
228
+ * @throws {DaytonaError} If the request itself fails (network issues, invalid request/response, etc.). Individual
229
+ * file download errors are returned in `FileDownloadResponse.error`. When the daemon provides structured
230
+ * per-file metadata, it is also available in `FileDownloadResponse.errorDetails`.
231
+ *
232
+ * @example
233
+ * // Download multiple files
234
+ * const results = await fs.downloadFiles([
235
+ * { source: 'tmp/data.json' },
236
+ * { source: 'tmp/config.json', destination: 'local_config.json' }
237
+ * ]);
238
+ * results.forEach(result => {
239
+ * if (result.error) {
240
+ * console.error(`Error downloading ${result.source}: ${result.error}`);
241
+ * } else if (result.result) {
242
+ * console.log(`Downloaded ${result.source} to ${result.result}`);
243
+ * }
244
+ * });
245
+ */
246
+ async downloadFiles(files, timeoutSec = 30 * 60) {
247
+ if (files.length === 0)
248
+ return [];
249
+ const isNonStreamingRuntime = RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
250
+ // Prepare destinations and metadata
251
+ const metadataMap = new Map();
252
+ for (const f of files) {
253
+ metadataMap.set(f.source, { destination: f.destination });
254
+ if (f.destination) {
255
+ const fs = await dynamicImport('fs', 'Downloading files to local files is not supported: ');
256
+ await fs.promises.mkdir(pathe.dirname(f.destination), { recursive: true });
144
257
  }
145
- })
146
- .catch((err) => {
147
- const normalizedError = options.signal?.aborted || isCanceledError(err) ? toDownloadCancelledError() : err;
148
- if (!resolvedStream) {
149
- reject(normalizedError);
150
- return;
151
- }
152
- const stream = resolvedStream;
153
- if (stream.destroyed || stream.readableEnded) {
154
- return;
155
- }
156
- stream.destroy(normalizedError instanceof Error ? normalizedError : new Error(String(normalizedError)));
258
+ }
259
+ const response = await this.apiClient.downloadFiles({ paths: files.map((f) => f.source) }, {
260
+ responseType: isNonStreamingRuntime ? 'arraybuffer' : 'stream',
261
+ timeout: timeoutSec * 1000,
157
262
  });
158
- });
159
- }
160
- /**
161
- * Downloads multiple files from the Sandbox. If the files already exist locally, they will be overwritten.
162
- *
163
- * @param {FileDownloadRequest[]} files - Array of file download requests.
164
- * @param {number} [timeoutSec] - Timeout for the download operation in seconds. 0 means no timeout.
165
- * Default is 30 minutes.
166
- * @returns {Promise<FileDownloadResponse[]>} Array of download results.
167
- *
168
- * @throws {DaytonaError} If the request itself fails (network issues, invalid request/response, etc.). Individual
169
- * file download errors are returned in `FileDownloadResponse.error`. When the daemon provides structured
170
- * per-file metadata, it is also available in `FileDownloadResponse.errorDetails`.
171
- *
172
- * @example
173
- * // Download multiple files
174
- * const results = await fs.downloadFiles([
175
- * { source: 'tmp/data.json' },
176
- * { source: 'tmp/config.json', destination: 'local_config.json' }
177
- * ]);
178
- * results.forEach(result => {
179
- * if (result.error) {
180
- * console.error(`Error downloading ${result.source}: ${result.error}`);
181
- * } else if (result.result) {
182
- * console.log(`Downloaded ${result.source} to ${result.result}`);
183
- * }
184
- * });
185
- */
186
- async downloadFiles(files, timeoutSec = 30 * 60) {
187
- if (files.length === 0)
188
- return [];
189
- const isNonStreamingRuntime = RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
190
- // Prepare destinations and metadata
191
- const metadataMap = new Map();
192
- for (const f of files) {
193
- metadataMap.set(f.source, { destination: f.destination });
194
- if (f.destination) {
195
- const fs = await dynamicImport('fs', 'Downloading files to local files is not supported: ');
196
- await fs.promises.mkdir(pathe.dirname(f.destination), { recursive: true });
263
+ const stream = normalizeResponseStream(response.data);
264
+ // Node.js path: use busboy for efficient streaming
265
+ if (isNonStreamingRuntime) {
266
+ await processDownloadFilesResponseWithBuffered(stream, response.headers, metadataMap);
267
+ }
268
+ else {
269
+ await processDownloadFilesResponseWithBusboy(stream, response.headers, metadataMap);
197
270
  }
271
+ return files.map((f) => {
272
+ const metadata = metadataMap.get(f.source);
273
+ const error = metadata?.error || (!metadata?.result ? 'No data received for this file' : undefined);
274
+ return {
275
+ source: f.source,
276
+ result: error ? undefined : metadata.result,
277
+ error,
278
+ errorDetails: error ? metadata?.errorDetails : undefined,
279
+ };
280
+ });
281
+ }
282
+ /**
283
+ * Searches for text patterns within files in the Sandbox.
284
+ *
285
+ * @param {string} path - Directory to search in. Relative paths are resolved based on the sandbox working directory.
286
+ * @param {string} pattern - Search pattern
287
+ * @returns {Promise<Array<Match>>} Array of matches with file and line information
288
+ *
289
+ * @example
290
+ * // Find all TODO comments in TypeScript files
291
+ * const matches = await fs.findFiles('app/src', 'TODO:');
292
+ * matches.forEach(match => {
293
+ * console.log(`${match.file}:${match.line}: ${match.content}`);
294
+ * });
295
+ */
296
+ async findFiles(path, pattern) {
297
+ const response = await this.apiClient.findInFiles(path, pattern);
298
+ return response.data;
198
299
  }
199
- const response = await this.apiClient.downloadFiles({ paths: files.map((f) => f.source) }, {
200
- responseType: isNonStreamingRuntime ? 'arraybuffer' : 'stream',
201
- timeout: timeoutSec * 1000,
202
- });
203
- const stream = normalizeResponseStream(response.data);
204
- // Node.js path: use busboy for efficient streaming
205
- if (isNonStreamingRuntime) {
206
- await processDownloadFilesResponseWithBuffered(stream, response.headers, metadataMap);
300
+ /**
301
+ * Retrieves detailed information about a file or directory.
302
+ *
303
+ * @param {string} path - Path to the file or directory. Relative paths are resolved based on the sandbox working directory.
304
+ * @returns {Promise<FileInfo>} Detailed file information including size, permissions, modification time
305
+ *
306
+ * @example
307
+ * // Get file details
308
+ * const info = await fs.getFileDetails('app/config.json');
309
+ * console.log(`Size: ${info.size}, Modified: ${info.modTime}`);
310
+ */
311
+ async getFileDetails(path) {
312
+ const response = await this.apiClient.getFileInfo(path);
313
+ return response.data;
207
314
  }
208
- else {
209
- await processDownloadFilesResponseWithBusboy(stream, response.headers, metadataMap);
315
+ /**
316
+ * Lists contents of a directory in the Sandbox.
317
+ *
318
+ * @param {string} path - Directory path to list. Relative paths are resolved based on the sandbox working directory.
319
+ * @returns {Promise<FileInfo[]>} Array of file and directory information
320
+ *
321
+ * @example
322
+ * // List directory contents
323
+ * const files = await fs.listFiles('app/src');
324
+ * files.forEach(file => {
325
+ * console.log(`${file.name} (${file.size} bytes)`);
326
+ * });
327
+ */
328
+ async listFiles(path) {
329
+ const response = await this.apiClient.listFiles(path);
330
+ return response.data;
210
331
  }
211
- return files.map((f) => {
212
- const metadata = metadataMap.get(f.source);
213
- const error = metadata?.error || (!metadata?.result ? 'No data received for this file' : undefined);
214
- return {
215
- source: f.source,
216
- result: error ? undefined : metadata.result,
217
- error,
218
- errorDetails: error ? metadata?.errorDetails : undefined,
332
+ /**
333
+ * Moves or renames a file or directory.
334
+ *
335
+ * @param {string} source - Source path. Relative paths are resolved based on the sandbox working directory.
336
+ * @param {string} destination - Destination path. Relative paths are resolved based on the sandbox working directory.
337
+ * @returns {Promise<void>}
338
+ *
339
+ * @example
340
+ * // Move a file to a new location
341
+ * await fs.moveFiles('app/temp/data.json', 'app/data/data.json');
342
+ */
343
+ async moveFiles(source, destination) {
344
+ const response = await this.apiClient.moveFile(source, destination);
345
+ return response.data;
346
+ }
347
+ /**
348
+ * Replaces text content in multiple files.
349
+ *
350
+ * @param {string[]} files - Array of file paths to process. Relative paths are resolved based on the sandbox working directory.
351
+ * @param {string} pattern - Pattern to replace
352
+ * @param {string} newValue - Replacement text
353
+ * @returns {Promise<Array<ReplaceResult>>} Results of the replace operation for each file
354
+ *
355
+ * @example
356
+ * // Update version number across multiple files
357
+ * const results = await fs.replaceInFiles(
358
+ * ['app/package.json', 'app/version.ts'],
359
+ * '"version": "1.0.0"',
360
+ * '"version": "1.1.0"'
361
+ * );
362
+ */
363
+ async replaceInFiles(files, pattern, newValue) {
364
+ const replaceRequest = {
365
+ files,
366
+ newValue,
367
+ pattern,
219
368
  };
220
- });
221
- }
222
- /**
223
- * Searches for text patterns within files in the Sandbox.
224
- *
225
- * @param {string} path - Directory to search in. Relative paths are resolved based on the sandbox working directory.
226
- * @param {string} pattern - Search pattern
227
- * @returns {Promise<Array<Match>>} Array of matches with file and line information
228
- *
229
- * @example
230
- * // Find all TODO comments in TypeScript files
231
- * const matches = await fs.findFiles('app/src', 'TODO:');
232
- * matches.forEach(match => {
233
- * console.log(`${match.file}:${match.line}: ${match.content}`);
234
- * });
235
- */
236
- async findFiles(path, pattern) {
237
- const response = await this.apiClient.findInFiles(path, pattern);
238
- return response.data;
239
- }
240
- /**
241
- * Retrieves detailed information about a file or directory.
242
- *
243
- * @param {string} path - Path to the file or directory. Relative paths are resolved based on the sandbox working directory.
244
- * @returns {Promise<FileInfo>} Detailed file information including size, permissions, modification time
245
- *
246
- * @example
247
- * // Get file details
248
- * const info = await fs.getFileDetails('app/config.json');
249
- * console.log(`Size: ${info.size}, Modified: ${info.modTime}`);
250
- */
251
- async getFileDetails(path) {
252
- const response = await this.apiClient.getFileInfo(path);
253
- return response.data;
254
- }
255
- /**
256
- * Lists contents of a directory in the Sandbox.
257
- *
258
- * @param {string} path - Directory path to list. Relative paths are resolved based on the sandbox working directory.
259
- * @returns {Promise<FileInfo[]>} Array of file and directory information
260
- *
261
- * @example
262
- * // List directory contents
263
- * const files = await fs.listFiles('app/src');
264
- * files.forEach(file => {
265
- * console.log(`${file.name} (${file.size} bytes)`);
266
- * });
267
- */
268
- async listFiles(path) {
269
- const response = await this.apiClient.listFiles(path);
270
- return response.data;
271
- }
272
- /**
273
- * Moves or renames a file or directory.
274
- *
275
- * @param {string} source - Source path. Relative paths are resolved based on the sandbox working directory.
276
- * @param {string} destination - Destination path. Relative paths are resolved based on the sandbox working directory.
277
- * @returns {Promise<void>}
278
- *
279
- * @example
280
- * // Move a file to a new location
281
- * await fs.moveFiles('app/temp/data.json', 'app/data/data.json');
282
- */
283
- async moveFiles(source, destination) {
284
- const response = await this.apiClient.moveFile(source, destination);
285
- return response.data;
286
- }
287
- /**
288
- * Replaces text content in multiple files.
289
- *
290
- * @param {string[]} files - Array of file paths to process. Relative paths are resolved based on the sandbox working directory.
291
- * @param {string} pattern - Pattern to replace
292
- * @param {string} newValue - Replacement text
293
- * @returns {Promise<Array<ReplaceResult>>} Results of the replace operation for each file
294
- *
295
- * @example
296
- * // Update version number across multiple files
297
- * const results = await fs.replaceInFiles(
298
- * ['app/package.json', 'app/version.ts'],
299
- * '"version": "1.0.0"',
300
- * '"version": "1.1.0"'
301
- * );
302
- */
303
- async replaceInFiles(files, pattern, newValue) {
304
- const replaceRequest = {
305
- files,
306
- newValue,
307
- pattern,
308
- };
309
- const response = await this.apiClient.replaceInFiles(replaceRequest);
310
- return response.data;
311
- }
312
- /**
313
- * Searches for files and directories by name pattern in the Sandbox.
314
- *
315
- * @param {string} path - Directory to search in. Relative paths are resolved based on the sandbox working directory.
316
- * @param {string} pattern - File name pattern (supports globs)
317
- * @returns {Promise<SearchFilesResponse>} Search results with matching files
318
- *
319
- * @example
320
- * // Find all TypeScript files
321
- * const result = await fs.searchFiles('app', '*.ts');
322
- * result.files.forEach(file => console.log(file));
323
- */
324
- async searchFiles(path, pattern) {
325
- const response = await this.apiClient.searchFiles(path, pattern);
326
- return response.data;
327
- }
328
- /**
329
- * Sets permissions and ownership for a file or directory.
330
- *
331
- * @param {string} path - Path to the file or directory. Relative paths are resolved based on the sandbox working directory.
332
- * @param {FilePermissionsParams} permissions - Permission settings
333
- * @returns {Promise<void>}
334
- *
335
- * @example
336
- * // Set file permissions and ownership
337
- * await fs.setFilePermissions('app/script.sh', {
338
- * owner: 'daytona',
339
- * group: 'users',
340
- * mode: '755' // Execute permission for shell script
341
- * });
342
- */
343
- async setFilePermissions(path, permissions) {
344
- const response = await this.apiClient.setFilePermissions(path, permissions.owner, permissions.group, permissions.mode);
345
- return response.data;
346
- }
347
- async uploadFile(src, dst, timeout = 30 * 60) {
348
- await this.uploadFiles([{ source: src, destination: dst }], timeout);
349
- }
350
- /**
351
- * Uploads a single file to the Sandbox using true streaming, with optional progress
352
- * tracking and cancellation. Memory usage stays flat regardless of source size: the
353
- * SDK pipes the source through a transform that counts bytes and forwards to the
354
- * underlying multipart upload without buffering the whole payload. The HTTP layer
355
- * uses chunked transfer encoding, so the source's natural EOF terminates the upload —
356
- * no advance size is needed.
357
- *
358
- * @param {UploadSource} source - The data to upload. Accepts the same `Buffer | string`
359
- * inputs as {@link FileSystem.uploadFile}, plus Node `Readable` streams and Web
360
- * `ReadableStream` instances. When a string is passed, it is treated as a local
361
- * file path and read in streaming chunks.
362
- * @param {string} remotePath - Destination path in the Sandbox. Relative paths are
363
- * resolved against the sandbox working directory.
364
- * @param {UploadStreamOptions} [options] - Streaming options: AbortSignal, onProgress
365
- * callback, timeout.
366
- * @returns {Promise<void>}
367
- *
368
- * @example
369
- * // Upload a 2 GB file with progress tracking and the ability to cancel
370
- * import { createReadStream } from 'fs';
371
- * const controller = new AbortController();
372
- * await sandbox.fs.uploadFileStream(createReadStream('big.bin'), 'tmp/big.bin', {
373
- * signal: controller.signal,
374
- * onProgress: ({ bytesSent }) => console.log(`${bytesSent} bytes sent`),
375
- * });
376
- */
377
- async uploadFileStream(source, remotePath, options = {}) {
378
- const isNonStreamingRuntime = RUNTIME === Runtime.DENO || RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
379
- if (isNonStreamingRuntime) {
380
- throw new DaytonaError('uploadFileStream is not supported in browser, Deno, or serverless runtimes. Use uploadFile instead.');
369
+ const response = await this.apiClient.replaceInFiles(replaceRequest);
370
+ return response.data;
381
371
  }
382
- if (options.signal?.aborted) {
383
- throw createAbortError(remotePath);
372
+ /**
373
+ * Searches for files and directories by name pattern in the Sandbox.
374
+ *
375
+ * @param {string} path - Directory to search in. Relative paths are resolved based on the sandbox working directory.
376
+ * @param {string} pattern - File name pattern (supports globs)
377
+ * @returns {Promise<SearchFilesResponse>} Search results with matching files
378
+ *
379
+ * @example
380
+ * // Find all TypeScript files
381
+ * const result = await fs.searchFiles('app', '*.ts');
382
+ * result.files.forEach(file => console.log(file));
383
+ */
384
+ async searchFiles(path, pattern) {
385
+ const response = await this.apiClient.searchFiles(path, pattern);
386
+ return response.data;
384
387
  }
385
- const timeout = options.timeout ?? 30 * 60;
386
- const sourceStream = await coerceUploadSource(source);
387
- const tracked = wrapWithUploadProgress(sourceStream, options.onProgress, options.signal);
388
- const FormDataClass = (await dynamicImport('form-data', 'Uploading files is not supported: '));
389
- const form = new FormDataClass();
390
- form.append('files[0].path', remotePath);
391
- // No knownLength: form-data falls back to chunked transfer encoding, which the
392
- // daemon's MultipartReader handles transparently. The source's EOF terminates
393
- // the upload no advance byte count needed.
394
- form.append('files[0].file', tracked, { filename: remotePath });
395
- try {
396
- await this.apiClient.uploadFiles({
397
- data: form,
398
- maxRedirects: 0,
399
- timeout: timeout * 1000,
400
- signal: options.signal,
401
- });
388
+ /**
389
+ * Sets permissions and ownership for a file or directory.
390
+ *
391
+ * @param {string} path - Path to the file or directory. Relative paths are resolved based on the sandbox working directory.
392
+ * @param {FilePermissionsParams} permissions - Permission settings
393
+ * @returns {Promise<void>}
394
+ *
395
+ * @example
396
+ * // Set file permissions and ownership
397
+ * await fs.setFilePermissions('app/script.sh', {
398
+ * owner: 'daytona',
399
+ * group: 'users',
400
+ * mode: '755' // Execute permission for shell script
401
+ * });
402
+ */
403
+ async setFilePermissions(path, permissions) {
404
+ const response = await this.apiClient.setFilePermissions(path, permissions.owner, permissions.group, permissions.mode);
405
+ return response.data;
406
+ }
407
+ async uploadFile(src, dst, timeout = 30 * 60) {
408
+ await this.uploadFiles([{ source: src, destination: dst }], timeout);
402
409
  }
403
- catch (err) {
410
+ /**
411
+ * Uploads a single file to the Sandbox using true streaming, with optional progress
412
+ * tracking and cancellation. Memory usage stays flat regardless of source size: the
413
+ * SDK pipes the source through a transform that counts bytes and forwards to the
414
+ * underlying multipart upload without buffering the whole payload. The HTTP layer
415
+ * uses chunked transfer encoding, so the source's natural EOF terminates the upload —
416
+ * no advance size is needed.
417
+ *
418
+ * @param {UploadSource} source - The data to upload. Accepts the same `Buffer | string`
419
+ * inputs as {@link FileSystem.uploadFile}, plus Node `Readable` streams and Web
420
+ * `ReadableStream` instances. When a string is passed, it is treated as a local
421
+ * file path and read in streaming chunks.
422
+ * @param {string} remotePath - Destination path in the Sandbox. Relative paths are
423
+ * resolved against the sandbox working directory.
424
+ * @param {UploadStreamOptions} [options] - Streaming options: AbortSignal, onProgress
425
+ * callback, timeout.
426
+ * @returns {Promise<void>}
427
+ *
428
+ * @example
429
+ * // Upload a 2 GB file with progress tracking and the ability to cancel
430
+ * import { createReadStream } from 'fs';
431
+ * const controller = new AbortController();
432
+ * await sandbox.fs.uploadFileStream(createReadStream('big.bin'), 'tmp/big.bin', {
433
+ * signal: controller.signal,
434
+ * onProgress: ({ bytesSent }) => console.log(`${bytesSent} bytes sent`),
435
+ * });
436
+ */
437
+ async uploadFileStream(source, remotePath, options = {}) {
438
+ const isNonStreamingRuntime = RUNTIME === Runtime.DENO || RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
439
+ if (isNonStreamingRuntime) {
440
+ throw new DaytonaError('uploadFileStream is not supported in browser, Deno, or serverless runtimes. Use uploadFile instead.');
441
+ }
404
442
  if (options.signal?.aborted) {
405
443
  throw createAbortError(remotePath);
406
444
  }
407
- throw err;
408
- }
409
- }
410
- /**
411
- * Uploads multiple files to the Sandbox. If files already exist at the destination paths,
412
- * they will be overwritten.
413
- *
414
- * @param {FileUpload[]} files - Array of files to upload.
415
- * @param {number} [timeout] - Timeout for the upload operation in seconds. 0 means no timeout.
416
- * Default is 30 minutes.
417
- * @returns {Promise<void>}
418
- *
419
- * @example
420
- * // Upload multiple text files
421
- * const files = [
422
- * {
423
- * source: Buffer.from('Content of file 1'),
424
- * destination: '/tmp/file1.txt'
425
- * },
426
- * {
427
- * source: 'app/data/file2.txt',
428
- * destination: '/tmp/file2.txt'
429
- * },
430
- * {
431
- * source: Buffer.from('{"key": "value"}'),
432
- * destination: '/tmp/config.json'
433
- * }
434
- * ];
435
- * await fs.uploadFiles(files);
436
- */
437
- async uploadFiles(files, timeout = 30 * 60) {
438
- const isNonStreamingRuntime = RUNTIME === Runtime.DENO || RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
439
- const FormDataClass = isNonStreamingRuntime
440
- ? FormData
441
- : (await dynamicImport('form-data', 'Uploading files is not supported: '));
442
- const form = new FormDataClass();
443
- for (const [i, { source, destination }] of files.entries()) {
444
- form.append(`files[${i}].path`, destination);
445
- const payload = await this.makeFilePayload(source);
446
- form.append(`files[${i}].file`, payload, destination);
447
- }
448
- if (isNonStreamingRuntime) {
449
- const url = `${this.clientConfig.basePath}/files/bulk-upload`;
450
- await fetch(url, {
451
- method: 'POST',
452
- headers: this.clientConfig.baseOptions.headers,
453
- body: form,
454
- signal: timeout ? AbortSignal.timeout(timeout * 1000) : undefined,
455
- });
456
- }
457
- else {
458
- await this.apiClient.uploadFiles({
459
- data: form,
460
- maxRedirects: 0,
461
- timeout: timeout * 1000,
462
- });
445
+ const timeout = options.timeout ?? 30 * 60;
446
+ const sourceStream = await coerceUploadSource(source);
447
+ const tracked = wrapWithUploadProgress(sourceStream, options.onProgress, options.signal);
448
+ const FormDataClass = (await dynamicImport('form-data', 'Uploading files is not supported: '));
449
+ const form = new FormDataClass();
450
+ form.append('files[0].path', remotePath);
451
+ // No knownLength: form-data falls back to chunked transfer encoding, which the
452
+ // daemon's MultipartReader handles transparently. The source's EOF terminates
453
+ // the upload no advance byte count needed.
454
+ form.append('files[0].file', tracked, { filename: remotePath });
455
+ try {
456
+ await this.apiClient.uploadFiles({
457
+ data: form,
458
+ maxRedirects: 0,
459
+ timeout: timeout * 1000,
460
+ signal: options.signal,
461
+ });
462
+ }
463
+ catch (err) {
464
+ if (options.signal?.aborted) {
465
+ throw createAbortError(remotePath);
466
+ }
467
+ throw err;
468
+ }
463
469
  }
464
- }
465
- async makeFilePayload(source) {
466
- // String = file path
467
- if (typeof source === 'string') {
468
- const fs = await dynamicImport('fs', 'Uploading file from local file system is not supported: ');
469
- return fs.createReadStream(source);
470
+ /**
471
+ * Uploads multiple files to the Sandbox. If files already exist at the destination paths,
472
+ * they will be overwritten.
473
+ *
474
+ * @param {FileUpload[]} files - Array of files to upload.
475
+ * @param {number} [timeout] - Timeout for the upload operation in seconds. 0 means no timeout.
476
+ * Default is 30 minutes.
477
+ * @returns {Promise<void>}
478
+ *
479
+ * @example
480
+ * // Upload multiple text files
481
+ * const files = [
482
+ * {
483
+ * source: Buffer.from('Content of file 1'),
484
+ * destination: '/tmp/file1.txt'
485
+ * },
486
+ * {
487
+ * source: 'app/data/file2.txt',
488
+ * destination: '/tmp/file2.txt'
489
+ * },
490
+ * {
491
+ * source: Buffer.from('{"key": "value"}'),
492
+ * destination: '/tmp/config.json'
493
+ * }
494
+ * ];
495
+ * await fs.uploadFiles(files);
496
+ */
497
+ async uploadFiles(files, timeout = 30 * 60) {
498
+ const isNonStreamingRuntime = RUNTIME === Runtime.DENO || RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS;
499
+ const FormDataClass = isNonStreamingRuntime
500
+ ? FormData
501
+ : (await dynamicImport('form-data', 'Uploading files is not supported: '));
502
+ const form = new FormDataClass();
503
+ for (const [i, { source, destination }] of files.entries()) {
504
+ form.append(`files[${i}].path`, destination);
505
+ const payload = await this.makeFilePayload(source);
506
+ form.append(`files[${i}].file`, payload, destination);
507
+ }
508
+ if (isNonStreamingRuntime) {
509
+ const url = `${this.clientConfig.basePath}/files/bulk-upload`;
510
+ await fetch(url, {
511
+ method: 'POST',
512
+ headers: this.clientConfig.baseOptions.headers,
513
+ body: form,
514
+ signal: timeout ? AbortSignal.timeout(timeout * 1000) : undefined,
515
+ });
516
+ }
517
+ else {
518
+ await this.apiClient.uploadFiles({
519
+ data: form,
520
+ maxRedirects: 0,
521
+ timeout: timeout * 1000,
522
+ });
523
+ }
470
524
  }
471
- // Blob
472
- if (RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS || RUNTIME === Runtime.DENO) {
473
- // Use .slice() to ensure we have a concrete ArrayBuffer, not ArrayBufferLike
474
- return new Blob([source.slice()], { type: 'application/octet-stream' });
525
+ async makeFilePayload(source) {
526
+ // String = file path
527
+ if (typeof source === 'string') {
528
+ const fs = await dynamicImport('fs', 'Uploading file from local file system is not supported: ');
529
+ return fs.createReadStream(source);
530
+ }
531
+ // Blob
532
+ if (RUNTIME === Runtime.BROWSER || RUNTIME === Runtime.SERVERLESS || RUNTIME === Runtime.DENO) {
533
+ // Use .slice() to ensure we have a concrete ArrayBuffer, not ArrayBufferLike
534
+ return new Blob([source.slice()], { type: 'application/octet-stream' });
535
+ }
536
+ // Readable stream
537
+ const stream = await dynamicImport('stream', 'Uploading file is not supported: ');
538
+ return stream.Readable.from(source);
475
539
  }
476
- // Readable stream
477
- const stream = await dynamicImport('stream', 'Uploading file is not supported: ');
478
- return stream.Readable.from(source);
479
- }
480
- }
481
- __decorate([
482
- WithInstrumentation(),
483
- __metadata("design:type", Function),
484
- __metadata("design:paramtypes", [String, String]),
485
- __metadata("design:returntype", Promise)
486
- ], FileSystem.prototype, "createFolder", null);
487
- __decorate([
488
- WithInstrumentation(),
489
- __metadata("design:type", Function),
490
- __metadata("design:paramtypes", [String, Boolean]),
491
- __metadata("design:returntype", Promise)
492
- ], FileSystem.prototype, "deleteFile", null);
493
- __decorate([
494
- WithInstrumentation(),
495
- __metadata("design:type", Function),
496
- __metadata("design:paramtypes", [String, Object, Number]),
497
- __metadata("design:returntype", Promise)
498
- ], FileSystem.prototype, "downloadFile", null);
499
- __decorate([
500
- WithInstrumentation(),
501
- __metadata("design:type", Function),
502
- __metadata("design:paramtypes", [String, Object]),
503
- __metadata("design:returntype", Promise)
504
- ], FileSystem.prototype, "downloadFileStream", null);
505
- __decorate([
506
- WithInstrumentation(),
507
- __metadata("design:type", Function),
508
- __metadata("design:paramtypes", [Array, Number]),
509
- __metadata("design:returntype", Promise)
510
- ], FileSystem.prototype, "downloadFiles", null);
511
- __decorate([
512
- WithInstrumentation(),
513
- __metadata("design:type", Function),
514
- __metadata("design:paramtypes", [String, String]),
515
- __metadata("design:returntype", Promise)
516
- ], FileSystem.prototype, "findFiles", null);
517
- __decorate([
518
- WithInstrumentation(),
519
- __metadata("design:type", Function),
520
- __metadata("design:paramtypes", [String]),
521
- __metadata("design:returntype", Promise)
522
- ], FileSystem.prototype, "getFileDetails", null);
523
- __decorate([
524
- WithInstrumentation(),
525
- __metadata("design:type", Function),
526
- __metadata("design:paramtypes", [String]),
527
- __metadata("design:returntype", Promise)
528
- ], FileSystem.prototype, "listFiles", null);
529
- __decorate([
530
- WithInstrumentation(),
531
- __metadata("design:type", Function),
532
- __metadata("design:paramtypes", [String, String]),
533
- __metadata("design:returntype", Promise)
534
- ], FileSystem.prototype, "moveFiles", null);
535
- __decorate([
536
- WithInstrumentation(),
537
- __metadata("design:type", Function),
538
- __metadata("design:paramtypes", [Array, String, String]),
539
- __metadata("design:returntype", Promise)
540
- ], FileSystem.prototype, "replaceInFiles", null);
541
- __decorate([
542
- WithInstrumentation(),
543
- __metadata("design:type", Function),
544
- __metadata("design:paramtypes", [String, String]),
545
- __metadata("design:returntype", Promise)
546
- ], FileSystem.prototype, "searchFiles", null);
547
- __decorate([
548
- WithInstrumentation(),
549
- __metadata("design:type", Function),
550
- __metadata("design:paramtypes", [String, Object]),
551
- __metadata("design:returntype", Promise)
552
- ], FileSystem.prototype, "setFilePermissions", null);
553
- __decorate([
554
- WithInstrumentation(),
555
- __metadata("design:type", Function),
556
- __metadata("design:paramtypes", [Object, String, Number]),
557
- __metadata("design:returntype", Promise)
558
- ], FileSystem.prototype, "uploadFile", null);
559
- __decorate([
560
- WithInstrumentation(),
561
- __metadata("design:type", Function),
562
- __metadata("design:paramtypes", [Object, String, Object]),
563
- __metadata("design:returntype", Promise)
564
- ], FileSystem.prototype, "uploadFileStream", null);
565
- __decorate([
566
- WithInstrumentation(),
567
- __metadata("design:type", Function),
568
- __metadata("design:paramtypes", [Array, Number]),
569
- __metadata("design:returntype", Promise)
570
- ], FileSystem.prototype, "uploadFiles", null);
540
+ };
541
+ })();
542
+ export { FileSystem };
571
543
  //# sourceMappingURL=FileSystem.js.map