@kibotos/sdk 0.0.0-stage → 0.1.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,1026 @@
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.1.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 sleep(ms, signal) {
248
+ if (signal?.aborted) {
249
+ return Promise.reject(createAbortError(signal));
250
+ }
251
+ if (ms <= 0) {
252
+ return Promise.resolve();
253
+ }
254
+ return new Promise((resolve, reject) => {
255
+ const onAbort = () => {
256
+ clearTimeout(timer);
257
+ reject(createAbortError(signal));
258
+ };
259
+ const timer = setTimeout(() => {
260
+ signal?.removeEventListener("abort", onAbort);
261
+ resolve();
262
+ }, ms);
263
+ signal?.addEventListener("abort", onAbort, { once: true });
264
+ });
265
+ }
266
+ function calculateBackoffMs(attempt, retryAfterMs) {
267
+ if (retryAfterMs !== void 0 && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
268
+ return retryAfterMs;
269
+ }
270
+ const exponential = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);
271
+ const jitter = 0.5 + Math.random() * 0.5;
272
+ return Math.round(exponential * jitter);
273
+ }
274
+ var HttpClient = class {
275
+ baseUrl;
276
+ maxRetries;
277
+ timeoutMs;
278
+ apiKey;
279
+ fetchImpl;
280
+ defaultHeaders;
281
+ constructor(options = {}) {
282
+ this.apiKey = options.apiKey ?? readEnv("KIBOTOS_API_KEY");
283
+ this.baseUrl = normalizeBaseUrl(options.baseUrl ?? readEnv("KIBOTOS_API_URL") ?? DEFAULT_BASE_URL);
284
+ this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
285
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
286
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
287
+ this.defaultHeaders = { ...options.defaultHeaders ?? {} };
288
+ if (typeof this.fetchImpl !== "function") {
289
+ throw new APIConnectionError(
290
+ "No fetch implementation found. Provide a custom `fetch` option or use a runtime with global `fetch` (Node 20+, Bun, Deno, Cloudflare Workers)."
291
+ );
292
+ }
293
+ }
294
+ buildUrl(path, query) {
295
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
296
+ const url = new URL(`${this.baseUrl}${normalizedPath}`);
297
+ if (query) {
298
+ query.forEach((value, key) => {
299
+ url.searchParams.append(key, value);
300
+ });
301
+ }
302
+ return url.toString();
303
+ }
304
+ async request(config) {
305
+ const { method, path, query, body, opts, disableWaitTimeoutRetry } = config;
306
+ const url = this.buildUrl(path, query);
307
+ const effectiveTimeoutMs = opts?.timeoutMs ?? this.timeoutMs;
308
+ const userSignal = opts?.signal;
309
+ const headers = new Headers();
310
+ headers.set("Accept", "application/json");
311
+ headers.set("User-Agent", `@kibotos/sdk/${SDK_VERSION}`);
312
+ if (this.apiKey) {
313
+ headers.set("Authorization", `Bearer ${this.apiKey}`);
314
+ }
315
+ for (const [k, v] of Object.entries(this.defaultHeaders)) {
316
+ headers.set(k, v);
317
+ }
318
+ if (opts?.headers) {
319
+ for (const [k, v] of Object.entries(opts.headers)) {
320
+ headers.set(k, v);
321
+ }
322
+ }
323
+ const hasBody = body !== void 0;
324
+ const serializedBody = hasBody ? JSON.stringify(body) : void 0;
325
+ if (hasBody && !headers.has("Content-Type")) {
326
+ headers.set("Content-Type", "application/json");
327
+ }
328
+ if (opts?.idempotencyKey) {
329
+ headers.set("Idempotency-Key", opts.idempotencyKey);
330
+ } else if (method === "POST" && !headers.has("Idempotency-Key")) {
331
+ headers.set("Idempotency-Key", generateUuid());
332
+ }
333
+ let attempt = 0;
334
+ while (true) {
335
+ if (userSignal?.aborted) {
336
+ throw createAbortError(userSignal);
337
+ }
338
+ const { signal, isTimeout, cleanup } = combineSignals(userSignal, effectiveTimeoutMs);
339
+ let response;
340
+ try {
341
+ response = await this.fetchImpl(url, {
342
+ method,
343
+ headers,
344
+ body: serializedBody,
345
+ signal
346
+ });
347
+ } catch (err) {
348
+ cleanup();
349
+ if (userSignal?.aborted) {
350
+ throw createAbortError(userSignal);
351
+ }
352
+ const connectionError = isTimeout() ? new APIConnectionError(`Request timed out after ${effectiveTimeoutMs}ms`, { cause: err }) : new APIConnectionError(
353
+ err instanceof Error && err.message ? `Network error: ${err.message}` : "Network error while contacting the Kibotos API",
354
+ { cause: err }
355
+ );
356
+ if (attempt < this.maxRetries) {
357
+ const delayMs = calculateBackoffMs(attempt);
358
+ attempt += 1;
359
+ await sleep(delayMs, userSignal);
360
+ continue;
361
+ }
362
+ throw connectionError;
363
+ }
364
+ let parsedBody;
365
+ try {
366
+ const text = await response.text();
367
+ if (text.length > 0) {
368
+ try {
369
+ parsedBody = JSON.parse(text);
370
+ } catch {
371
+ parsedBody = text;
372
+ }
373
+ }
374
+ } catch (err) {
375
+ cleanup();
376
+ if (userSignal?.aborted) {
377
+ throw createAbortError(userSignal);
378
+ }
379
+ 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 });
380
+ if (attempt < this.maxRetries) {
381
+ const delayMs = calculateBackoffMs(attempt);
382
+ attempt += 1;
383
+ await sleep(delayMs, userSignal);
384
+ continue;
385
+ }
386
+ throw readError;
387
+ } finally {
388
+ cleanup();
389
+ }
390
+ if (response.ok) {
391
+ return parsedBody;
392
+ }
393
+ const apiError = createAPIError(
394
+ response.status,
395
+ response.headers,
396
+ parsedBody,
397
+ response.statusText || void 0
398
+ );
399
+ if (this.shouldRetryAPIError(apiError, disableWaitTimeoutRetry) && attempt < this.maxRetries) {
400
+ const retryAfterMs = apiError instanceof RateLimitError ? apiError.retryAfterMs : parseRetryAfterMs(response.headers.get("Retry-After"));
401
+ const delayMs = calculateBackoffMs(attempt, retryAfterMs);
402
+ attempt += 1;
403
+ await sleep(delayMs, userSignal);
404
+ continue;
405
+ }
406
+ throw apiError;
407
+ }
408
+ }
409
+ shouldRetryAPIError(error, disableWaitTimeoutRetry) {
410
+ if (disableWaitTimeoutRetry && error.status === 408 && error.code === "wait_timeout") {
411
+ return false;
412
+ }
413
+ return error.retryable || RETRYABLE_HTTP_STATUSES.has(error.status);
414
+ }
415
+ };
416
+
417
+ // src/pagination.ts
418
+ async function* paginate(fetchPage, initialPageToken) {
419
+ let pageToken = initialPageToken;
420
+ const seenTokens = /* @__PURE__ */ new Set();
421
+ while (true) {
422
+ const page = await fetchPage(pageToken);
423
+ for (const item of page.data) {
424
+ yield item;
425
+ }
426
+ const next = page.next_page_token;
427
+ if (!next || seenTokens.has(next)) {
428
+ break;
429
+ }
430
+ seenTokens.add(next);
431
+ pageToken = next;
432
+ }
433
+ }
434
+ function buildQueryParams(params) {
435
+ const searchParams = new URLSearchParams();
436
+ if (!params) {
437
+ return searchParams;
438
+ }
439
+ for (const [key, value] of Object.entries(params)) {
440
+ if (value === void 0) {
441
+ continue;
442
+ }
443
+ if (key === "labels" && typeof value === "object" && !Array.isArray(value)) {
444
+ for (const [labelKey, labelValue] of Object.entries(value)) {
445
+ searchParams.set(`label.${labelKey}`, labelValue);
446
+ }
447
+ } else if (Array.isArray(value)) {
448
+ for (const item of value) {
449
+ searchParams.append(key, String(item));
450
+ }
451
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
452
+ searchParams.set(key, String(value));
453
+ }
454
+ }
455
+ return searchParams;
456
+ }
457
+
458
+ // src/resources/exposures.ts
459
+ var ExposuresResource = class {
460
+ constructor(http) {
461
+ this.http = http;
462
+ }
463
+ http;
464
+ /**
465
+ * Creates a public HTTPS exposure for a workspace port (`201 Created`).
466
+ * `POST /v1/workspaces/{id}/exposures`
467
+ */
468
+ create(workspaceId, body, opts) {
469
+ return this.http.request({
470
+ method: "POST",
471
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures`,
472
+ body,
473
+ opts
474
+ });
475
+ }
476
+ /**
477
+ * Lists exposures for a workspace.
478
+ * `GET /v1/workspaces/{id}/exposures`
479
+ */
480
+ list(workspaceId, params, opts) {
481
+ return this.http.request({
482
+ method: "GET",
483
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures`,
484
+ query: buildQueryParams({
485
+ include_revoked: params?.include_revoked,
486
+ limit: params?.limit,
487
+ page_token: params?.page_token
488
+ }),
489
+ opts
490
+ });
491
+ }
492
+ /**
493
+ * Auto-paginates across all exposures for a workspace.
494
+ */
495
+ iterate(workspaceId, params, opts) {
496
+ return paginate(
497
+ (pageToken) => this.list(
498
+ workspaceId,
499
+ {
500
+ ...params,
501
+ page_token: pageToken
502
+ },
503
+ opts
504
+ ),
505
+ params?.page_token
506
+ );
507
+ }
508
+ /**
509
+ * Retrieves a specific exposure by ID.
510
+ * `GET /v1/workspaces/{id}/exposures/{exposure_id}`
511
+ */
512
+ get(workspaceId, exposureId, opts) {
513
+ return this.http.request({
514
+ method: "GET",
515
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures/${encodeURIComponent(exposureId)}`,
516
+ opts
517
+ });
518
+ }
519
+ /**
520
+ * Revokes an active exposure.
521
+ * `DELETE /v1/workspaces/{id}/exposures/{exposure_id}`
522
+ */
523
+ revoke(workspaceId, exposureId, opts) {
524
+ return this.http.request({
525
+ method: "DELETE",
526
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures/${encodeURIComponent(exposureId)}`,
527
+ opts
528
+ });
529
+ }
530
+ };
531
+
532
+ // src/resources/templates.ts
533
+ var TemplatesResource = class {
534
+ constructor(http) {
535
+ this.http = http;
536
+ }
537
+ http;
538
+ /**
539
+ * Lists templates across zones.
540
+ * `GET /v1/templates`
541
+ */
542
+ list(params, opts) {
543
+ return this.http.request({
544
+ method: "GET",
545
+ path: "/templates",
546
+ query: buildQueryParams({
547
+ owner: params?.owner,
548
+ zone: params?.zone,
549
+ limit: params?.limit,
550
+ page_token: params?.page_token
551
+ }),
552
+ opts
553
+ });
554
+ }
555
+ /**
556
+ * Auto-paginates across all templates matching `params`.
557
+ */
558
+ iterate(params, opts) {
559
+ return paginate(
560
+ (pageToken) => this.list(
561
+ {
562
+ ...params,
563
+ page_token: pageToken
564
+ },
565
+ opts
566
+ ),
567
+ params?.page_token
568
+ );
569
+ }
570
+ /**
571
+ * Retrieves a template by ID.
572
+ * `GET /v1/templates/{id}`
573
+ */
574
+ get(id, opts) {
575
+ return this.http.request({
576
+ method: "GET",
577
+ path: `/templates/${encodeURIComponent(id)}`,
578
+ opts
579
+ });
580
+ }
581
+ /**
582
+ * Lists revisions for a template.
583
+ * `GET /v1/templates/{id}/revisions`
584
+ */
585
+ listRevisions(id, params, opts) {
586
+ return this.http.request({
587
+ method: "GET",
588
+ path: `/templates/${encodeURIComponent(id)}/revisions`,
589
+ query: buildQueryParams({
590
+ limit: params?.limit,
591
+ page_token: params?.page_token
592
+ }),
593
+ opts
594
+ });
595
+ }
596
+ /**
597
+ * Retrieves a specific template revision.
598
+ * `GET /v1/templates/{id}/revisions/{revision_id}`
599
+ */
600
+ getRevision(id, revisionId, opts) {
601
+ return this.http.request({
602
+ method: "GET",
603
+ path: `/templates/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}`,
604
+ opts
605
+ });
606
+ }
607
+ };
608
+
609
+ // src/wait.ts
610
+ var DEFAULT_WAIT_TIMEOUT_SECONDS = 30;
611
+ var MAX_CHUNK_TIMEOUT_SECONDS = 60;
612
+ var HTTP_TIMEOUT_BUFFER_SECONDS = 15;
613
+ async function executeWaitLoop(http, params) {
614
+ const statuses = Array.isArray(params.status) ? params.status : [params.status];
615
+ if (statuses.length === 0) {
616
+ throw new KibotosError("wait() requires at least one target status");
617
+ }
618
+ const totalTimeoutSeconds = params.timeoutSeconds ?? DEFAULT_WAIT_TIMEOUT_SECONDS;
619
+ if (!Number.isFinite(totalTimeoutSeconds) || totalTimeoutSeconds <= 0) {
620
+ throw new KibotosError("wait() timeoutSeconds must be a positive number");
621
+ }
622
+ const deadlineMs = Date.now() + totalTimeoutSeconds * 1e3;
623
+ let remainingBudgetSeconds = totalTimeoutSeconds;
624
+ while (true) {
625
+ if (params.opts?.signal?.aborted) {
626
+ throw params.opts.signal.reason ?? new Error("The operation was aborted.");
627
+ }
628
+ const chunkSeconds = Math.min(
629
+ MAX_CHUNK_TIMEOUT_SECONDS,
630
+ Math.max(1, Math.ceil(remainingBudgetSeconds))
631
+ );
632
+ const query = new URLSearchParams();
633
+ for (const status of statuses) {
634
+ query.append("status", status);
635
+ }
636
+ query.set("timeout", String(chunkSeconds));
637
+ const effectiveOpts = {
638
+ ...params.opts,
639
+ timeoutMs: params.opts?.timeoutMs ?? Math.max(http.timeoutMs, (chunkSeconds + HTTP_TIMEOUT_BUFFER_SECONDS) * 1e3)
640
+ };
641
+ try {
642
+ return await http.request({
643
+ method: "GET",
644
+ path: params.path,
645
+ query,
646
+ opts: effectiveOpts,
647
+ disableWaitTimeoutRetry: true
648
+ });
649
+ } catch (err) {
650
+ if (!(err instanceof WaitTimeoutError)) {
651
+ throw err;
652
+ }
653
+ const wallRemainingSeconds = (deadlineMs - Date.now()) / 1e3;
654
+ remainingBudgetSeconds = Math.min(remainingBudgetSeconds - chunkSeconds, wallRemainingSeconds);
655
+ if (remainingBudgetSeconds <= 0) {
656
+ throw err;
657
+ }
658
+ }
659
+ }
660
+ }
661
+
662
+ // src/resources/volumes.ts
663
+ var VolumesResource = class {
664
+ constructor(http) {
665
+ this.http = http;
666
+ }
667
+ http;
668
+ /**
669
+ * Creates a new persistent volume asynchronously (`202 Accepted`).
670
+ * `POST /v1/volumes`
671
+ */
672
+ create(body, opts) {
673
+ return this.http.request({
674
+ method: "POST",
675
+ path: "/volumes",
676
+ body,
677
+ opts
678
+ });
679
+ }
680
+ /**
681
+ * Lists volumes across zones.
682
+ * `GET /v1/volumes`
683
+ */
684
+ list(params, opts) {
685
+ return this.http.request({
686
+ method: "GET",
687
+ path: "/volumes",
688
+ query: buildQueryParams({
689
+ zone: params?.zone,
690
+ attached: params?.attached,
691
+ labels: params?.labels,
692
+ limit: params?.limit,
693
+ page_token: params?.page_token
694
+ }),
695
+ opts
696
+ });
697
+ }
698
+ /**
699
+ * Auto-paginates across all volumes matching `params`.
700
+ */
701
+ iterate(params, opts) {
702
+ return paginate(
703
+ (pageToken) => this.list(
704
+ {
705
+ ...params,
706
+ page_token: pageToken
707
+ },
708
+ opts
709
+ ),
710
+ params?.page_token
711
+ );
712
+ }
713
+ /**
714
+ * Retrieves a volume by ID.
715
+ * `GET /v1/volumes/{id}`
716
+ */
717
+ get(id, opts) {
718
+ return this.http.request({
719
+ method: "GET",
720
+ path: `/volumes/${encodeURIComponent(id)}`,
721
+ opts
722
+ });
723
+ }
724
+ /**
725
+ * Updates volume metadata (`name` and/or `labels`).
726
+ * `PATCH /v1/volumes/{id}`
727
+ */
728
+ update(id, body, opts) {
729
+ return this.http.request({
730
+ method: "PATCH",
731
+ path: `/volumes/${encodeURIComponent(id)}`,
732
+ body,
733
+ opts
734
+ });
735
+ }
736
+ /**
737
+ * Resizes a volume asynchronously (`202 Accepted`).
738
+ * `POST /v1/volumes/{id}/resize`
739
+ */
740
+ resize(id, body, opts) {
741
+ return this.http.request({
742
+ method: "POST",
743
+ path: `/volumes/${encodeURIComponent(id)}/resize`,
744
+ body,
745
+ opts
746
+ });
747
+ }
748
+ /**
749
+ * Deletes a volume asynchronously (`202 Accepted`).
750
+ * `DELETE /v1/volumes/{id}`
751
+ */
752
+ delete(id, opts) {
753
+ return this.http.request({
754
+ method: "DELETE",
755
+ path: `/volumes/${encodeURIComponent(id)}`,
756
+ opts
757
+ });
758
+ }
759
+ /**
760
+ * Waits until the volume reaches one of the target statuses.
761
+ * Automatically chunks calls into `<= 60s` windows when `timeoutSeconds > 60`.
762
+ * `GET /v1/volumes/{id}/wait`
763
+ */
764
+ wait(id, params, opts) {
765
+ return executeWaitLoop(this.http, {
766
+ path: `/volumes/${encodeURIComponent(id)}/wait`,
767
+ status: params.status,
768
+ timeoutSeconds: params.timeoutSeconds,
769
+ opts
770
+ });
771
+ }
772
+ };
773
+
774
+ // src/resources/workspaces.ts
775
+ var WorkspacesResource = class {
776
+ constructor(http) {
777
+ this.http = http;
778
+ }
779
+ http;
780
+ /**
781
+ * Creates a new workspace asynchronously (`202 Accepted`).
782
+ * `POST /v1/workspaces`
783
+ */
784
+ create(body, opts) {
785
+ return this.http.request({
786
+ method: "POST",
787
+ path: "/workspaces",
788
+ body,
789
+ opts
790
+ });
791
+ }
792
+ /**
793
+ * Lists workspaces across zones.
794
+ * `GET /v1/workspaces`
795
+ */
796
+ list(params, opts) {
797
+ return this.http.request({
798
+ method: "GET",
799
+ path: "/workspaces",
800
+ query: buildQueryParams({
801
+ status: params?.status,
802
+ zone: params?.zone,
803
+ labels: params?.labels,
804
+ limit: params?.limit,
805
+ page_token: params?.page_token
806
+ }),
807
+ opts
808
+ });
809
+ }
810
+ /**
811
+ * Auto-paginates across all workspaces matching `params`.
812
+ */
813
+ iterate(params, opts) {
814
+ return paginate(
815
+ (pageToken) => this.list(
816
+ {
817
+ ...params,
818
+ page_token: pageToken
819
+ },
820
+ opts
821
+ ),
822
+ params?.page_token
823
+ );
824
+ }
825
+ /**
826
+ * Retrieves a workspace by ID.
827
+ * `GET /v1/workspaces/{id}`
828
+ */
829
+ get(id, opts) {
830
+ return this.http.request({
831
+ method: "GET",
832
+ path: `/workspaces/${encodeURIComponent(id)}`,
833
+ opts
834
+ });
835
+ }
836
+ /**
837
+ * Updates workspace metadata (`name` and/or `labels`).
838
+ * `PATCH /v1/workspaces/{id}`
839
+ */
840
+ update(id, body, opts) {
841
+ return this.http.request({
842
+ method: "PATCH",
843
+ path: `/workspaces/${encodeURIComponent(id)}`,
844
+ body,
845
+ opts
846
+ });
847
+ }
848
+ /**
849
+ * Deletes a workspace asynchronously (`202 Accepted`).
850
+ * `DELETE /v1/workspaces/{id}`
851
+ */
852
+ delete(id, opts) {
853
+ return this.http.request({
854
+ method: "DELETE",
855
+ path: `/workspaces/${encodeURIComponent(id)}`,
856
+ opts
857
+ });
858
+ }
859
+ /**
860
+ * Starts a stopped workspace (`202 Accepted`).
861
+ * `POST /v1/workspaces/{id}/start`
862
+ */
863
+ start(id, body, opts) {
864
+ return this.http.request({
865
+ method: "POST",
866
+ path: `/workspaces/${encodeURIComponent(id)}/start`,
867
+ body,
868
+ opts
869
+ });
870
+ }
871
+ /**
872
+ * Stops an available workspace (`202 Accepted`).
873
+ * `POST /v1/workspaces/{id}/stop`
874
+ */
875
+ stop(id, body, opts) {
876
+ return this.http.request({
877
+ method: "POST",
878
+ path: `/workspaces/${encodeURIComponent(id)}/stop`,
879
+ body,
880
+ opts
881
+ });
882
+ }
883
+ /**
884
+ * Updates the auto-timeout policy for a workspace.
885
+ * `POST /v1/workspaces/{id}/timeout`
886
+ */
887
+ setTimeout(id, body, opts) {
888
+ return this.http.request({
889
+ method: "POST",
890
+ path: `/workspaces/${encodeURIComponent(id)}/timeout`,
891
+ body,
892
+ opts
893
+ });
894
+ }
895
+ /**
896
+ * Sets the network mode for a workspace.
897
+ * `PUT /v1/workspaces/{id}/network`
898
+ */
899
+ setNetwork(id, body, opts) {
900
+ return this.http.request({
901
+ method: "PUT",
902
+ path: `/workspaces/${encodeURIComponent(id)}/network`,
903
+ body,
904
+ opts
905
+ });
906
+ }
907
+ /**
908
+ * Attaches a volume to a workspace.
909
+ * `PUT /v1/workspaces/{id}/volume`
910
+ */
911
+ attachVolume(id, body, opts) {
912
+ return this.http.request({
913
+ method: "PUT",
914
+ path: `/workspaces/${encodeURIComponent(id)}/volume`,
915
+ body,
916
+ opts
917
+ });
918
+ }
919
+ /**
920
+ * Detaches the attached volume from a workspace.
921
+ * `DELETE /v1/workspaces/{id}/volume`
922
+ */
923
+ detachVolume(id, opts) {
924
+ return this.http.request({
925
+ method: "DELETE",
926
+ path: `/workspaces/${encodeURIComponent(id)}/volume`,
927
+ opts
928
+ });
929
+ }
930
+ /**
931
+ * Waits until the workspace reaches one of the target statuses.
932
+ * Automatically chunks calls into `<= 60s` windows when `timeoutSeconds > 60`.
933
+ * `GET /v1/workspaces/{id}/wait`
934
+ */
935
+ wait(id, params, opts) {
936
+ return executeWaitLoop(this.http, {
937
+ path: `/workspaces/${encodeURIComponent(id)}/wait`,
938
+ status: params.status,
939
+ timeoutSeconds: params.timeoutSeconds,
940
+ opts
941
+ });
942
+ }
943
+ };
944
+
945
+ // src/resources/zones.ts
946
+ var ZonesResource = class {
947
+ constructor(http) {
948
+ this.http = http;
949
+ }
950
+ http;
951
+ /**
952
+ * Lists zones available to the authenticated organization.
953
+ * `GET /v1/zones`
954
+ */
955
+ list(params, opts) {
956
+ return this.http.request({
957
+ method: "GET",
958
+ path: "/zones",
959
+ query: buildQueryParams({
960
+ limit: params?.limit,
961
+ page_token: params?.page_token
962
+ }),
963
+ opts
964
+ });
965
+ }
966
+ /**
967
+ * Auto-paginates across all zones matching `params`.
968
+ */
969
+ iterate(params, opts) {
970
+ return paginate(
971
+ (pageToken) => this.list(
972
+ {
973
+ ...params,
974
+ page_token: pageToken
975
+ },
976
+ opts
977
+ ),
978
+ params?.page_token
979
+ );
980
+ }
981
+ };
982
+
983
+ // src/client.ts
984
+ var Kibotos = class {
985
+ zones;
986
+ templates;
987
+ workspaces;
988
+ volumes;
989
+ exposures;
990
+ http;
991
+ constructor(options = {}) {
992
+ this.http = new HttpClient(options);
993
+ this.zones = new ZonesResource(this.http);
994
+ this.templates = new TemplatesResource(this.http);
995
+ this.workspaces = new WorkspacesResource(this.http);
996
+ this.volumes = new VolumesResource(this.http);
997
+ this.exposures = new ExposuresResource(this.http);
998
+ }
999
+ /** Normalized base URL (always ending in `/v1`). */
1000
+ get baseUrl() {
1001
+ return this.http.baseUrl;
1002
+ }
1003
+ };
1004
+
1005
+ exports.APIConnectionError = APIConnectionError;
1006
+ exports.AuthenticationError = AuthenticationError;
1007
+ exports.ConflictError = ConflictError;
1008
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1009
+ exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
1010
+ exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1011
+ exports.ExposuresResource = ExposuresResource;
1012
+ exports.Kibotos = Kibotos;
1013
+ exports.KibotosAPIError = KibotosAPIError;
1014
+ exports.KibotosError = KibotosError;
1015
+ exports.NotFoundError = NotFoundError;
1016
+ exports.PermissionDeniedError = PermissionDeniedError;
1017
+ exports.RateLimitError = RateLimitError;
1018
+ exports.SDK_VERSION = SDK_VERSION;
1019
+ exports.TemplatesResource = TemplatesResource;
1020
+ exports.UnexpectedStatusError = UnexpectedStatusError;
1021
+ exports.VolumesResource = VolumesResource;
1022
+ exports.WaitTimeoutError = WaitTimeoutError;
1023
+ exports.WorkspacesResource = WorkspacesResource;
1024
+ exports.ZonesResource = ZonesResource;
1025
+ //# sourceMappingURL=index.cjs.map
1026
+ //# sourceMappingURL=index.cjs.map