cubepod 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js ADDED
@@ -0,0 +1,1501 @@
1
+ import { buildTarGzBytes } from './archive.js';
2
+ import { CubePodError, parseAPIError } from './errors.js';
3
+ import { readNdjsonStream } from './ndjson.js';
4
+
5
+ const textEncoder = new TextEncoder();
6
+ const textDecoder = new TextDecoder('utf-8');
7
+
8
+ /**
9
+ * Safely read an environment variable across Node, Deno, Bun, and browser runtimes.
10
+ *
11
+ * @param {...string} names
12
+ * @returns {string | undefined}
13
+ */
14
+ function readEnv(...names) {
15
+ if (typeof process === 'undefined' || !process.env) return undefined;
16
+ for (const name of names) {
17
+ const val = process.env[name];
18
+ if (val) return val;
19
+ }
20
+ return undefined;
21
+ }
22
+
23
+ /**
24
+ * Sleep for `ms` milliseconds, rejecting immediately if `signal` aborts.
25
+ *
26
+ * @param {number} ms
27
+ * @param {AbortSignal} [signal]
28
+ * @returns {Promise<void>}
29
+ */
30
+ function sleep(ms, signal) {
31
+ if (signal?.aborted) {
32
+ return Promise.reject(signal.reason ?? new CubePodError('Request aborted'));
33
+ }
34
+ return new Promise((resolve, reject) => {
35
+ const timer = setTimeout(() => {
36
+ signal?.removeEventListener('abort', onAbort);
37
+ resolve();
38
+ }, ms);
39
+ const onAbort = () => {
40
+ clearTimeout(timer);
41
+ reject(signal?.reason ?? new CubePodError('Request aborted'));
42
+ };
43
+ signal?.addEventListener('abort', onAbort, { once: true });
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Combine an optional caller AbortSignal and an optional timeout into one AbortSignal.
49
+ *
50
+ * @param {number} timeoutMs
51
+ * @param {AbortSignal} [callerSignal]
52
+ * @returns {{ signal?: AbortSignal; cleanup: () => void }}
53
+ */
54
+ function createRequestSignal(timeoutMs, callerSignal) {
55
+ const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
56
+ if (!hasTimeout && !callerSignal) {
57
+ return { signal: undefined, cleanup: () => {} };
58
+ }
59
+ if (!hasTimeout) {
60
+ return { signal: callerSignal, cleanup: () => {} };
61
+ }
62
+
63
+ const controller = new AbortController();
64
+ const timer = setTimeout(() => {
65
+ controller.abort(new CubePodError(`Request timed out after ${timeoutMs}ms`));
66
+ }, timeoutMs);
67
+
68
+ const onCallerAbort = () => {
69
+ controller.abort(callerSignal?.reason ?? new CubePodError('Request aborted'));
70
+ };
71
+
72
+ if (callerSignal) {
73
+ if (callerSignal.aborted) {
74
+ clearTimeout(timer);
75
+ controller.abort(callerSignal.reason ?? new CubePodError('Request aborted'));
76
+ return { signal: controller.signal, cleanup: () => {} };
77
+ }
78
+ callerSignal.addEventListener('abort', onCallerAbort, { once: true });
79
+ }
80
+
81
+ return {
82
+ signal: controller.signal,
83
+ cleanup: () => {
84
+ clearTimeout(timer);
85
+ callerSignal?.removeEventListener('abort', onCallerAbort);
86
+ },
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Normalize raw gateway SandboxInfo JSON into SDK SandboxInfo shape.
92
+ *
93
+ * @param {Record<string, any>} raw
94
+ * @returns {import('./client.d.ts').SandboxInfo}
95
+ */
96
+ export function normalizeSandboxInfo(raw) {
97
+ return {
98
+ sandboxId: raw.sandboxID ?? raw.sandboxId ?? '',
99
+ templateId: raw.templateID ?? raw.templateId ?? '',
100
+ state: raw.state ?? '',
101
+ clientId: raw.clientID ?? raw.clientId,
102
+ envdVersion: raw.envdVersion,
103
+ startedAt: raw.startedAt,
104
+ endAt: raw.endAt,
105
+ cpuCount: raw.cpuCount,
106
+ memoryMB: raw.memoryMB,
107
+ diskSizeMB: raw.diskSizeMB,
108
+ envdPort: raw.envdPort ?? 49983,
109
+ poddUrl: raw.poddURL ?? raw.poddUrl,
110
+ rootfsGeneration: raw.rootfsGeneration ?? 1,
111
+ volumeKey: raw.volumeKey,
112
+ metadata: raw.metadata,
113
+ createdAt: raw.createdAt,
114
+ timeoutSeconds: raw.timeoutSeconds,
115
+ leaseSeconds: raw.leaseSeconds,
116
+ autoResumeCount: raw.autoResumeCount,
117
+ reason: raw.reason,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Normalize command run/status response JSON.
123
+ *
124
+ * @param {Record<string, any>} raw
125
+ * @param {string} [fallbackId]
126
+ * @returns {import('./client.d.ts').CommandResult}
127
+ */
128
+ function normalizeCommandResult(raw, fallbackId = '') {
129
+ const id = raw.id ?? raw.cmdID ?? fallbackId;
130
+ const exitCode =
131
+ raw.exit_code !== undefined
132
+ ? raw.exit_code
133
+ : raw.exitCode !== undefined
134
+ ? raw.exitCode
135
+ : undefined;
136
+ const stdout = raw.stdout ?? raw.output ?? '';
137
+ const stderr = raw.stderr ?? '';
138
+ const output = raw.output ?? stdout;
139
+ return {
140
+ id,
141
+ cmdId: raw.cmdID ?? id,
142
+ running: raw.running ?? false,
143
+ pid: raw.pid,
144
+ exitCode,
145
+ stdout,
146
+ stderr,
147
+ output,
148
+ cursor: raw.cursor ?? 0,
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Parse JSON if body is non-empty, otherwise return undefined.
154
+ *
155
+ * @template T
156
+ * @param {Response} response
157
+ * @returns {Promise<T>}
158
+ */
159
+ async function readJsonOrUndefined(response) {
160
+ const text = await response.text();
161
+ if (!text) return /** @type {T} */ (undefined);
162
+ return JSON.parse(text);
163
+ }
164
+
165
+ /**
166
+ * Statically & dynamically typed HTTP client for CubePod Control & Data Plane.
167
+ */
168
+ export class CubePodClient {
169
+ /** @type {string} */
170
+ baseUrl;
171
+ /** @type {string | undefined} */
172
+ apiKey;
173
+ /** @type {number} */
174
+ timeoutMs;
175
+ /** @type {number} */
176
+ maxRetries;
177
+ /** @type {number} */
178
+ retryDelayMs;
179
+ /** @type {typeof globalThis.fetch} */
180
+ _fetch;
181
+ /** @type {Record<string, string>} */
182
+ defaultHeaders;
183
+
184
+ /**
185
+ * @param {import('./client.d.ts').CubePodClientOptions} [options]
186
+ */
187
+ constructor(options = {}) {
188
+ const rawBaseUrl =
189
+ options.baseUrl ??
190
+ readEnv('CUBEPOD_BASE_URL', 'CUBEPOD_API_URL') ??
191
+ 'http://localhost:8080';
192
+ this.baseUrl = rawBaseUrl.replace(/\/+$/, '');
193
+ this.apiKey = options.apiKey ?? readEnv('CUBEPOD_API_KEY', 'E2B_API_KEY');
194
+ this.timeoutMs = options.timeoutMs ?? 60_000;
195
+ this.maxRetries = options.maxRetries ?? 2;
196
+ this.retryDelayMs = options.retryDelayMs ?? 10;
197
+ this._fetch = options.fetch ?? globalThis.fetch;
198
+ this.defaultHeaders = { ...(options.headers ?? {}) };
199
+
200
+ if (typeof this._fetch !== 'function') {
201
+ throw new CubePodError('No fetch implementation available in this runtime');
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Build a full request URL from a path and optional query params.
207
+ *
208
+ * @param {string} path
209
+ * @param {Record<string, string | number | boolean | undefined>} [query]
210
+ * @returns {string}
211
+ */
212
+ _buildUrl(path, query) {
213
+ const base = path.startsWith('http://') || path.startsWith('https://')
214
+ ? path
215
+ : `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
216
+ if (!query) return base;
217
+
218
+ const params = new URLSearchParams();
219
+ for (const [key, value] of Object.entries(query)) {
220
+ if (value !== undefined) {
221
+ params.set(key, String(value));
222
+ }
223
+ }
224
+ const qs = params.toString();
225
+ if (!qs) return base;
226
+ return base.includes('?') ? `${base}&${qs}` : `${base}?${qs}`;
227
+ }
228
+
229
+ /**
230
+ * Execute an HTTP request with bearer auth, timeout, and transient 502/503/504 retries.
231
+ *
232
+ * @param {string} method
233
+ * @param {string} path
234
+ * @param {{
235
+ * query?: Record<string, string | number | boolean | undefined>;
236
+ * json?: unknown;
237
+ * body?: BodyInit | Uint8Array | null;
238
+ * headers?: Record<string, string>;
239
+ * signal?: AbortSignal;
240
+ * sandboxId?: string;
241
+ * includeAuth?: boolean;
242
+ * retry?: boolean;
243
+ * }} [options]
244
+ * @returns {Promise<Response>}
245
+ */
246
+ async _request(method, path, options = {}) {
247
+ const url = this._buildUrl(path, options.query);
248
+ const headers = new Headers(this.defaultHeaders);
249
+ if (options.includeAuth !== false && this.apiKey) {
250
+ headers.set('Authorization', `Bearer ${this.apiKey}`);
251
+ }
252
+ if (options.headers) {
253
+ for (const [k, v] of Object.entries(options.headers)) {
254
+ headers.set(k, v);
255
+ }
256
+ }
257
+
258
+ /** @type {BodyInit | undefined} */
259
+ let body;
260
+ if (options.json !== undefined) {
261
+ if (!headers.has('Content-Type')) {
262
+ headers.set('Content-Type', 'application/json');
263
+ }
264
+ body = JSON.stringify(options.json);
265
+ } else if (options.body !== undefined && options.body !== null) {
266
+ body = /** @type {BodyInit} */ (options.body);
267
+ }
268
+
269
+ const maxRetries = options.retry === false ? 0 : this.maxRetries;
270
+ let attempt = 0;
271
+
272
+ while (true) {
273
+ const { signal, cleanup } = createRequestSignal(this.timeoutMs, options.signal);
274
+ /** @type {Response} */
275
+ let response;
276
+ try {
277
+ response = await this._fetch(url, {
278
+ method,
279
+ headers,
280
+ body,
281
+ signal,
282
+ });
283
+ } catch (err) {
284
+ cleanup();
285
+ throw err instanceof CubePodError
286
+ ? err
287
+ : new CubePodError(err instanceof Error ? err.message : String(err), { cause: err });
288
+ }
289
+ cleanup();
290
+
291
+ if (response.ok) {
292
+ return response;
293
+ }
294
+
295
+ const apiErr = await parseAPIError(response, { sandboxId: options.sandboxId });
296
+ const isRetryableStatus =
297
+ apiErr.statusCode === 502 || apiErr.statusCode === 504 || apiErr.statusCode === 503;
298
+ const isTerminalReadyTimeout =
299
+ apiErr.statusCode === 503 &&
300
+ Boolean(apiErr.sandboxId || apiErr.logPath);
301
+
302
+ if (isRetryableStatus && !isTerminalReadyTimeout && attempt < maxRetries) {
303
+ attempt += 1;
304
+ await sleep(this.retryDelayMs * 2 ** (attempt - 1), options.signal);
305
+ continue;
306
+ }
307
+
308
+ throw apiErr;
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Check Gateway health and cluster counts.
314
+ *
315
+ * @param {import('./client.d.ts').RequestOptions} [options]
316
+ * @returns {Promise<import('./client.d.ts').HealthStatus>}
317
+ */
318
+ async health(options = {}) {
319
+ const resp = await this._request('GET', '/health', { signal: options.signal });
320
+ return readJsonOrUndefined(resp);
321
+ }
322
+
323
+ // ---------------------------------------------------------------------------
324
+ // Sandbox Lifecycle
325
+ // ---------------------------------------------------------------------------
326
+
327
+ /**
328
+ * Create or claim a sandbox.
329
+ *
330
+ * @param {import('./client.d.ts').CreateSandboxOptions} [options]
331
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
332
+ */
333
+ async createSandbox(options = {}) {
334
+ /** @type {Record<string, unknown>} */
335
+ const payload = {
336
+ templateID: options.templateId ?? 'cubeplex-ubuntu24-desktop',
337
+ };
338
+ if (options.timeoutSeconds !== undefined) {
339
+ payload.timeout = options.timeoutSeconds;
340
+ } else if (options.timeout !== undefined) {
341
+ payload.timeout = options.timeout;
342
+ }
343
+ if (options.metadata !== undefined) {
344
+ payload.metadata = options.metadata;
345
+ }
346
+ if (options.envVars !== undefined) {
347
+ payload.envVars = options.envVars;
348
+ }
349
+ if (options.autoPause !== undefined) {
350
+ payload.autoPause = options.autoPause;
351
+ }
352
+ if (options.autoResume !== undefined) {
353
+ payload.autoResume = options.autoResume;
354
+ }
355
+ if (options.warmPoolRef !== undefined) {
356
+ payload.warmPoolRef = options.warmPoolRef;
357
+ }
358
+
359
+ /** @type {Record<string, unknown>} */
360
+ const extension = {};
361
+ if (options.volumeKey !== undefined) extension.volumeKey = options.volumeKey;
362
+ if (options.rootfsSize !== undefined) extension.rootfsSize = options.rootfsSize;
363
+ if (options.workspaceSize !== undefined) extension.workspaceSize = options.workspaceSize;
364
+ if (options.networkPolicy !== undefined) extension.networkPolicy = options.networkPolicy;
365
+ if (options.secretBindings !== undefined) extension.secretBindings = options.secretBindings;
366
+ if (Object.keys(extension).length > 0) {
367
+ payload.extension = extension;
368
+ }
369
+
370
+ const resp = await this._request('POST', '/sandboxes', {
371
+ json: payload,
372
+ signal: options.signal,
373
+ });
374
+ const data = await readJsonOrUndefined(resp);
375
+ return normalizeSandboxInfo(data ?? {});
376
+ }
377
+
378
+ /**
379
+ * Fetch status and metadata for an existing sandbox.
380
+ *
381
+ * @param {string} sandboxId
382
+ * @param {import('./client.d.ts').RequestOptions} [options]
383
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
384
+ */
385
+ async getSandbox(sandboxId, options = {}) {
386
+ const resp = await this._request('GET', `/sandboxes/${encodeURIComponent(sandboxId)}`, {
387
+ signal: options.signal,
388
+ sandboxId,
389
+ });
390
+ const data = await readJsonOrUndefined(resp);
391
+ return normalizeSandboxInfo(data ?? {});
392
+ }
393
+
394
+ /**
395
+ * List sandboxes, optionally filtered by state and/or templateId.
396
+ *
397
+ * @param {import('./client.d.ts').ListSandboxesOptions} [filter]
398
+ * @param {import('./client.d.ts').RequestOptions} [options]
399
+ * @returns {Promise<import('./client.d.ts').SandboxInfo[]>}
400
+ */
401
+ async listSandboxes(filter = {}, options = {}) {
402
+ const resp = await this._request('GET', '/sandboxes', {
403
+ query: {
404
+ state: filter.state,
405
+ templateID: filter.templateId,
406
+ },
407
+ signal: options.signal ?? filter.signal,
408
+ });
409
+ const data = await readJsonOrUndefined(resp);
410
+ const items = Array.isArray(data) ? data : (data?.sandboxes ?? []);
411
+ return items.map(normalizeSandboxInfo);
412
+ }
413
+
414
+ /**
415
+ * Connect to a sandbox, automatically resuming it if Paused.
416
+ *
417
+ * @param {string} sandboxId
418
+ * @param {import('./client.d.ts').RequestOptions} [options]
419
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
420
+ */
421
+ async connectSandbox(sandboxId, options = {}) {
422
+ const resp = await this._request(
423
+ 'POST',
424
+ `/sandboxes/${encodeURIComponent(sandboxId)}/connect`,
425
+ { signal: options.signal, sandboxId },
426
+ );
427
+ const data = await readJsonOrUndefined(resp);
428
+ return normalizeSandboxInfo(data ?? {});
429
+ }
430
+
431
+ /**
432
+ * Suspend compute while retaining RootFS Upper and Workspace block PVCs.
433
+ *
434
+ * @param {string} sandboxId
435
+ * @param {import('./client.d.ts').RequestOptions} [options]
436
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
437
+ */
438
+ async pauseSandbox(sandboxId, options = {}) {
439
+ const resp = await this._request(
440
+ 'POST',
441
+ `/sandboxes/${encodeURIComponent(sandboxId)}/pause`,
442
+ { signal: options.signal, sandboxId },
443
+ );
444
+ const data = await readJsonOrUndefined(resp);
445
+ return normalizeSandboxInfo(data ?? {});
446
+ }
447
+
448
+ /**
449
+ * Set or renew the sandbox idle auto-pause timeout.
450
+ *
451
+ * @param {string} sandboxId
452
+ * @param {number} [timeoutSeconds=1800]
453
+ * @param {import('./client.d.ts').RequestOptions} [options]
454
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
455
+ */
456
+ async setSandboxTimeout(sandboxId, timeoutSeconds = 1800, options = {}) {
457
+ const resp = await this._request(
458
+ 'POST',
459
+ `/sandboxes/${encodeURIComponent(sandboxId)}/timeout`,
460
+ {
461
+ json: { timeoutSeconds },
462
+ signal: options.signal,
463
+ sandboxId,
464
+ },
465
+ );
466
+ const data = await readJsonOrUndefined(resp);
467
+ return normalizeSandboxInfo(data ?? {});
468
+ }
469
+
470
+ /**
471
+ * Refresh sandbox idle timeout via E2B-standard `/refreshes`.
472
+ *
473
+ * @param {string} sandboxId
474
+ * @param {number} [durationSeconds=300]
475
+ * @param {import('./client.d.ts').RequestOptions} [options]
476
+ * @returns {Promise<void>}
477
+ */
478
+ async refreshSandbox(sandboxId, durationSeconds = 300, options = {}) {
479
+ await this._request(
480
+ 'POST',
481
+ `/sandboxes/${encodeURIComponent(sandboxId)}/refreshes`,
482
+ {
483
+ json: { duration: durationSeconds },
484
+ signal: options.signal,
485
+ sandboxId,
486
+ },
487
+ );
488
+ }
489
+
490
+ /**
491
+ * Acquire or renew a lease protecting the sandbox against idle pause.
492
+ *
493
+ * @param {string} sandboxId
494
+ * @param {number} [leaseSeconds=300]
495
+ * @param {import('./client.d.ts').RequestOptions} [options]
496
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
497
+ */
498
+ async acquireLease(sandboxId, leaseSeconds = 300, options = {}) {
499
+ const resp = await this._request(
500
+ 'POST',
501
+ `/sandboxes/${encodeURIComponent(sandboxId)}/lease`,
502
+ {
503
+ json: { leaseSeconds },
504
+ signal: options.signal,
505
+ sandboxId,
506
+ },
507
+ );
508
+ const data = await readJsonOrUndefined(resp);
509
+ return normalizeSandboxInfo(data ?? {});
510
+ }
511
+
512
+ /**
513
+ * Reset the persistent RootFS Upper PVC to a clean Base Image while preserving `/workspace`.
514
+ *
515
+ * @param {string} sandboxId
516
+ * @param {import('./client.d.ts').RequestOptions} [options]
517
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
518
+ */
519
+ async resetRootfs(sandboxId, options = {}) {
520
+ const resp = await this._request(
521
+ 'POST',
522
+ `/sandboxes/${encodeURIComponent(sandboxId)}/reset-rootfs`,
523
+ { signal: options.signal, sandboxId },
524
+ );
525
+ const data = await readJsonOrUndefined(resp);
526
+ return normalizeSandboxInfo(data ?? {});
527
+ }
528
+
529
+ /**
530
+ * Clone an existing sandbox via Copy-on-Write block snapshots.
531
+ *
532
+ * @param {string} sandboxId
533
+ * @param {import('./client.d.ts').ForkSandboxOptions} [forkOptions]
534
+ * @param {import('./client.d.ts').RequestOptions} [options]
535
+ * @returns {Promise<import('./client.d.ts').SandboxInfo>}
536
+ */
537
+ async forkSandbox(sandboxId, forkOptions = {}, options = {}) {
538
+ /** @type {Record<string, unknown>} */
539
+ const payload = {};
540
+ if (forkOptions.volumeKey !== undefined) payload.volumeKey = forkOptions.volumeKey;
541
+ if (forkOptions.metadata !== undefined) payload.metadata = forkOptions.metadata;
542
+
543
+ const resp = await this._request(
544
+ 'POST',
545
+ `/sandboxes/${encodeURIComponent(sandboxId)}/fork`,
546
+ {
547
+ json: Object.keys(payload).length > 0 ? payload : undefined,
548
+ signal: options.signal ?? forkOptions.signal,
549
+ sandboxId,
550
+ },
551
+ );
552
+ const data = await readJsonOrUndefined(resp);
553
+ return normalizeSandboxInfo(data ?? {});
554
+ }
555
+
556
+ /**
557
+ * Terminate and delete a sandbox.
558
+ *
559
+ * @param {string} sandboxId
560
+ * @param {import('./client.d.ts').DeleteSandboxOptions} [deleteOptions]
561
+ * @param {import('./client.d.ts').RequestOptions} [options]
562
+ * @returns {Promise<void>}
563
+ */
564
+ async deleteSandbox(sandboxId, deleteOptions = {}, options = {}) {
565
+ await this._request('DELETE', `/sandboxes/${encodeURIComponent(sandboxId)}`, {
566
+ query:
567
+ deleteOptions.deleteVolumes !== undefined
568
+ ? { deleteVolumes: deleteOptions.deleteVolumes }
569
+ : undefined,
570
+ signal: options.signal ?? deleteOptions.signal,
571
+ sandboxId,
572
+ });
573
+ }
574
+
575
+ /**
576
+ * Get public ingress host/URL metadata for a sandbox port.
577
+ *
578
+ * @param {string} sandboxId
579
+ * @param {number} port
580
+ * @param {import('./client.d.ts').RequestOptions} [options]
581
+ * @returns {Promise<import('./client.d.ts').EndpointHost>}
582
+ */
583
+ async getEndpointHost(sandboxId, port, options = {}) {
584
+ const resp = await this._request(
585
+ 'GET',
586
+ `/sandboxes/${encodeURIComponent(sandboxId)}/endpoints/${port}`,
587
+ { signal: options.signal, sandboxId },
588
+ );
589
+ const data = (await readJsonOrUndefined(resp)) ?? {};
590
+ return {
591
+ host: data.host ?? data.endpoint ?? '',
592
+ url: data.url ?? (data.host ? `http://${data.host}` : ''),
593
+ endpoint: data.endpoint ?? data.host ?? '',
594
+ port: data.port ?? port,
595
+ sandboxId: data.sandboxID ?? data.sandboxId ?? sandboxId,
596
+ };
597
+ }
598
+
599
+ /**
600
+ * Get the public host string for a sandbox port (E2B `get_host` compatible).
601
+ *
602
+ * @param {string} sandboxId
603
+ * @param {number} port
604
+ * @param {import('./client.d.ts').RequestOptions} [options]
605
+ * @returns {Promise<string>}
606
+ */
607
+ async getHost(sandboxId, port, options = {}) {
608
+ const info = await this.getEndpointHost(sandboxId, port, options);
609
+ return info.host;
610
+ }
611
+
612
+ /**
613
+ * Mint an HMAC-SHA256 signed `/panel/{token}/` reverse-proxy endpoint for a sandbox port.
614
+ *
615
+ * @param {string} sandboxId
616
+ * @param {number} port
617
+ * @param {import('./client.d.ts').CreateEndpointOptions} [endpointOptions]
618
+ * @param {import('./client.d.ts').RequestOptions} [options]
619
+ * @returns {Promise<import('./client.d.ts').PanelEndpoint>}
620
+ */
621
+ async createEndpoint(sandboxId, port, endpointOptions = {}, options = {}) {
622
+ /** @type {Record<string, unknown>} */
623
+ const payload = {};
624
+ if (endpointOptions.expiresInSeconds !== undefined) {
625
+ payload.expiresInSeconds = endpointOptions.expiresInSeconds;
626
+ }
627
+ if (endpointOptions.targetUrl !== undefined) {
628
+ payload.targetUrl = endpointOptions.targetUrl;
629
+ }
630
+
631
+ const resp = await this._request(
632
+ 'POST',
633
+ `/sandboxes/${encodeURIComponent(sandboxId)}/endpoints/${port}`,
634
+ {
635
+ json: payload,
636
+ signal: options.signal ?? endpointOptions.signal,
637
+ sandboxId,
638
+ },
639
+ );
640
+ const data = (await readJsonOrUndefined(resp)) ?? {};
641
+ return {
642
+ url: data.url ?? '',
643
+ token: data.token ?? '',
644
+ expiresAt: data.expiresAt,
645
+ };
646
+ }
647
+
648
+ // ---------------------------------------------------------------------------
649
+ // Commands
650
+ // ---------------------------------------------------------------------------
651
+
652
+ /**
653
+ * Run a foreground or background shell command inside the sandbox.
654
+ *
655
+ * IMPORTANT: `uid` and `gid` are omitted from the JSON body unless explicitly
656
+ * passed by the caller so the server/template `USER` is preserved.
657
+ *
658
+ * @param {string} sandboxId
659
+ * @param {string} command
660
+ * @param {import('./client.d.ts').RunCommandOptions} [options]
661
+ * @returns {Promise<import('./client.d.ts').CommandResult>}
662
+ */
663
+ async runCommand(sandboxId, command, options = {}) {
664
+ /** @type {Record<string, unknown>} */
665
+ const payload = {
666
+ command,
667
+ background: Boolean(options.background),
668
+ };
669
+ if (options.workdir !== undefined) payload.workdir = options.workdir;
670
+ if (options.envs !== undefined) payload.envs = options.envs;
671
+ if (options.uid !== undefined) payload.uid = options.uid;
672
+ if (options.gid !== undefined) payload.gid = options.gid;
673
+
674
+ const resp = await this._request(
675
+ 'POST',
676
+ `/sandboxes/${encodeURIComponent(sandboxId)}/commands/run`,
677
+ {
678
+ json: payload,
679
+ signal: options.signal,
680
+ sandboxId,
681
+ },
682
+ );
683
+ const data = (await readJsonOrUndefined(resp)) ?? {};
684
+ return normalizeCommandResult(data);
685
+ }
686
+
687
+ /**
688
+ * Inspect background command process status, PID, exit code, and log cursor.
689
+ *
690
+ * @param {string} sandboxId
691
+ * @param {string} cmdId
692
+ * @param {import('./client.d.ts').RequestOptions} [options]
693
+ * @returns {Promise<import('./client.d.ts').CommandResult>}
694
+ */
695
+ async getCommandStatus(sandboxId, cmdId, options = {}) {
696
+ const resp = await this._request(
697
+ 'GET',
698
+ `/sandboxes/${encodeURIComponent(sandboxId)}/commands/${encodeURIComponent(cmdId)}/status`,
699
+ { signal: options.signal, sandboxId },
700
+ );
701
+ const data = (await readJsonOrUndefined(resp)) ?? {};
702
+ return normalizeCommandResult(data, cmdId);
703
+ }
704
+
705
+ /**
706
+ * Read incremental command logs via stateless byte-offset `cursor`.
707
+ *
708
+ * @param {string} sandboxId
709
+ * @param {string} cmdId
710
+ * @param {number | import('./client.d.ts').GetCommandLogsOptions} [options]
711
+ * @returns {Promise<import('./client.d.ts').CommandLogs>}
712
+ */
713
+ async getCommandLogs(sandboxId, cmdId, options = {}) {
714
+ const opts = typeof options === 'number' ? { cursor: options } : options;
715
+ const resp = await this._request(
716
+ 'GET',
717
+ `/sandboxes/${encodeURIComponent(sandboxId)}/commands/${encodeURIComponent(cmdId)}/logs`,
718
+ {
719
+ query: opts.cursor !== undefined ? { cursor: opts.cursor } : undefined,
720
+ signal: opts.signal,
721
+ sandboxId,
722
+ },
723
+ );
724
+ const data = (await readJsonOrUndefined(resp)) ?? {};
725
+ const exitCode =
726
+ data.exit_code !== undefined
727
+ ? data.exit_code
728
+ : data.exitCode !== undefined
729
+ ? data.exitCode
730
+ : undefined;
731
+ return {
732
+ id: data.id ?? data.cmdID ?? cmdId,
733
+ cmdId: data.cmdID ?? data.id ?? cmdId,
734
+ content: data.content ?? '',
735
+ cursor: data.cursor ?? opts.cursor ?? 0,
736
+ running: data.running ?? false,
737
+ exitCode,
738
+ };
739
+ }
740
+
741
+ /**
742
+ * Send SIGKILL to a running command process group.
743
+ *
744
+ * @param {string} sandboxId
745
+ * @param {string} cmdId
746
+ * @param {import('./client.d.ts').RequestOptions} [options]
747
+ * @returns {Promise<{ id: string; killed: boolean }>}
748
+ */
749
+ async killCommand(sandboxId, cmdId, options = {}) {
750
+ const resp = await this._request(
751
+ 'POST',
752
+ `/sandboxes/${encodeURIComponent(sandboxId)}/commands/${encodeURIComponent(cmdId)}/kill`,
753
+ { signal: options.signal, sandboxId },
754
+ );
755
+ const data = (await readJsonOrUndefined(resp)) ?? {};
756
+ return {
757
+ id: data.id ?? cmdId,
758
+ killed: Boolean(data.killed ?? true),
759
+ };
760
+ }
761
+
762
+ // ---------------------------------------------------------------------------
763
+ // Code Interpreter
764
+ // ---------------------------------------------------------------------------
765
+
766
+ /**
767
+ * Execute code via the in-guest Jupyter/Code Interpreter, streaming NDJSON events.
768
+ *
769
+ * @param {string} sandboxId
770
+ * @param {string} code
771
+ * @param {import('./client.d.ts').RunCodeOptions} [options]
772
+ * @returns {Promise<import('./client.d.ts').ExecutionResult>}
773
+ */
774
+ async runCode(sandboxId, code, options = {}) {
775
+ /** @type {Record<string, unknown>} */
776
+ const payload = { code };
777
+ if (options.contextId !== undefined) payload.context_id = options.contextId;
778
+ if (options.language !== undefined) payload.language = options.language;
779
+ if (options.envVars !== undefined) payload.env_vars = options.envVars;
780
+
781
+ const resp = await this._request(
782
+ 'POST',
783
+ `/sandboxes/${encodeURIComponent(sandboxId)}/code/execute`,
784
+ {
785
+ json: payload,
786
+ headers: { Accept: 'application/x-ndjson, application/json' },
787
+ signal: options.signal,
788
+ sandboxId,
789
+ },
790
+ );
791
+
792
+ /** @type {{ stdout: string[]; stderr: string[] }} */
793
+ const logs = { stdout: [], stderr: [] };
794
+ /** @type {import('./client.d.ts').CodeResult[]} */
795
+ const results = [];
796
+ /** @type {import('./client.d.ts').CodeExecutionError | undefined} */
797
+ let error;
798
+ /** @type {number | undefined} */
799
+ let executionCount;
800
+
801
+ /**
802
+ * @param {Record<string, any>} event
803
+ */
804
+ const handleEvent = async (event) => {
805
+ if (!event || typeof event !== 'object') return;
806
+ switch (event.type) {
807
+ case 'stdout': {
808
+ const text = typeof event.text === 'string' ? event.text : '';
809
+ logs.stdout.push(text);
810
+ if (options.onStdout) {
811
+ await options.onStdout({
812
+ text,
813
+ line: text,
814
+ timestamp: event.timestamp,
815
+ error: false,
816
+ });
817
+ }
818
+ break;
819
+ }
820
+ case 'stderr': {
821
+ const text = typeof event.text === 'string' ? event.text : '';
822
+ logs.stderr.push(text);
823
+ if (options.onStderr) {
824
+ await options.onStderr({
825
+ text,
826
+ line: text,
827
+ timestamp: event.timestamp,
828
+ error: true,
829
+ });
830
+ }
831
+ break;
832
+ }
833
+ case 'result': {
834
+ /** @type {import('./client.d.ts').CodeResult} */
835
+ const resultObj = {
836
+ text: event.text ?? undefined,
837
+ png: event.png ?? undefined,
838
+ html: event.html ?? undefined,
839
+ isMainResult: event.is_main_result ?? event.isMainResult ?? true,
840
+ raw: event,
841
+ };
842
+ results.push(resultObj);
843
+ if (options.onResult) {
844
+ await options.onResult(resultObj);
845
+ }
846
+ break;
847
+ }
848
+ case 'error': {
849
+ error = {
850
+ name: event.name ?? 'ExecutionError',
851
+ value: event.value ?? '',
852
+ traceback: event.traceback ?? '',
853
+ exitCode: event.exitCode ?? event.exit_code,
854
+ };
855
+ if (options.onError) {
856
+ await options.onError(error);
857
+ }
858
+ break;
859
+ }
860
+ case 'number_of_executions': {
861
+ executionCount = event.execution_count ?? event.executionCount;
862
+ break;
863
+ }
864
+ default:
865
+ break;
866
+ }
867
+ };
868
+
869
+ const contentType = resp.headers.get('content-type') ?? '';
870
+ if (resp.body && !contentType.includes('application/json')) {
871
+ await readNdjsonStream(resp.body, handleEvent);
872
+ } else {
873
+ const text = await resp.text();
874
+ if (text.trim()) {
875
+ try {
876
+ const parsed = JSON.parse(text);
877
+ if (Array.isArray(parsed)) {
878
+ for (const item of parsed) {
879
+ await handleEvent(item);
880
+ }
881
+ } else {
882
+ await handleEvent(parsed);
883
+ }
884
+ } catch {
885
+ for (const line of text.split('\n')) {
886
+ const trimmed = line.trim();
887
+ if (trimmed) {
888
+ await handleEvent(JSON.parse(trimmed));
889
+ }
890
+ }
891
+ }
892
+ }
893
+ }
894
+
895
+ const stdout = logs.stdout.join('');
896
+ const stderr = logs.stderr.join('');
897
+ const lastResultText = results.length > 0 ? results[results.length - 1].text : undefined;
898
+
899
+ return {
900
+ logs,
901
+ stdout,
902
+ stderr,
903
+ results,
904
+ error,
905
+ executionCount,
906
+ text: lastResultText ?? (stdout || undefined),
907
+ };
908
+ }
909
+
910
+ /**
911
+ * Create a stateful Code Interpreter execution context.
912
+ *
913
+ * @param {string} sandboxId
914
+ * @param {import('./client.d.ts').CreateContextOptions} [contextOptions]
915
+ * @param {import('./client.d.ts').RequestOptions} [options]
916
+ * @returns {Promise<import('./client.d.ts').CodeContext>}
917
+ */
918
+ async createContext(sandboxId, contextOptions = {}, options = {}) {
919
+ /** @type {Record<string, unknown>} */
920
+ const payload = {};
921
+ if (contextOptions.id !== undefined) payload.id = contextOptions.id;
922
+ if (contextOptions.language !== undefined) payload.language = contextOptions.language;
923
+ if (contextOptions.cwd !== undefined) payload.cwd = contextOptions.cwd;
924
+
925
+ const resp = await this._request(
926
+ 'POST',
927
+ `/sandboxes/${encodeURIComponent(sandboxId)}/code/contexts`,
928
+ {
929
+ json: payload,
930
+ signal: options.signal ?? contextOptions.signal,
931
+ sandboxId,
932
+ },
933
+ );
934
+ return (await readJsonOrUndefined(resp)) ?? {};
935
+ }
936
+
937
+ /**
938
+ * List active Code Interpreter contexts inside a sandbox.
939
+ *
940
+ * @param {string} sandboxId
941
+ * @param {import('./client.d.ts').RequestOptions} [options]
942
+ * @returns {Promise<import('./client.d.ts').CodeContext[]>}
943
+ */
944
+ async listContexts(sandboxId, options = {}) {
945
+ const resp = await this._request(
946
+ 'GET',
947
+ `/sandboxes/${encodeURIComponent(sandboxId)}/code/contexts`,
948
+ { signal: options.signal, sandboxId },
949
+ );
950
+ const data = await readJsonOrUndefined(resp);
951
+ return Array.isArray(data) ? data : (data?.contexts ?? []);
952
+ }
953
+
954
+ /**
955
+ * Get metadata for a Code Interpreter context.
956
+ *
957
+ * @param {string} sandboxId
958
+ * @param {string} contextId
959
+ * @param {import('./client.d.ts').RequestOptions} [options]
960
+ * @returns {Promise<import('./client.d.ts').CodeContext>}
961
+ */
962
+ async getContext(sandboxId, contextId, options = {}) {
963
+ const resp = await this._request(
964
+ 'GET',
965
+ `/sandboxes/${encodeURIComponent(sandboxId)}/code/contexts/${encodeURIComponent(contextId)}`,
966
+ { signal: options.signal, sandboxId },
967
+ );
968
+ return (await readJsonOrUndefined(resp)) ?? {};
969
+ }
970
+
971
+ /**
972
+ * Restart a Code Interpreter context (clearing in-memory variables).
973
+ *
974
+ * @param {string} sandboxId
975
+ * @param {string} contextId
976
+ * @param {import('./client.d.ts').RequestOptions} [options]
977
+ * @returns {Promise<import('./client.d.ts').CodeContext>}
978
+ */
979
+ async restartContext(sandboxId, contextId, options = {}) {
980
+ const resp = await this._request(
981
+ 'POST',
982
+ `/sandboxes/${encodeURIComponent(sandboxId)}/code/contexts/${encodeURIComponent(contextId)}/restart`,
983
+ { signal: options.signal, sandboxId },
984
+ );
985
+ return (await readJsonOrUndefined(resp)) ?? {};
986
+ }
987
+
988
+ /**
989
+ * Delete a Code Interpreter context and terminate its worker process.
990
+ *
991
+ * @param {string} sandboxId
992
+ * @param {string} contextId
993
+ * @param {import('./client.d.ts').RequestOptions} [options]
994
+ * @returns {Promise<void>}
995
+ */
996
+ async deleteContext(sandboxId, contextId, options = {}) {
997
+ await this._request(
998
+ 'DELETE',
999
+ `/sandboxes/${encodeURIComponent(sandboxId)}/code/contexts/${encodeURIComponent(contextId)}`,
1000
+ { signal: options.signal, sandboxId },
1001
+ );
1002
+ }
1003
+
1004
+ // ---------------------------------------------------------------------------
1005
+ // Files
1006
+ // ---------------------------------------------------------------------------
1007
+
1008
+ /**
1009
+ * Write a file inside the sandbox.
1010
+ *
1011
+ * IMPORTANT: `uid` and `gid` query parameters are omitted unless explicitly passed
1012
+ * by the caller so the server/template `USER` is preserved.
1013
+ *
1014
+ * @param {string} sandboxId
1015
+ * @param {string} path
1016
+ * @param {string | Uint8Array | ArrayBuffer} content
1017
+ * @param {import('./client.d.ts').WriteFileOptions} [options]
1018
+ * @returns {Promise<{ status?: string; path: string; size: number }>}
1019
+ */
1020
+ async writeFile(sandboxId, path, content, options = {}) {
1021
+ /** @type {Uint8Array} */
1022
+ let data;
1023
+ if (typeof content === 'string') {
1024
+ data = textEncoder.encode(content);
1025
+ } else if (content instanceof Uint8Array) {
1026
+ data = content;
1027
+ } else if (content instanceof ArrayBuffer) {
1028
+ data = new Uint8Array(content);
1029
+ } else {
1030
+ throw new TypeError('content must be a string, Uint8Array, or ArrayBuffer');
1031
+ }
1032
+
1033
+ /** @type {Record<string, string | number | undefined>} */
1034
+ const query = { path };
1035
+ if (options.uid !== undefined) query.uid = options.uid;
1036
+ if (options.gid !== undefined) query.gid = options.gid;
1037
+ if (options.mode !== undefined) query.mode = options.mode;
1038
+
1039
+ const resp = await this._request(
1040
+ 'PUT',
1041
+ `/sandboxes/${encodeURIComponent(sandboxId)}/files`,
1042
+ {
1043
+ query,
1044
+ body: data,
1045
+ headers: { 'Content-Type': 'application/octet-stream' },
1046
+ signal: options.signal,
1047
+ sandboxId,
1048
+ },
1049
+ );
1050
+ const res = (await readJsonOrUndefined(resp)) ?? {};
1051
+ return {
1052
+ status: res.status,
1053
+ path: res.path ?? path,
1054
+ size: res.size ?? data.byteLength,
1055
+ };
1056
+ }
1057
+
1058
+ /**
1059
+ * Read raw file bytes from inside the sandbox.
1060
+ *
1061
+ * @param {string} sandboxId
1062
+ * @param {string} path
1063
+ * @param {import('./client.d.ts').RequestOptions} [options]
1064
+ * @returns {Promise<Uint8Array>}
1065
+ */
1066
+ async readFileBytes(sandboxId, path, options = {}) {
1067
+ const resp = await this._request(
1068
+ 'GET',
1069
+ `/sandboxes/${encodeURIComponent(sandboxId)}/files`,
1070
+ {
1071
+ query: { path },
1072
+ signal: options.signal,
1073
+ sandboxId,
1074
+ },
1075
+ );
1076
+ return new Uint8Array(await resp.arrayBuffer());
1077
+ }
1078
+
1079
+ /**
1080
+ * Read a UTF-8 text file from inside the sandbox.
1081
+ *
1082
+ * @param {string} sandboxId
1083
+ * @param {string} path
1084
+ * @param {import('./client.d.ts').RequestOptions} [options]
1085
+ * @returns {Promise<string>}
1086
+ */
1087
+ async readFileText(sandboxId, path, options = {}) {
1088
+ const bytes = await this.readFileBytes(sandboxId, path, options);
1089
+ return textDecoder.decode(bytes);
1090
+ }
1091
+
1092
+ /**
1093
+ * Remove a file or directory inside the sandbox.
1094
+ *
1095
+ * @param {string} sandboxId
1096
+ * @param {string} path
1097
+ * @param {import('./client.d.ts').RequestOptions} [options]
1098
+ * @returns {Promise<{ status?: string; deleted?: string }>}
1099
+ */
1100
+ async removeFile(sandboxId, path, options = {}) {
1101
+ const resp = await this._request(
1102
+ 'DELETE',
1103
+ `/sandboxes/${encodeURIComponent(sandboxId)}/files`,
1104
+ {
1105
+ query: { path },
1106
+ signal: options.signal,
1107
+ sandboxId,
1108
+ },
1109
+ );
1110
+ return (await readJsonOrUndefined(resp)) ?? { status: 'ok', deleted: path };
1111
+ }
1112
+
1113
+ /**
1114
+ * List files and directories at `path` inside the sandbox.
1115
+ *
1116
+ * @param {string} sandboxId
1117
+ * @param {string} [path='/workspace']
1118
+ * @param {import('./client.d.ts').RequestOptions} [options]
1119
+ * @returns {Promise<import('./client.d.ts').FileEntry[]>}
1120
+ */
1121
+ async listFiles(sandboxId, path = '/workspace', options = {}) {
1122
+ const resp = await this._request(
1123
+ 'GET',
1124
+ `/sandboxes/${encodeURIComponent(sandboxId)}/files/list`,
1125
+ {
1126
+ query: { path },
1127
+ signal: options.signal,
1128
+ sandboxId,
1129
+ },
1130
+ );
1131
+ const data = await readJsonOrUndefined(resp);
1132
+ const entries = Array.isArray(data) ? data : (data?.entries ?? []);
1133
+ return entries.map((/** @type {Record<string, any>} */ entry) => ({
1134
+ name: entry.name ?? '',
1135
+ path: entry.path ?? '',
1136
+ isDir: Boolean(entry.is_dir ?? entry.isDir ?? false),
1137
+ size: entry.size ?? 0,
1138
+ mode: entry.mode ?? '0644',
1139
+ }));
1140
+ }
1141
+
1142
+ /**
1143
+ * Extract a tar.gz archive (or file map) into the sandbox in a single HTTP request.
1144
+ *
1145
+ * @param {string} sandboxId
1146
+ * @param {Uint8Array | ArrayBuffer | Record<string, string | Uint8Array | ArrayBuffer>} archiveOrFiles
1147
+ * @param {import('./client.d.ts').ArchiveSyncOptions} [options]
1148
+ * @returns {Promise<{ status: string; extracted?: number }>}
1149
+ */
1150
+ async archiveSync(sandboxId, archiveOrFiles, options = {}) {
1151
+ /** @type {Uint8Array} */
1152
+ let payloadBytes;
1153
+ if (archiveOrFiles instanceof Uint8Array) {
1154
+ payloadBytes = archiveOrFiles;
1155
+ } else if (archiveOrFiles instanceof ArrayBuffer) {
1156
+ payloadBytes = new Uint8Array(archiveOrFiles);
1157
+ } else if (archiveOrFiles && typeof archiveOrFiles === 'object') {
1158
+ payloadBytes = await buildTarGzBytes(archiveOrFiles, {
1159
+ uid: options.uid,
1160
+ gid: options.gid,
1161
+ });
1162
+ } else {
1163
+ throw new TypeError('archiveOrFiles must be a Uint8Array, ArrayBuffer, or file map');
1164
+ }
1165
+
1166
+ /** @type {Record<string, string | number | undefined>} */
1167
+ const query = {
1168
+ dest: options.dest ?? '/workspace',
1169
+ };
1170
+ if (options.removePaths && options.removePaths.length > 0) {
1171
+ query.remove_paths = options.removePaths.join(',');
1172
+ }
1173
+ if (options.uid !== undefined) query.uid = options.uid;
1174
+ if (options.gid !== undefined) query.gid = options.gid;
1175
+
1176
+ const resp = await this._request(
1177
+ 'POST',
1178
+ `/sandboxes/${encodeURIComponent(sandboxId)}/files/archive-sync`,
1179
+ {
1180
+ query,
1181
+ body: payloadBytes,
1182
+ headers: { 'Content-Type': 'application/gzip' },
1183
+ signal: options.signal,
1184
+ sandboxId,
1185
+ },
1186
+ );
1187
+ return (await readJsonOrUndefined(resp)) ?? { status: 'ok' };
1188
+ }
1189
+
1190
+ // ---------------------------------------------------------------------------
1191
+ // Templates & WarmPools (CEP-0019)
1192
+ // ---------------------------------------------------------------------------
1193
+
1194
+ /**
1195
+ * List templates from `/templates` (supports both E2B array and legacy wrapper).
1196
+ *
1197
+ * @param {import('./client.d.ts').ListTemplatesOptions} [options]
1198
+ * @returns {Promise<import('./client.d.ts').E2BTemplate[]>}
1199
+ */
1200
+ async listTemplates(options = {}) {
1201
+ const resp = await this._request('GET', '/templates', {
1202
+ query: options.teamId !== undefined ? { teamID: options.teamId } : undefined,
1203
+ signal: options.signal,
1204
+ });
1205
+ const data = await readJsonOrUndefined(resp);
1206
+ return Array.isArray(data) ? data : (data?.templates ?? []);
1207
+ }
1208
+
1209
+ /**
1210
+ * List templates with cursor pagination via `/v2/templates` and `X-Next-Token`.
1211
+ *
1212
+ * @param {import('./client.d.ts').ListTemplatesV2Options} [options]
1213
+ * @returns {Promise<import('./client.d.ts').ListTemplatesV2Response>}
1214
+ */
1215
+ async listTemplatesV2(options = {}) {
1216
+ const resp = await this._request('GET', '/v2/templates', {
1217
+ query: {
1218
+ limit: options.limit,
1219
+ nextToken: options.nextToken,
1220
+ },
1221
+ signal: options.signal,
1222
+ });
1223
+ const templates = (await readJsonOrUndefined(resp)) ?? [];
1224
+ const rawNextToken = resp.headers.get('X-Next-Token');
1225
+ return {
1226
+ templates: Array.isArray(templates) ? templates : (templates.templates ?? []),
1227
+ nextToken: rawNextToken ? rawNextToken : undefined,
1228
+ };
1229
+ }
1230
+
1231
+ /**
1232
+ * Get a template (and its builds) by ID or alias, safely escaping slashes/colons.
1233
+ *
1234
+ * @param {string} templateIdOrAlias
1235
+ * @param {import('./client.d.ts').GetTemplateOptions} [options]
1236
+ * @returns {Promise<import('./client.d.ts').TemplateWithBuilds>}
1237
+ */
1238
+ async getTemplate(templateIdOrAlias, options = {}) {
1239
+ const path = options.byAlias
1240
+ ? `/templates/aliases/${encodeURIComponent(templateIdOrAlias)}`
1241
+ : `/templates/${encodeURIComponent(templateIdOrAlias)}`;
1242
+ const resp = await this._request('GET', path, { signal: options.signal });
1243
+ return (await readJsonOrUndefined(resp)) ?? {};
1244
+ }
1245
+
1246
+ /**
1247
+ * Resolve a template directly via `/templates/aliases/{alias}`.
1248
+ *
1249
+ * @param {string} alias
1250
+ * @param {import('./client.d.ts').RequestOptions} [options]
1251
+ * @returns {Promise<import('./client.d.ts').E2BTemplate>}
1252
+ */
1253
+ async getTemplateByAlias(alias, options = {}) {
1254
+ const resp = await this._request(
1255
+ 'GET',
1256
+ `/templates/aliases/${encodeURIComponent(alias)}`,
1257
+ { signal: options.signal },
1258
+ );
1259
+ return (await readJsonOrUndefined(resp)) ?? {};
1260
+ }
1261
+
1262
+ /**
1263
+ * Request template creation or rebuild (`POST /v3/templates`, 202 Accepted).
1264
+ *
1265
+ * @param {import('./client.d.ts').CreateTemplateRequest} request
1266
+ * @param {import('./client.d.ts').CreateTemplateOptions} [options]
1267
+ * @returns {Promise<import('./client.d.ts').TemplateRequestBuildResponse>}
1268
+ */
1269
+ async createTemplate(request, options = {}) {
1270
+ /** @type {Record<string, string>} */
1271
+ const headers = {};
1272
+ if (options.idempotencyKey) {
1273
+ headers['Idempotency-Key'] = options.idempotencyKey;
1274
+ }
1275
+
1276
+ const resp = await this._request('POST', '/v3/templates', {
1277
+ json: request,
1278
+ headers,
1279
+ signal: options.signal,
1280
+ });
1281
+ return (await readJsonOrUndefined(resp)) ?? {};
1282
+ }
1283
+
1284
+ /**
1285
+ * Start an image or recipe build for a template build ID (`POST /v2/templates/{templateID}/builds/{buildID}`, 202).
1286
+ *
1287
+ * @param {string} templateId
1288
+ * @param {string} buildId
1289
+ * @param {import('./client.d.ts').StartTemplateBuildRequest} request
1290
+ * @param {import('./client.d.ts').RequestOptions} [options]
1291
+ * @returns {Promise<void>}
1292
+ */
1293
+ async startTemplateBuild(templateId, buildId, request, options = {}) {
1294
+ await this._request(
1295
+ 'POST',
1296
+ `/v2/templates/${encodeURIComponent(templateId)}/builds/${encodeURIComponent(buildId)}`,
1297
+ {
1298
+ json: request,
1299
+ signal: options.signal,
1300
+ },
1301
+ );
1302
+ }
1303
+
1304
+ /**
1305
+ * Poll build status and incremental logs (`GET /templates/{templateID}/builds/{buildID}/status`).
1306
+ *
1307
+ * @param {string} templateId
1308
+ * @param {string} buildId
1309
+ * @param {import('./client.d.ts').GetTemplateBuildStatusOptions} [options]
1310
+ * @returns {Promise<import('./client.d.ts').TemplateBuildInfo>}
1311
+ */
1312
+ async getTemplateBuildStatus(templateId, buildId, options = {}) {
1313
+ const resp = await this._request(
1314
+ 'GET',
1315
+ `/templates/${encodeURIComponent(templateId)}/builds/${encodeURIComponent(buildId)}/status`,
1316
+ {
1317
+ query: {
1318
+ logsOffset: options.logsOffset,
1319
+ limit: options.limit,
1320
+ level: options.level,
1321
+ },
1322
+ signal: options.signal,
1323
+ },
1324
+ );
1325
+ return (await readJsonOrUndefined(resp)) ?? {};
1326
+ }
1327
+
1328
+ /**
1329
+ * Read build log entries (`GET /templates/{templateID}/builds/{buildID}/logs`).
1330
+ *
1331
+ * @param {string} templateId
1332
+ * @param {string} buildId
1333
+ * @param {import('./client.d.ts').GetTemplateBuildLogsOptions} [options]
1334
+ * @returns {Promise<{ logs: import('./client.d.ts').BuildLogEntry[] }>}
1335
+ */
1336
+ async getTemplateBuildLogs(templateId, buildId, options = {}) {
1337
+ const resp = await this._request(
1338
+ 'GET',
1339
+ `/templates/${encodeURIComponent(templateId)}/builds/${encodeURIComponent(buildId)}/logs`,
1340
+ {
1341
+ query: {
1342
+ cursor: options.cursor,
1343
+ limit: options.limit,
1344
+ direction: options.direction,
1345
+ level: options.level,
1346
+ },
1347
+ signal: options.signal,
1348
+ },
1349
+ );
1350
+ return (await readJsonOrUndefined(resp)) ?? { logs: [] };
1351
+ }
1352
+
1353
+ /**
1354
+ * Check build context cache presence and obtain an upload URL.
1355
+ *
1356
+ * @param {string} templateId
1357
+ * @param {string} hash
1358
+ * @param {import('./client.d.ts').RequestOptions} [options]
1359
+ * @returns {Promise<import('./client.d.ts').TemplateBuildFileUpload>}
1360
+ */
1361
+ async getTemplateFileUploadLink(templateId, hash, options = {}) {
1362
+ const resp = await this._request(
1363
+ 'GET',
1364
+ `/templates/${encodeURIComponent(templateId)}/files/${encodeURIComponent(hash)}`,
1365
+ { signal: options.signal },
1366
+ );
1367
+ return (await readJsonOrUndefined(resp)) ?? { present: false };
1368
+ }
1369
+
1370
+ /**
1371
+ * Upload a tar or gzip-compressed tar build context to the signed upload URL.
1372
+ *
1373
+ * @param {string} uploadUrl
1374
+ * @param {Uint8Array | ArrayBuffer} tarBytes
1375
+ * @param {{ headers?: Record<string, string>; signal?: AbortSignal }} [options]
1376
+ * @returns {Promise<void>}
1377
+ */
1378
+ async uploadTemplateFileContext(uploadUrl, tarBytes, options = {}) {
1379
+ const body = tarBytes instanceof ArrayBuffer ? new Uint8Array(tarBytes) : tarBytes;
1380
+ await this._request('PUT', uploadUrl, {
1381
+ body,
1382
+ headers: {
1383
+ 'Content-Type': 'application/gzip',
1384
+ ...(options.headers ?? {}),
1385
+ },
1386
+ includeAuth: false,
1387
+ signal: options.signal,
1388
+ });
1389
+ }
1390
+
1391
+ /**
1392
+ * Delete a template (`DELETE /templates/{templateID}`, 204 No Content).
1393
+ *
1394
+ * @param {string} templateId
1395
+ * @param {import('./client.d.ts').DeleteTemplateOptions} [options]
1396
+ * @returns {Promise<void>}
1397
+ */
1398
+ async deleteTemplate(templateId, options = {}) {
1399
+ await this._request('DELETE', `/templates/${encodeURIComponent(templateId)}`, {
1400
+ query: options.force !== undefined ? { force: options.force } : undefined,
1401
+ signal: options.signal,
1402
+ });
1403
+ }
1404
+
1405
+ /**
1406
+ * Update template public visibility (`PATCH /v2/templates/{templateID}`).
1407
+ *
1408
+ * @param {string} templateId
1409
+ * @param {boolean} isPublic
1410
+ * @param {import('./client.d.ts').RequestOptions} [options]
1411
+ * @returns {Promise<{ names: string[] }>}
1412
+ */
1413
+ async updateTemplateVisibility(templateId, isPublic, options = {}) {
1414
+ const resp = await this._request(
1415
+ 'PATCH',
1416
+ `/v2/templates/${encodeURIComponent(templateId)}`,
1417
+ {
1418
+ json: { public: isPublic },
1419
+ signal: options.signal,
1420
+ },
1421
+ );
1422
+ return (await readJsonOrUndefined(resp)) ?? { names: [] };
1423
+ }
1424
+
1425
+ /**
1426
+ * Assign tags to a template build (`POST /templates/tags`, 201).
1427
+ *
1428
+ * @param {string} target
1429
+ * @param {string[]} tags
1430
+ * @param {import('./client.d.ts').RequestOptions} [options]
1431
+ * @returns {Promise<void>}
1432
+ */
1433
+ async assignTemplateTags(target, tags, options = {}) {
1434
+ await this._request('POST', '/templates/tags', {
1435
+ json: { target, tags },
1436
+ signal: options.signal,
1437
+ });
1438
+ }
1439
+
1440
+ /**
1441
+ * Remove tags from a template (`DELETE /templates/tags`, 204).
1442
+ *
1443
+ * @param {string} name
1444
+ * @param {string[]} tags
1445
+ * @param {import('./client.d.ts').RequestOptions} [options]
1446
+ * @returns {Promise<void>}
1447
+ */
1448
+ async deleteTemplateTags(name, tags, options = {}) {
1449
+ await this._request('DELETE', '/templates/tags', {
1450
+ json: { name, tags },
1451
+ signal: options.signal,
1452
+ });
1453
+ }
1454
+
1455
+ /**
1456
+ * List assigned tags for a template (`GET /templates/{templateID}/tags`).
1457
+ *
1458
+ * @param {string} templateId
1459
+ * @param {import('./client.d.ts').RequestOptions} [options]
1460
+ * @returns {Promise<import('./client.d.ts').TemplateTagInfo[]>}
1461
+ */
1462
+ async getTemplateTags(templateId, options = {}) {
1463
+ const resp = await this._request(
1464
+ 'GET',
1465
+ `/templates/${encodeURIComponent(templateId)}/tags`,
1466
+ { signal: options.signal },
1467
+ );
1468
+ return (await readJsonOrUndefined(resp)) ?? [];
1469
+ }
1470
+
1471
+ /**
1472
+ * Create or scale a PodWarmPool (`POST /warmpools`, 201).
1473
+ *
1474
+ * @param {import('./client.d.ts').CreateWarmPoolRequest} request
1475
+ * @param {import('./client.d.ts').RequestOptions} [options]
1476
+ * @returns {Promise<import('./client.d.ts').WarmPoolInfo>}
1477
+ */
1478
+ async createWarmPool(request, options = {}) {
1479
+ const resp = await this._request('POST', '/warmpools', {
1480
+ json: {
1481
+ name: request.name,
1482
+ templateRef: request.templateRef ?? request.templateId,
1483
+ replicas: request.replicas,
1484
+ },
1485
+ signal: options.signal,
1486
+ });
1487
+ return (await readJsonOrUndefined(resp)) ?? {};
1488
+ }
1489
+
1490
+ /**
1491
+ * List active PodWarmPools (`GET /warmpools`).
1492
+ *
1493
+ * @param {import('./client.d.ts').RequestOptions} [options]
1494
+ * @returns {Promise<import('./client.d.ts').WarmPoolInfo[]>}
1495
+ */
1496
+ async listWarmPools(options = {}) {
1497
+ const resp = await this._request('GET', '/warmpools', { signal: options.signal });
1498
+ const data = await readJsonOrUndefined(resp);
1499
+ return Array.isArray(data) ? data : (data?.warmPools ?? data?.warmpools ?? []);
1500
+ }
1501
+ }