@kibotos/sdk 0.0.0-stage → 0.2.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/dist/index.cjs ADDED
@@ -0,0 +1,1508 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var KibotosError = class extends Error {
5
+ constructor(message, options) {
6
+ super(message, options);
7
+ this.name = new.target.name;
8
+ Object.setPrototypeOf(this, new.target.prototype);
9
+ }
10
+ };
11
+ var APIConnectionError = class extends KibotosError {
12
+ constructor(message = "Failed to connect to the Kibotos API", options) {
13
+ super(message, options);
14
+ }
15
+ };
16
+ var KibotosAPIError = class extends KibotosError {
17
+ status;
18
+ code;
19
+ requestId;
20
+ retryable;
21
+ details;
22
+ headers;
23
+ constructor(init) {
24
+ super(init.message, init.cause !== void 0 ? { cause: init.cause } : void 0);
25
+ this.status = init.status;
26
+ this.code = init.code;
27
+ this.requestId = init.requestId;
28
+ this.retryable = init.retryable;
29
+ this.details = init.details;
30
+ this.headers = init.headers;
31
+ }
32
+ };
33
+ var AuthenticationError = class extends KibotosAPIError {
34
+ };
35
+ var PermissionDeniedError = class extends KibotosAPIError {
36
+ };
37
+ var NotFoundError = class extends KibotosAPIError {
38
+ };
39
+ var WaitTimeoutError = class extends KibotosAPIError {
40
+ };
41
+ var ConflictError = class extends KibotosAPIError {
42
+ };
43
+ var UnexpectedStatusError = class extends ConflictError {
44
+ };
45
+ var RateLimitError = class extends KibotosAPIError {
46
+ /** Parsed `Retry-After` delay in milliseconds, if provided by the server. */
47
+ retryAfterMs;
48
+ constructor(init) {
49
+ super(init);
50
+ this.retryAfterMs = init.retryAfterMs;
51
+ }
52
+ };
53
+ var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
54
+ function parseRetryAfterMs(headerValue, nowMs = Date.now()) {
55
+ if (!headerValue) {
56
+ return void 0;
57
+ }
58
+ const trimmed = headerValue.trim();
59
+ if (trimmed.length === 0) {
60
+ return void 0;
61
+ }
62
+ const seconds = Number(trimmed);
63
+ if (Number.isFinite(seconds) && seconds >= 0) {
64
+ return Math.round(seconds * 1e3);
65
+ }
66
+ const dateMs = Date.parse(trimmed);
67
+ if (!Number.isNaN(dateMs)) {
68
+ return Math.max(0, dateMs - nowMs);
69
+ }
70
+ return void 0;
71
+ }
72
+ function isErrorEnvelope(value) {
73
+ if (typeof value !== "object" || value === null) {
74
+ return false;
75
+ }
76
+ const err = value.error;
77
+ return typeof err === "object" && err !== null;
78
+ }
79
+ function createAPIError(status, headers, body, fallbackMessage) {
80
+ const headerRequestId = headers.get("Request-Id") ?? void 0;
81
+ let code = "http_error";
82
+ let message = fallbackMessage || `Kibotos API request failed with status ${status}`;
83
+ let requestId = headerRequestId;
84
+ let retryable = DEFAULT_RETRYABLE_STATUSES.has(status);
85
+ let details;
86
+ if (isErrorEnvelope(body)) {
87
+ const err = body.error;
88
+ if (typeof err.code === "string" && err.code.length > 0) {
89
+ code = err.code;
90
+ }
91
+ if (typeof err.message === "string" && err.message.length > 0) {
92
+ message = err.message;
93
+ }
94
+ if (typeof err.request_id === "string" && err.request_id.length > 0) {
95
+ requestId = err.request_id;
96
+ }
97
+ if (typeof err.retryable === "boolean") {
98
+ retryable = err.retryable;
99
+ }
100
+ if (typeof err.details === "object" && err.details !== null && !Array.isArray(err.details)) {
101
+ details = err.details;
102
+ }
103
+ }
104
+ const init = {
105
+ status,
106
+ code,
107
+ message,
108
+ requestId,
109
+ retryable,
110
+ details,
111
+ headers
112
+ };
113
+ if (status === 401) {
114
+ return new AuthenticationError(init);
115
+ }
116
+ if (status === 403) {
117
+ return new PermissionDeniedError(init);
118
+ }
119
+ if (status === 404) {
120
+ return new NotFoundError(init);
121
+ }
122
+ if (status === 408) {
123
+ return new WaitTimeoutError(init);
124
+ }
125
+ if (status === 409) {
126
+ if (code === "unexpected_status") {
127
+ return new UnexpectedStatusError(init);
128
+ }
129
+ return new ConflictError(init);
130
+ }
131
+ if (status === 429) {
132
+ const retryAfterMs = parseRetryAfterMs(headers.get("Retry-After"));
133
+ return new RateLimitError({ ...init, retryAfterMs });
134
+ }
135
+ return new KibotosAPIError(init);
136
+ }
137
+
138
+ // src/http.ts
139
+ var DEFAULT_BASE_URL = "https://api.kibo.to/v1";
140
+ var DEFAULT_MAX_RETRIES = 3;
141
+ var DEFAULT_TIMEOUT_MS = 3e4;
142
+ var SDK_VERSION = "0.2.0";
143
+ var INITIAL_RETRY_DELAY_MS = 500;
144
+ var MAX_RETRY_DELAY_MS = 8e3;
145
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
146
+ function readEnv(name) {
147
+ try {
148
+ const proc = globalThis.process;
149
+ if (proc && typeof proc === "object" && proc.env && typeof proc.env === "object") {
150
+ const val = proc.env[name];
151
+ return typeof val === "string" && val.length > 0 ? val : void 0;
152
+ }
153
+ } catch {
154
+ }
155
+ return void 0;
156
+ }
157
+ function normalizeBaseUrl(rawUrl) {
158
+ const trimmed = rawUrl.trim().replace(/\/+$/, "");
159
+ if (trimmed.length === 0) {
160
+ return DEFAULT_BASE_URL;
161
+ }
162
+ if (trimmed.endsWith("/v1")) {
163
+ return trimmed;
164
+ }
165
+ return `${trimmed}/v1`;
166
+ }
167
+ function generateUuid() {
168
+ if (typeof globalThis.crypto?.randomUUID === "function") {
169
+ return globalThis.crypto.randomUUID();
170
+ }
171
+ const bytes = new Uint8Array(16);
172
+ globalThis.crypto.getRandomValues(bytes);
173
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
174
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
175
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
176
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
177
+ }
178
+ function createAbortError(signal) {
179
+ if (signal.reason !== void 0) {
180
+ return signal.reason;
181
+ }
182
+ if (typeof DOMException !== "undefined") {
183
+ return new DOMException("The operation was aborted.", "AbortError");
184
+ }
185
+ const err = new Error("The operation was aborted.");
186
+ err.name = "AbortError";
187
+ return err;
188
+ }
189
+ function combineSignals(userSignal, timeoutMs) {
190
+ const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
191
+ if (!userSignal && !hasTimeout) {
192
+ return { signal: void 0, isTimeout: () => false, cleanup: () => {
193
+ } };
194
+ }
195
+ let timedOut = false;
196
+ if (!userSignal && hasTimeout) {
197
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
198
+ timeoutSignal.addEventListener(
199
+ "abort",
200
+ () => {
201
+ timedOut = true;
202
+ },
203
+ { once: true }
204
+ );
205
+ return {
206
+ signal: timeoutSignal,
207
+ isTimeout: () => timedOut || timeoutSignal.aborted,
208
+ cleanup: () => {
209
+ }
210
+ };
211
+ }
212
+ if (userSignal && !hasTimeout) {
213
+ return {
214
+ signal: userSignal,
215
+ isTimeout: () => false,
216
+ cleanup: () => {
217
+ }
218
+ };
219
+ }
220
+ const controller = new AbortController();
221
+ const onUserAbort = () => {
222
+ controller.abort(createAbortError(userSignal));
223
+ };
224
+ if (userSignal.aborted) {
225
+ controller.abort(createAbortError(userSignal));
226
+ return {
227
+ signal: controller.signal,
228
+ isTimeout: () => false,
229
+ cleanup: () => {
230
+ }
231
+ };
232
+ }
233
+ userSignal.addEventListener("abort", onUserAbort, { once: true });
234
+ const timer = setTimeout(() => {
235
+ timedOut = true;
236
+ controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));
237
+ }, timeoutMs);
238
+ return {
239
+ signal: controller.signal,
240
+ isTimeout: () => timedOut,
241
+ cleanup: () => {
242
+ clearTimeout(timer);
243
+ userSignal.removeEventListener("abort", onUserAbort);
244
+ }
245
+ };
246
+ }
247
+ function combineResponseSignals(userSignal, timeoutMs) {
248
+ const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
249
+ if (userSignal && hasTimeout && typeof AbortSignal.any !== "function") {
250
+ const combined = combineSignals(userSignal, timeoutMs);
251
+ combined.signal?.addEventListener("abort", combined.cleanup, { once: true });
252
+ return combined;
253
+ }
254
+ const timeoutSignal = hasTimeout ? AbortSignal.timeout(timeoutMs) : void 0;
255
+ return {
256
+ signal: userSignal && timeoutSignal ? AbortSignal.any([userSignal, timeoutSignal]) : userSignal ?? timeoutSignal,
257
+ isTimeout: () => timeoutSignal?.aborted === true,
258
+ cleanup: () => {
259
+ }
260
+ };
261
+ }
262
+ function sleep(ms, signal) {
263
+ if (signal?.aborted) {
264
+ return Promise.reject(createAbortError(signal));
265
+ }
266
+ if (ms <= 0) {
267
+ return Promise.resolve();
268
+ }
269
+ return new Promise((resolve, reject) => {
270
+ const onAbort = () => {
271
+ clearTimeout(timer);
272
+ reject(createAbortError(signal));
273
+ };
274
+ const timer = setTimeout(() => {
275
+ signal?.removeEventListener("abort", onAbort);
276
+ resolve();
277
+ }, ms);
278
+ signal?.addEventListener("abort", onAbort, { once: true });
279
+ });
280
+ }
281
+ function calculateBackoffMs(attempt, retryAfterMs) {
282
+ if (retryAfterMs !== void 0 && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
283
+ return retryAfterMs;
284
+ }
285
+ const exponential = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);
286
+ const jitter = 0.5 + Math.random() * 0.5;
287
+ return Math.round(exponential * jitter);
288
+ }
289
+ var HttpClient = class {
290
+ baseUrl;
291
+ maxRetries;
292
+ timeoutMs;
293
+ apiKey;
294
+ fetchImpl;
295
+ defaultHeaders;
296
+ constructor(options = {}) {
297
+ this.apiKey = options.apiKey ?? readEnv("KIBOTOS_API_KEY");
298
+ this.baseUrl = normalizeBaseUrl(options.baseUrl ?? readEnv("KIBOTOS_API_URL") ?? DEFAULT_BASE_URL);
299
+ this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
300
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
301
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
302
+ this.defaultHeaders = { ...options.defaultHeaders ?? {} };
303
+ if (typeof this.fetchImpl !== "function") {
304
+ throw new APIConnectionError(
305
+ "No fetch implementation found. Provide a custom `fetch` option or use a runtime with global `fetch` (Node 20+, Bun, Deno, Cloudflare Workers)."
306
+ );
307
+ }
308
+ }
309
+ buildUrl(path, query) {
310
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
311
+ const url = new URL(`${this.baseUrl}${normalizedPath}`);
312
+ if (query) {
313
+ query.forEach((value, key) => {
314
+ url.searchParams.append(key, value);
315
+ });
316
+ }
317
+ return url.toString();
318
+ }
319
+ buildHeaders(overrides) {
320
+ const headers = new Headers();
321
+ if (this.apiKey) {
322
+ headers.set("Authorization", `Bearer ${this.apiKey}`);
323
+ }
324
+ for (const [k, v] of Object.entries(this.defaultHeaders)) {
325
+ headers.set(k, v);
326
+ }
327
+ for (const [k, v] of Object.entries(overrides ?? {})) {
328
+ headers.set(k, v);
329
+ }
330
+ return headers;
331
+ }
332
+ async request(config) {
333
+ return await this.perform(config, false);
334
+ }
335
+ requestResponse(config) {
336
+ return this.perform(config, true);
337
+ }
338
+ async perform(config, rawResponse) {
339
+ const { method, path, query, body, rawBody, opts, disableWaitTimeoutRetry } = config;
340
+ const url = this.buildUrl(path, query);
341
+ const effectiveTimeoutMs = opts?.timeoutMs ?? this.timeoutMs;
342
+ const userSignal = opts?.signal;
343
+ const maxRetries = config.nonReplayable ? 0 : this.maxRetries;
344
+ const headers = this.buildHeaders(opts?.headers);
345
+ headers.set("Accept", config.accept ?? headers.get("Accept") ?? "application/json");
346
+ if (!headers.has("User-Agent")) {
347
+ headers.set("User-Agent", `@kibotos/sdk/${SDK_VERSION}`);
348
+ }
349
+ const requestBody = rawBody ?? (body === void 0 ? void 0 : JSON.stringify(body));
350
+ if (requestBody !== void 0 && !headers.has("Content-Type")) {
351
+ headers.set("Content-Type", rawBody === void 0 ? "application/json" : "application/octet-stream");
352
+ }
353
+ if (config.disableIdempotency) {
354
+ headers.delete("Idempotency-Key");
355
+ } else if (opts?.idempotencyKey) {
356
+ headers.set("Idempotency-Key", opts.idempotencyKey);
357
+ } else if (method === "POST" && !headers.has("Idempotency-Key")) {
358
+ headers.set("Idempotency-Key", generateUuid());
359
+ }
360
+ let attempt = 0;
361
+ while (true) {
362
+ if (userSignal?.aborted) {
363
+ throw createAbortError(userSignal);
364
+ }
365
+ const { signal, isTimeout, cleanup } = rawResponse ? combineResponseSignals(userSignal, effectiveTimeoutMs) : combineSignals(userSignal, effectiveTimeoutMs);
366
+ let response;
367
+ try {
368
+ const init = {
369
+ method,
370
+ headers,
371
+ body: requestBody,
372
+ signal
373
+ };
374
+ if (config.duplex) init.duplex = config.duplex;
375
+ response = await this.fetchImpl(url, init);
376
+ } catch (err) {
377
+ cleanup();
378
+ if (userSignal?.aborted) {
379
+ throw createAbortError(userSignal);
380
+ }
381
+ const connectionError = isTimeout() ? new APIConnectionError(`Request timed out after ${effectiveTimeoutMs}ms`, { cause: err }) : new APIConnectionError(
382
+ err instanceof Error && err.message ? `Network error: ${err.message}` : "Network error while contacting the Kibotos API",
383
+ { cause: err }
384
+ );
385
+ if (attempt < maxRetries) {
386
+ const delayMs = calculateBackoffMs(attempt);
387
+ attempt += 1;
388
+ await sleep(delayMs, userSignal);
389
+ continue;
390
+ }
391
+ throw connectionError;
392
+ }
393
+ if (rawResponse && (response.ok || config.successStatuses?.includes(response.status))) {
394
+ return response;
395
+ }
396
+ let parsedBody;
397
+ try {
398
+ const text = await response.text();
399
+ if (text.length > 0) {
400
+ try {
401
+ parsedBody = JSON.parse(text);
402
+ } catch {
403
+ parsedBody = text;
404
+ }
405
+ }
406
+ } catch (err) {
407
+ cleanup();
408
+ if (userSignal?.aborted) {
409
+ throw createAbortError(userSignal);
410
+ }
411
+ const readError = isTimeout() ? new APIConnectionError(`Request timed out after ${effectiveTimeoutMs}ms`, { cause: err }) : new APIConnectionError("Failed to read response body from the Kibotos API", { cause: err });
412
+ if (attempt < maxRetries) {
413
+ const delayMs = calculateBackoffMs(attempt);
414
+ attempt += 1;
415
+ await sleep(delayMs, userSignal);
416
+ continue;
417
+ }
418
+ throw readError;
419
+ } finally {
420
+ cleanup();
421
+ }
422
+ if (response.ok) {
423
+ return parsedBody;
424
+ }
425
+ const apiError = createAPIError(
426
+ response.status,
427
+ response.headers,
428
+ parsedBody,
429
+ response.statusText || void 0
430
+ );
431
+ if (this.shouldRetryAPIError(apiError, disableWaitTimeoutRetry) && attempt < maxRetries) {
432
+ const retryAfterMs = apiError instanceof RateLimitError ? apiError.retryAfterMs : parseRetryAfterMs(response.headers.get("Retry-After"));
433
+ const delayMs = calculateBackoffMs(attempt, retryAfterMs);
434
+ attempt += 1;
435
+ await sleep(delayMs, userSignal);
436
+ continue;
437
+ }
438
+ throw apiError;
439
+ }
440
+ }
441
+ shouldRetryAPIError(error, disableWaitTimeoutRetry) {
442
+ if (disableWaitTimeoutRetry && error.status === 408 && error.code === "wait_timeout") {
443
+ return false;
444
+ }
445
+ return error.retryable || RETRYABLE_HTTP_STATUSES.has(error.status);
446
+ }
447
+ };
448
+
449
+ // src/pagination.ts
450
+ async function* paginate(fetchPage, initialPageToken) {
451
+ let pageToken = initialPageToken;
452
+ const seenTokens = /* @__PURE__ */ new Set();
453
+ while (true) {
454
+ const page = await fetchPage(pageToken);
455
+ for (const item of page.data) {
456
+ yield item;
457
+ }
458
+ const next = page.next_page_token;
459
+ if (!next || seenTokens.has(next)) {
460
+ break;
461
+ }
462
+ seenTokens.add(next);
463
+ pageToken = next;
464
+ }
465
+ }
466
+ function buildQueryParams(params) {
467
+ const searchParams = new URLSearchParams();
468
+ if (!params) {
469
+ return searchParams;
470
+ }
471
+ for (const [key, value] of Object.entries(params)) {
472
+ if (value === void 0) {
473
+ continue;
474
+ }
475
+ if (key === "labels" && typeof value === "object" && !Array.isArray(value)) {
476
+ for (const [labelKey, labelValue] of Object.entries(value)) {
477
+ searchParams.set(`label.${labelKey}`, labelValue);
478
+ }
479
+ } else if (Array.isArray(value)) {
480
+ for (const item of value) {
481
+ searchParams.append(key, String(item));
482
+ }
483
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
484
+ searchParams.set(key, String(value));
485
+ }
486
+ }
487
+ return searchParams;
488
+ }
489
+
490
+ // src/resources/exposures.ts
491
+ var ExposuresResource = class {
492
+ constructor(http) {
493
+ this.http = http;
494
+ }
495
+ http;
496
+ /**
497
+ * Creates a public HTTPS exposure for a workspace port (`201 Created`).
498
+ * `POST /v1/workspaces/{id}/exposures`
499
+ */
500
+ create(workspaceId, body, opts) {
501
+ return this.http.request({
502
+ method: "POST",
503
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures`,
504
+ body,
505
+ opts
506
+ });
507
+ }
508
+ /**
509
+ * Lists exposures for a workspace.
510
+ * `GET /v1/workspaces/{id}/exposures`
511
+ */
512
+ list(workspaceId, params, opts) {
513
+ return this.http.request({
514
+ method: "GET",
515
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures`,
516
+ query: buildQueryParams({
517
+ include_revoked: params?.include_revoked,
518
+ limit: params?.limit,
519
+ page_token: params?.page_token
520
+ }),
521
+ opts
522
+ });
523
+ }
524
+ /**
525
+ * Auto-paginates across all exposures for a workspace.
526
+ */
527
+ iterate(workspaceId, params, opts) {
528
+ return paginate(
529
+ (pageToken) => this.list(
530
+ workspaceId,
531
+ {
532
+ ...params,
533
+ page_token: pageToken
534
+ },
535
+ opts
536
+ ),
537
+ params?.page_token
538
+ );
539
+ }
540
+ /**
541
+ * Retrieves a specific exposure by ID.
542
+ * `GET /v1/workspaces/{id}/exposures/{exposure_id}`
543
+ */
544
+ get(workspaceId, exposureId, opts) {
545
+ return this.http.request({
546
+ method: "GET",
547
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures/${encodeURIComponent(exposureId)}`,
548
+ opts
549
+ });
550
+ }
551
+ /**
552
+ * Revokes an active exposure.
553
+ * `DELETE /v1/workspaces/{id}/exposures/{exposure_id}`
554
+ */
555
+ revoke(workspaceId, exposureId, opts) {
556
+ return this.http.request({
557
+ method: "DELETE",
558
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures/${encodeURIComponent(exposureId)}`,
559
+ opts
560
+ });
561
+ }
562
+ };
563
+
564
+ // src/resources/templates.ts
565
+ var TemplatesResource = class {
566
+ constructor(http) {
567
+ this.http = http;
568
+ }
569
+ http;
570
+ /**
571
+ * Lists templates across zones.
572
+ * `GET /v1/templates`
573
+ */
574
+ list(params, opts) {
575
+ return this.http.request({
576
+ method: "GET",
577
+ path: "/templates",
578
+ query: buildQueryParams({
579
+ owner: params?.owner,
580
+ zone: params?.zone,
581
+ limit: params?.limit,
582
+ page_token: params?.page_token
583
+ }),
584
+ opts
585
+ });
586
+ }
587
+ /**
588
+ * Auto-paginates across all templates matching `params`.
589
+ */
590
+ iterate(params, opts) {
591
+ return paginate(
592
+ (pageToken) => this.list(
593
+ {
594
+ ...params,
595
+ page_token: pageToken
596
+ },
597
+ opts
598
+ ),
599
+ params?.page_token
600
+ );
601
+ }
602
+ /**
603
+ * Retrieves a template by ID.
604
+ * `GET /v1/templates/{id}`
605
+ */
606
+ get(id, opts) {
607
+ return this.http.request({
608
+ method: "GET",
609
+ path: `/templates/${encodeURIComponent(id)}`,
610
+ opts
611
+ });
612
+ }
613
+ /**
614
+ * Lists revisions for a template.
615
+ * `GET /v1/templates/{id}/revisions`
616
+ */
617
+ listRevisions(id, params, opts) {
618
+ return this.http.request({
619
+ method: "GET",
620
+ path: `/templates/${encodeURIComponent(id)}/revisions`,
621
+ query: buildQueryParams({
622
+ limit: params?.limit,
623
+ page_token: params?.page_token
624
+ }),
625
+ opts
626
+ });
627
+ }
628
+ /**
629
+ * Retrieves a specific template revision.
630
+ * `GET /v1/templates/{id}/revisions/{revision_id}`
631
+ */
632
+ getRevision(id, revisionId, opts) {
633
+ return this.http.request({
634
+ method: "GET",
635
+ path: `/templates/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}`,
636
+ opts
637
+ });
638
+ }
639
+ };
640
+
641
+ // src/wait.ts
642
+ var DEFAULT_WAIT_TIMEOUT_SECONDS = 30;
643
+ var MAX_CHUNK_TIMEOUT_SECONDS = 60;
644
+ var HTTP_TIMEOUT_BUFFER_SECONDS = 15;
645
+ async function executeWaitLoop(http, params) {
646
+ const statuses = Array.isArray(params.status) ? params.status : [params.status];
647
+ if (statuses.length === 0) {
648
+ throw new KibotosError("wait() requires at least one target status");
649
+ }
650
+ const totalTimeoutSeconds = params.timeoutSeconds ?? DEFAULT_WAIT_TIMEOUT_SECONDS;
651
+ if (!Number.isFinite(totalTimeoutSeconds) || totalTimeoutSeconds <= 0) {
652
+ throw new KibotosError("wait() timeoutSeconds must be a positive number");
653
+ }
654
+ const deadlineMs = Date.now() + totalTimeoutSeconds * 1e3;
655
+ let remainingBudgetSeconds = totalTimeoutSeconds;
656
+ while (true) {
657
+ if (params.opts?.signal?.aborted) {
658
+ throw params.opts.signal.reason ?? new Error("The operation was aborted.");
659
+ }
660
+ const chunkSeconds = Math.min(
661
+ MAX_CHUNK_TIMEOUT_SECONDS,
662
+ Math.max(1, Math.ceil(remainingBudgetSeconds))
663
+ );
664
+ const query = new URLSearchParams();
665
+ for (const status of statuses) {
666
+ query.append("status", status);
667
+ }
668
+ query.set("timeout", String(chunkSeconds));
669
+ const effectiveOpts = {
670
+ ...params.opts,
671
+ timeoutMs: params.opts?.timeoutMs ?? Math.max(http.timeoutMs, (chunkSeconds + HTTP_TIMEOUT_BUFFER_SECONDS) * 1e3)
672
+ };
673
+ try {
674
+ return await http.request({
675
+ method: "GET",
676
+ path: params.path,
677
+ query,
678
+ opts: effectiveOpts,
679
+ disableWaitTimeoutRetry: true
680
+ });
681
+ } catch (err) {
682
+ if (!(err instanceof WaitTimeoutError)) {
683
+ throw err;
684
+ }
685
+ const wallRemainingSeconds = (deadlineMs - Date.now()) / 1e3;
686
+ remainingBudgetSeconds = Math.min(remainingBudgetSeconds - chunkSeconds, wallRemainingSeconds);
687
+ if (remainingBudgetSeconds <= 0) {
688
+ throw err;
689
+ }
690
+ }
691
+ }
692
+ }
693
+
694
+ // src/resources/volumes.ts
695
+ var VolumesResource = class {
696
+ constructor(http) {
697
+ this.http = http;
698
+ }
699
+ http;
700
+ /**
701
+ * Creates a new persistent volume asynchronously (`202 Accepted`).
702
+ * `POST /v1/volumes`
703
+ */
704
+ create(body, opts) {
705
+ return this.http.request({
706
+ method: "POST",
707
+ path: "/volumes",
708
+ body,
709
+ opts
710
+ });
711
+ }
712
+ /**
713
+ * Lists volumes across zones.
714
+ * `GET /v1/volumes`
715
+ */
716
+ list(params, opts) {
717
+ return this.http.request({
718
+ method: "GET",
719
+ path: "/volumes",
720
+ query: buildQueryParams({
721
+ zone: params?.zone,
722
+ attached: params?.attached,
723
+ labels: params?.labels,
724
+ limit: params?.limit,
725
+ page_token: params?.page_token
726
+ }),
727
+ opts
728
+ });
729
+ }
730
+ /**
731
+ * Auto-paginates across all volumes matching `params`.
732
+ */
733
+ iterate(params, opts) {
734
+ return paginate(
735
+ (pageToken) => this.list(
736
+ {
737
+ ...params,
738
+ page_token: pageToken
739
+ },
740
+ opts
741
+ ),
742
+ params?.page_token
743
+ );
744
+ }
745
+ /**
746
+ * Retrieves a volume by ID.
747
+ * `GET /v1/volumes/{id}`
748
+ */
749
+ get(id, opts) {
750
+ return this.http.request({
751
+ method: "GET",
752
+ path: `/volumes/${encodeURIComponent(id)}`,
753
+ opts
754
+ });
755
+ }
756
+ /**
757
+ * Updates volume metadata (`name` and/or `labels`).
758
+ * `PATCH /v1/volumes/{id}`
759
+ */
760
+ update(id, body, opts) {
761
+ return this.http.request({
762
+ method: "PATCH",
763
+ path: `/volumes/${encodeURIComponent(id)}`,
764
+ body,
765
+ opts
766
+ });
767
+ }
768
+ /**
769
+ * Resizes a volume asynchronously (`202 Accepted`).
770
+ * `POST /v1/volumes/{id}/resize`
771
+ */
772
+ resize(id, body, opts) {
773
+ return this.http.request({
774
+ method: "POST",
775
+ path: `/volumes/${encodeURIComponent(id)}/resize`,
776
+ body,
777
+ opts
778
+ });
779
+ }
780
+ /**
781
+ * Deletes a volume asynchronously (`202 Accepted`).
782
+ * `DELETE /v1/volumes/{id}`
783
+ */
784
+ delete(id, opts) {
785
+ return this.http.request({
786
+ method: "DELETE",
787
+ path: `/volumes/${encodeURIComponent(id)}`,
788
+ opts
789
+ });
790
+ }
791
+ /**
792
+ * Waits until the volume reaches one of the target statuses.
793
+ * Automatically chunks calls into `<= 60s` windows when `timeoutSeconds > 60`.
794
+ * `GET /v1/volumes/{id}/wait`
795
+ */
796
+ wait(id, params, opts) {
797
+ return executeWaitLoop(this.http, {
798
+ path: `/volumes/${encodeURIComponent(id)}/wait`,
799
+ status: params.status,
800
+ timeoutSeconds: params.timeoutSeconds,
801
+ opts
802
+ });
803
+ }
804
+ };
805
+
806
+ // src/sse.ts
807
+ var EXEC_EVENTS = /* @__PURE__ */ new Set([
808
+ "started",
809
+ "stdout",
810
+ "stderr",
811
+ "heartbeat",
812
+ "exited",
813
+ "error"
814
+ ]);
815
+ async function* parseExecEvents(response) {
816
+ if (!response.body) throw new Error("Kibotos exec stream has no response body");
817
+ const reader = response.body.getReader();
818
+ const decoder = new TextDecoder();
819
+ let pending = "";
820
+ let event = "";
821
+ let data = [];
822
+ let skipLF = false;
823
+ try {
824
+ while (true) {
825
+ const { value, done } = await reader.read();
826
+ const chunk = decoder.decode(value, { stream: !done });
827
+ if (chunk.length > 0) {
828
+ pending += skipLF && chunk.startsWith("\n") ? chunk.slice(1) : chunk;
829
+ skipLF = false;
830
+ }
831
+ let offset = 0;
832
+ const lineEnd = /\r\n|[\r\n]/g;
833
+ for (let match = lineEnd.exec(pending); match; match = lineEnd.exec(pending)) {
834
+ const line = pending.slice(offset, match.index);
835
+ offset = lineEnd.lastIndex;
836
+ skipLF = match[0] === "\r" && offset === pending.length;
837
+ if (line === "") {
838
+ const name = event;
839
+ const payload = data.join("\n");
840
+ const hasData = data.length > 0;
841
+ event = "";
842
+ data = [];
843
+ if (hasData && EXEC_EVENTS.has(name)) {
844
+ let decoded = payload;
845
+ try {
846
+ decoded = JSON.parse(payload);
847
+ } catch {
848
+ }
849
+ yield { event: name, data: decoded };
850
+ }
851
+ continue;
852
+ }
853
+ const colon = line.indexOf(":");
854
+ const field = colon === -1 ? line : line.slice(0, colon);
855
+ let fieldValue = colon === -1 ? "" : line.slice(colon + 1);
856
+ if (fieldValue.startsWith(" ")) fieldValue = fieldValue.slice(1);
857
+ if (field === "event") event = fieldValue;
858
+ if (field === "data") data.push(fieldValue);
859
+ }
860
+ pending = pending.slice(offset);
861
+ if (done) break;
862
+ }
863
+ } finally {
864
+ try {
865
+ await reader.cancel();
866
+ } catch {
867
+ } finally {
868
+ reader.releaseLock();
869
+ }
870
+ }
871
+ }
872
+
873
+ // src/websocket.ts
874
+ var FRAME_VERSION = 1;
875
+ var HEADER_BYTES = 6;
876
+ var WorkspaceChannel = {
877
+ stdin: 0,
878
+ stdout: 1,
879
+ stderr: 2,
880
+ pty: 3,
881
+ tunnel: 4
882
+ };
883
+ function encodeBinaryFrame(streamId, channel, payload) {
884
+ validateStreamId(streamId);
885
+ validateChannel(channel);
886
+ const frame = new Uint8Array(HEADER_BYTES + payload.byteLength);
887
+ const header = new DataView(frame.buffer);
888
+ header.setUint8(0, FRAME_VERSION);
889
+ header.setUint32(1, streamId, false);
890
+ header.setUint8(5, channel);
891
+ frame.set(payload, HEADER_BYTES);
892
+ return frame;
893
+ }
894
+ function decodeBinaryFrame(input) {
895
+ const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
896
+ if (bytes.byteLength < HEADER_BYTES) throw new RangeError("Workspace frame is shorter than 6 bytes");
897
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
898
+ if (header.getUint8(0) !== FRAME_VERSION) throw new RangeError("Unsupported workspace frame version");
899
+ const streamId = header.getUint32(1, false);
900
+ validateStreamId(streamId);
901
+ const channel = header.getUint8(5);
902
+ validateChannel(channel);
903
+ return {
904
+ stream_id: streamId,
905
+ channel,
906
+ payload: bytes.subarray(HEADER_BYTES)
907
+ };
908
+ }
909
+ function validateStreamId(streamId) {
910
+ if (!Number.isInteger(streamId) || streamId < 1 || streamId > 4294967295) {
911
+ throw new RangeError("stream_id must be a nonzero unsigned 32-bit integer");
912
+ }
913
+ }
914
+ function validateChannel(channel) {
915
+ if (!Number.isInteger(channel) || channel < 0 || channel > 4) {
916
+ throw new RangeError("Invalid workspace frame channel");
917
+ }
918
+ }
919
+ function decodeWorkspaceFrame(data) {
920
+ if (typeof data !== "string") return { type: "binary", frame: decodeBinaryFrame(data) };
921
+ const frame = JSON.parse(data);
922
+ if (!frame || typeof frame !== "object" || !("type" in frame) || typeof frame.type !== "string") {
923
+ throw new TypeError("Invalid workspace control frame");
924
+ }
925
+ return { type: "control", frame };
926
+ }
927
+ function webSocketUrl(url) {
928
+ const target = new URL(url);
929
+ if (target.protocol === "https:") target.protocol = "wss:";
930
+ if (target.protocol === "http:") target.protocol = "ws:";
931
+ if (target.protocol !== "ws:" && target.protocol !== "wss:") {
932
+ throw new TypeError("A WebSocket URL requires HTTP or HTTPS");
933
+ }
934
+ return target.toString();
935
+ }
936
+ function openWebSocket(url, headers, options) {
937
+ const handshake = { protocols: options?.protocols, headers: Object.fromEntries(headers) };
938
+ if (options?.factory) return options.factory(url, handshake);
939
+ const NativeWebSocket = globalThis.WebSocket;
940
+ if (typeof NativeWebSocket !== "function") {
941
+ throw new APIConnectionError("Global WebSocket is unavailable. Supply a WebSocket factory.");
942
+ }
943
+ if (Object.keys(handshake.headers).length === 0) {
944
+ return new NativeWebSocket(url, options?.protocols);
945
+ }
946
+ if (globalThis.process?.versions?.node) {
947
+ const NodeWebSocket = NativeWebSocket;
948
+ return new NodeWebSocket(url, handshake);
949
+ }
950
+ throw new APIConnectionError("This runtime requires a WebSocket factory to set handshake headers.");
951
+ }
952
+ var WorkspaceSocket = class {
953
+ constructor(socket) {
954
+ this.socket = socket;
955
+ socket.binaryType = "arraybuffer";
956
+ }
957
+ socket;
958
+ /** Subscribe to decoded frames. Returns an unsubscribe function. */
959
+ onFrame(listener) {
960
+ const onMessage = (event) => {
961
+ listener(decodeWorkspaceFrame(event.data));
962
+ };
963
+ this.socket.addEventListener("message", onMessage);
964
+ return () => this.socket.removeEventListener("message", onMessage);
965
+ }
966
+ sendControl(frame) {
967
+ this.socket.send(JSON.stringify(frame));
968
+ }
969
+ open(streamId, kind, params = {}) {
970
+ validateStreamId(streamId);
971
+ this.sendControl({ type: "open", stream_id: streamId, kind, params });
972
+ }
973
+ sendBinary(streamId, channel, payload) {
974
+ this.socket.send(encodeBinaryFrame(streamId, channel, payload));
975
+ }
976
+ close(code, reason) {
977
+ this.socket.close(code, reason);
978
+ }
979
+ };
980
+
981
+ // src/resources/workspaces.ts
982
+ function workspacePath(id) {
983
+ return `/workspaces/${encodeURIComponent(id)}`;
984
+ }
985
+ var WorkspacesResource = class {
986
+ constructor(http) {
987
+ this.http = http;
988
+ }
989
+ http;
990
+ /**
991
+ * Creates a new workspace asynchronously (`202 Accepted`).
992
+ * `POST /v1/workspaces`
993
+ */
994
+ create(body, opts) {
995
+ const { noTimeout, ...rest } = body;
996
+ if (noTimeout && rest.timeout !== void 0) {
997
+ return Promise.reject(new TypeError("Cannot combine noTimeout with timeout"));
998
+ }
999
+ const payload = noTimeout ? { ...rest, timeout: { seconds: 0 } } : rest;
1000
+ return this.http.request({
1001
+ method: "POST",
1002
+ path: "/workspaces",
1003
+ body: payload,
1004
+ opts
1005
+ });
1006
+ }
1007
+ /**
1008
+ * Lists workspaces across zones.
1009
+ * `GET /v1/workspaces`
1010
+ */
1011
+ list(params, opts) {
1012
+ return this.http.request({
1013
+ method: "GET",
1014
+ path: "/workspaces",
1015
+ query: buildQueryParams({
1016
+ status: params?.status,
1017
+ zone: params?.zone,
1018
+ labels: params?.labels,
1019
+ limit: params?.limit,
1020
+ page_token: params?.page_token
1021
+ }),
1022
+ opts
1023
+ });
1024
+ }
1025
+ /**
1026
+ * Auto-paginates across all workspaces matching `params`.
1027
+ */
1028
+ iterate(params, opts) {
1029
+ return paginate(
1030
+ (pageToken) => this.list(
1031
+ {
1032
+ ...params,
1033
+ page_token: pageToken
1034
+ },
1035
+ opts
1036
+ ),
1037
+ params?.page_token
1038
+ );
1039
+ }
1040
+ /**
1041
+ * Retrieves a workspace by ID.
1042
+ * `GET /v1/workspaces/{id}`
1043
+ */
1044
+ get(id, opts) {
1045
+ return this.http.request({
1046
+ method: "GET",
1047
+ path: `/workspaces/${encodeURIComponent(id)}`,
1048
+ opts
1049
+ });
1050
+ }
1051
+ /**
1052
+ * Updates workspace metadata and resizes eligible stopped or failed workspaces.
1053
+ * `PATCH /v1/workspaces/{id}`
1054
+ */
1055
+ update(id, body, opts) {
1056
+ return this.http.request({
1057
+ method: "PATCH",
1058
+ path: `/workspaces/${encodeURIComponent(id)}`,
1059
+ body,
1060
+ opts
1061
+ });
1062
+ }
1063
+ /**
1064
+ * Deletes a workspace asynchronously (`202 Accepted`).
1065
+ * `DELETE /v1/workspaces/{id}`
1066
+ */
1067
+ delete(id, opts) {
1068
+ return this.http.request({
1069
+ method: "DELETE",
1070
+ path: `/workspaces/${encodeURIComponent(id)}`,
1071
+ opts
1072
+ });
1073
+ }
1074
+ /**
1075
+ * Starts a stopped workspace (`202 Accepted`).
1076
+ * `POST /v1/workspaces/{id}/start`
1077
+ */
1078
+ start(id, body, opts) {
1079
+ let payload;
1080
+ if (body !== void 0) {
1081
+ const { noTimeout, ...rest } = body;
1082
+ if (noTimeout && rest.timeout !== void 0) {
1083
+ return Promise.reject(new TypeError("Cannot combine noTimeout with timeout"));
1084
+ }
1085
+ payload = noTimeout ? { ...rest, timeout: { seconds: 0 } } : rest;
1086
+ }
1087
+ return this.http.request({
1088
+ method: "POST",
1089
+ path: `/workspaces/${encodeURIComponent(id)}/start`,
1090
+ body: payload,
1091
+ opts
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Stops an available workspace (`202 Accepted`).
1096
+ * `POST /v1/workspaces/{id}/stop`
1097
+ */
1098
+ stop(id, body, opts) {
1099
+ return this.http.request({
1100
+ method: "POST",
1101
+ path: `/workspaces/${encodeURIComponent(id)}/stop`,
1102
+ body,
1103
+ opts
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Updates the auto-timeout policy for a workspace.
1108
+ * `POST /v1/workspaces/{id}/timeout`
1109
+ */
1110
+ setTimeout(id, body, opts) {
1111
+ return this.http.request({
1112
+ method: "POST",
1113
+ path: `/workspaces/${encodeURIComponent(id)}/timeout`,
1114
+ body,
1115
+ opts
1116
+ });
1117
+ }
1118
+ /**
1119
+ * Removes the auto-timeout policy so the workspace does not expire automatically.
1120
+ * `POST /v1/workspaces/{id}/timeout` with `{ seconds: 0 }`.
1121
+ */
1122
+ clearTimeout(id, opts) {
1123
+ return this.setTimeout(id, { seconds: 0 }, opts);
1124
+ }
1125
+ /**
1126
+ * Replaces the outbound network policy for a workspace.
1127
+ * `PUT /v1/workspaces/{id}/network`
1128
+ */
1129
+ setNetwork(id, body, opts) {
1130
+ return this.http.request({
1131
+ method: "PUT",
1132
+ path: `/workspaces/${encodeURIComponent(id)}/network`,
1133
+ body,
1134
+ opts
1135
+ });
1136
+ }
1137
+ setVolumes(id, body, opts) {
1138
+ return this.http.request({ method: "PUT", path: `${workspacePath(id)}/volumes`, body, opts });
1139
+ }
1140
+ setPacks(id, body, opts) {
1141
+ return this.http.request({ method: "PUT", path: `${workspacePath(id)}/packs`, body, opts });
1142
+ }
1143
+ getMetrics(id, params, opts) {
1144
+ return this.http.request({
1145
+ method: "GET",
1146
+ path: `${workspacePath(id)}/metrics`,
1147
+ query: buildQueryParams({
1148
+ start: params?.start instanceof Date ? params.start.toISOString() : params?.start,
1149
+ end: params?.end instanceof Date ? params.end.toISOString() : params?.end
1150
+ }),
1151
+ opts
1152
+ });
1153
+ }
1154
+ exec(id, body, opts) {
1155
+ return this.http.request({
1156
+ method: "POST",
1157
+ path: `${workspacePath(id)}/exec`,
1158
+ body,
1159
+ opts: { ...opts, timeoutMs: opts?.timeoutMs ?? ((body.timeout_seconds ?? 30) + 15) * 1e3 },
1160
+ accept: "application/json",
1161
+ nonReplayable: true,
1162
+ disableIdempotency: true
1163
+ });
1164
+ }
1165
+ async *execStream(id, body, opts) {
1166
+ const response = await this.http.requestResponse({
1167
+ method: "POST",
1168
+ path: `${workspacePath(id)}/exec`,
1169
+ body,
1170
+ opts: { ...opts, timeoutMs: opts?.timeoutMs ?? 0 },
1171
+ accept: "text/event-stream",
1172
+ nonReplayable: true,
1173
+ disableIdempotency: true
1174
+ });
1175
+ yield* parseExecEvents(response);
1176
+ }
1177
+ listFiles(id, path, opts) {
1178
+ return this.http.request({
1179
+ method: "GET",
1180
+ path: `${workspacePath(id)}/files`,
1181
+ query: buildQueryParams({ path, depth: opts?.depth, user: opts?.user }),
1182
+ opts
1183
+ });
1184
+ }
1185
+ statFile(id, path, opts) {
1186
+ return this.http.request({
1187
+ method: "GET",
1188
+ path: `${workspacePath(id)}/files/stat`,
1189
+ query: buildQueryParams({ path, user: opts?.user }),
1190
+ opts
1191
+ });
1192
+ }
1193
+ async readFile(id, path, opts) {
1194
+ const headers = new Headers(opts?.headers);
1195
+ if (opts?.range !== void 0) headers.set("Range", opts.range);
1196
+ if (opts?.ifNoneMatch !== void 0) headers.set("If-None-Match", opts.ifNoneMatch);
1197
+ const response = await this.http.requestResponse({
1198
+ method: "GET",
1199
+ path: `${workspacePath(id)}/files/content`,
1200
+ query: buildQueryParams({ path, user: opts?.user }),
1201
+ opts: { ...opts, headers: Object.fromEntries(headers), timeoutMs: opts?.timeoutMs ?? 0 },
1202
+ accept: "application/octet-stream",
1203
+ successStatuses: [304]
1204
+ });
1205
+ if (opts?.as === "bytes") return new Uint8Array(await response.arrayBuffer());
1206
+ if (opts?.as === "stream") return response.body;
1207
+ return response;
1208
+ }
1209
+ writeFile(id, path, content, opts) {
1210
+ const body = content instanceof Uint8Array ? content.buffer instanceof ArrayBuffer ? new Uint8Array(content.buffer, content.byteOffset, content.byteLength) : new Uint8Array(content) : content;
1211
+ return this.http.request({
1212
+ method: "PUT",
1213
+ path: `${workspacePath(id)}/files/content`,
1214
+ query: buildQueryParams({ path, mode: opts?.mode, create_only: opts?.createOnly, user: opts?.user }),
1215
+ opts: { ...opts, timeoutMs: opts?.timeoutMs ?? 0 },
1216
+ rawBody: body,
1217
+ duplex: body instanceof ReadableStream ? "half" : void 0,
1218
+ nonReplayable: true
1219
+ });
1220
+ }
1221
+ makeDir(id, body, opts) {
1222
+ return this.http.request({
1223
+ method: "POST",
1224
+ path: `${workspacePath(id)}/files/mkdir`,
1225
+ body,
1226
+ opts,
1227
+ nonReplayable: true,
1228
+ disableIdempotency: true
1229
+ });
1230
+ }
1231
+ moveFile(id, body, opts) {
1232
+ return this.http.request({
1233
+ method: "POST",
1234
+ path: `${workspacePath(id)}/files/move`,
1235
+ body,
1236
+ opts,
1237
+ nonReplayable: true,
1238
+ disableIdempotency: true
1239
+ });
1240
+ }
1241
+ deleteFile(id, path, opts) {
1242
+ return this.http.request({
1243
+ method: "DELETE",
1244
+ path: `${workspacePath(id)}/files`,
1245
+ query: buildQueryParams({ path, user: opts?.user }),
1246
+ opts,
1247
+ nonReplayable: true,
1248
+ disableIdempotency: true
1249
+ });
1250
+ }
1251
+ wsUrl(id) {
1252
+ return webSocketUrl(this.http.buildUrl(`${workspacePath(id)}/ws`));
1253
+ }
1254
+ tunnelWSUrl(id, target) {
1255
+ const url = this.http.buildUrl(`${workspacePath(id)}/tunnels/ws`, buildQueryParams({ ...target }));
1256
+ return webSocketUrl(url);
1257
+ }
1258
+ desktopVNCUrl(id) {
1259
+ return webSocketUrl(this.http.buildUrl(`${workspacePath(id)}/desktop/vnc`));
1260
+ }
1261
+ proxyUrl(id, port, path = "", query) {
1262
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1263
+ throw new RangeError("port must be between 1 and 65535");
1264
+ }
1265
+ const segments = path.replace(/^\//, "").split("/");
1266
+ if (segments.some((segment) => segment === "." || segment === "..")) {
1267
+ throw new TypeError("Proxy path must not contain dot segments");
1268
+ }
1269
+ const suffix = path ? `/${segments.map(encodeURIComponent).join("/")}` : "";
1270
+ return this.http.buildUrl(`${workspacePath(id)}/proxy/${port}${suffix}`, query);
1271
+ }
1272
+ proxyWSUrl(id, port, path, query) {
1273
+ return webSocketUrl(this.proxyUrl(id, port, path, query));
1274
+ }
1275
+ /** Headers for a WebSocket upgrade or an authenticated proxy request. */
1276
+ wsHeaders(overrides) {
1277
+ return this.http.buildHeaders(overrides);
1278
+ }
1279
+ connectWS(id, opts) {
1280
+ return new WorkspaceSocket(openWebSocket(this.wsUrl(id), this.wsHeaders(opts?.headers), opts));
1281
+ }
1282
+ connectTunnel(id, target, opts) {
1283
+ return openWebSocket(this.tunnelWSUrl(id, target), this.wsHeaders(opts?.headers), opts);
1284
+ }
1285
+ connectDesktop(id, opts) {
1286
+ return openWebSocket(this.desktopVNCUrl(id), this.wsHeaders(opts?.headers), opts);
1287
+ }
1288
+ connectProxy(id, port, opts) {
1289
+ const url = this.proxyWSUrl(id, port, opts?.path, opts?.query);
1290
+ return openWebSocket(url, this.wsHeaders(opts?.headers), opts);
1291
+ }
1292
+ /**
1293
+ * Attaches a volume to a workspace.
1294
+ * `PUT /v1/workspaces/{id}/volume`
1295
+ */
1296
+ attachVolume(id, body, opts) {
1297
+ return this.http.request({
1298
+ method: "PUT",
1299
+ path: `/workspaces/${encodeURIComponent(id)}/volume`,
1300
+ body,
1301
+ opts
1302
+ });
1303
+ }
1304
+ /**
1305
+ * Detaches the attached volume from a workspace.
1306
+ * `DELETE /v1/workspaces/{id}/volume`
1307
+ */
1308
+ detachVolume(id, opts) {
1309
+ return this.http.request({
1310
+ method: "DELETE",
1311
+ path: `/workspaces/${encodeURIComponent(id)}/volume`,
1312
+ opts
1313
+ });
1314
+ }
1315
+ /**
1316
+ * Waits until the workspace reaches one of the target statuses.
1317
+ * Automatically chunks calls into `<= 60s` windows when `timeoutSeconds > 60`.
1318
+ * `GET /v1/workspaces/{id}/wait`
1319
+ */
1320
+ wait(id, params, opts) {
1321
+ return executeWaitLoop(this.http, {
1322
+ path: `/workspaces/${encodeURIComponent(id)}/wait`,
1323
+ status: params.status,
1324
+ timeoutSeconds: params.timeoutSeconds,
1325
+ opts
1326
+ });
1327
+ }
1328
+ };
1329
+
1330
+ // src/resources/zones.ts
1331
+ var ZonesResource = class {
1332
+ constructor(http) {
1333
+ this.http = http;
1334
+ }
1335
+ http;
1336
+ /**
1337
+ * Lists zones available to the authenticated organization.
1338
+ * `GET /v1/zones`
1339
+ */
1340
+ list(params, opts) {
1341
+ return this.http.request({
1342
+ method: "GET",
1343
+ path: "/zones",
1344
+ query: buildQueryParams({
1345
+ limit: params?.limit,
1346
+ page_token: params?.page_token
1347
+ }),
1348
+ opts
1349
+ });
1350
+ }
1351
+ /**
1352
+ * Auto-paginates across all zones matching `params`.
1353
+ */
1354
+ iterate(params, opts) {
1355
+ return paginate(
1356
+ (pageToken) => this.list(
1357
+ {
1358
+ ...params,
1359
+ page_token: pageToken
1360
+ },
1361
+ opts
1362
+ ),
1363
+ params?.page_token
1364
+ );
1365
+ }
1366
+ };
1367
+
1368
+ // src/resources/egresses.ts
1369
+ var EgressesResource = class {
1370
+ constructor(http) {
1371
+ this.http = http;
1372
+ }
1373
+ http;
1374
+ create(body, opts) {
1375
+ return this.http.request({ method: "POST", path: "/egresses", body, opts });
1376
+ }
1377
+ list(params, opts) {
1378
+ return this.http.request({
1379
+ method: "GET",
1380
+ path: "/egresses",
1381
+ query: buildQueryParams({ ...params }),
1382
+ opts
1383
+ });
1384
+ }
1385
+ get(id, opts) {
1386
+ return this.http.request({ method: "GET", path: `/egresses/${encodeURIComponent(id)}`, opts });
1387
+ }
1388
+ replace(id, body, opts) {
1389
+ return this.http.request({ method: "PUT", path: `/egresses/${encodeURIComponent(id)}`, body, opts });
1390
+ }
1391
+ update(id, body, opts) {
1392
+ return this.http.request({ method: "PATCH", path: `/egresses/${encodeURIComponent(id)}`, body, opts });
1393
+ }
1394
+ delete(id, opts) {
1395
+ return this.http.request({ method: "DELETE", path: `/egresses/${encodeURIComponent(id)}`, opts });
1396
+ }
1397
+ };
1398
+
1399
+ // src/resources/packs.ts
1400
+ var PacksResource = class {
1401
+ constructor(http) {
1402
+ this.http = http;
1403
+ }
1404
+ http;
1405
+ list(params, opts) {
1406
+ return this.http.request({ method: "GET", path: "/packs", query: buildQueryParams({ ...params }), opts });
1407
+ }
1408
+ get(id, opts) {
1409
+ return this.http.request({ method: "GET", path: `/packs/${encodeURIComponent(id)}`, opts });
1410
+ }
1411
+ getRevision(id, revisionId, opts) {
1412
+ return this.http.request({
1413
+ method: "GET",
1414
+ path: `/packs/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}`,
1415
+ opts
1416
+ });
1417
+ }
1418
+ };
1419
+
1420
+ // src/resources/resolvers.ts
1421
+ var ResolversResource = class {
1422
+ constructor(http) {
1423
+ this.http = http;
1424
+ }
1425
+ http;
1426
+ create(body, opts) {
1427
+ return this.http.request({ method: "POST", path: "/resolvers", body, opts });
1428
+ }
1429
+ list(params, opts) {
1430
+ return this.http.request({
1431
+ method: "GET",
1432
+ path: "/resolvers",
1433
+ query: buildQueryParams({ ...params }),
1434
+ opts
1435
+ });
1436
+ }
1437
+ get(id, opts) {
1438
+ return this.http.request({ method: "GET", path: `/resolvers/${encodeURIComponent(id)}`, opts });
1439
+ }
1440
+ replace(id, body, opts) {
1441
+ return this.http.request({ method: "PUT", path: `/resolvers/${encodeURIComponent(id)}`, body, opts });
1442
+ }
1443
+ update(id, body, opts) {
1444
+ return this.http.request({ method: "PATCH", path: `/resolvers/${encodeURIComponent(id)}`, body, opts });
1445
+ }
1446
+ delete(id, opts) {
1447
+ return this.http.request({ method: "DELETE", path: `/resolvers/${encodeURIComponent(id)}`, opts });
1448
+ }
1449
+ };
1450
+
1451
+ // src/client.ts
1452
+ var Kibotos = class {
1453
+ zones;
1454
+ templates;
1455
+ workspaces;
1456
+ volumes;
1457
+ exposures;
1458
+ egresses;
1459
+ packs;
1460
+ resolvers;
1461
+ http;
1462
+ constructor(options = {}) {
1463
+ this.http = new HttpClient(options);
1464
+ this.zones = new ZonesResource(this.http);
1465
+ this.templates = new TemplatesResource(this.http);
1466
+ this.workspaces = new WorkspacesResource(this.http);
1467
+ this.volumes = new VolumesResource(this.http);
1468
+ this.egresses = new EgressesResource(this.http);
1469
+ this.packs = new PacksResource(this.http);
1470
+ this.resolvers = new ResolversResource(this.http);
1471
+ this.exposures = new ExposuresResource(this.http);
1472
+ }
1473
+ /** Normalized base URL (always ending in `/v1`). */
1474
+ get baseUrl() {
1475
+ return this.http.baseUrl;
1476
+ }
1477
+ };
1478
+
1479
+ exports.APIConnectionError = APIConnectionError;
1480
+ exports.AuthenticationError = AuthenticationError;
1481
+ exports.ConflictError = ConflictError;
1482
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1483
+ exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
1484
+ exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1485
+ exports.EgressesResource = EgressesResource;
1486
+ exports.ExposuresResource = ExposuresResource;
1487
+ exports.Kibotos = Kibotos;
1488
+ exports.KibotosAPIError = KibotosAPIError;
1489
+ exports.KibotosError = KibotosError;
1490
+ exports.NotFoundError = NotFoundError;
1491
+ exports.PacksResource = PacksResource;
1492
+ exports.PermissionDeniedError = PermissionDeniedError;
1493
+ exports.RateLimitError = RateLimitError;
1494
+ exports.ResolversResource = ResolversResource;
1495
+ exports.SDK_VERSION = SDK_VERSION;
1496
+ exports.TemplatesResource = TemplatesResource;
1497
+ exports.UnexpectedStatusError = UnexpectedStatusError;
1498
+ exports.VolumesResource = VolumesResource;
1499
+ exports.WaitTimeoutError = WaitTimeoutError;
1500
+ exports.WorkspaceChannel = WorkspaceChannel;
1501
+ exports.WorkspaceSocket = WorkspaceSocket;
1502
+ exports.WorkspacesResource = WorkspacesResource;
1503
+ exports.ZonesResource = ZonesResource;
1504
+ exports.decodeBinaryFrame = decodeBinaryFrame;
1505
+ exports.decodeWorkspaceFrame = decodeWorkspaceFrame;
1506
+ exports.encodeBinaryFrame = encodeBinaryFrame;
1507
+ //# sourceMappingURL=index.cjs.map
1508
+ //# sourceMappingURL=index.cjs.map