@containify-platform/sdk 0.0.0-stage → 1.0.317

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/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @containify-platform/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Containify API for TypeScript and JavaScript: every route typed from the API's OpenAPI
4
+ spec, retries that are safe for writes, a helper to follow deploys, and webhook signature
5
+ checks. Runs in Node 18+, Bun, Deno and edge runtimes.
6
+
7
+ ```bash
8
+ npm install @containify-platform/sdk
9
+ ```
10
+
11
+ ```ts
12
+ import { Containify } from '@containify-platform/sdk'
13
+
14
+ const cfy = new Containify({ token: process.env.CONTAINIFY_TOKEN! })
15
+
16
+ const { project } = await cfy.call(
17
+ cfy.api.POST('/projects', { body: { name: 'acme', workspaceId, labels: { customer: '4821' } } }),
18
+ )
19
+ ```
20
+
21
+ Docs: https://containify.cloud/docs/api/sdks
@@ -0,0 +1,50 @@
1
+ import createClient from 'openapi-fetch';
2
+ import type { components, paths } from './schema.js';
3
+ export type { components, paths };
4
+ export { withRetries, type RetryOptions } from './retry.js';
5
+ export { verifyWebhook, WebhookVerificationError, type WebhookEvent } from './webhooks.js';
6
+ /** The API's address. */
7
+ export declare const DEFAULT_BASE_URL = "https://api.containify.cloud";
8
+ export type Client = ReturnType<typeof createClient<paths>>;
9
+ export type Operation = components['schemas']['Operation'];
10
+ export interface ContainifyOptions {
11
+ /** An API key: personal, a service account's, or a project token (cfy_…). */
12
+ token: string;
13
+ /** Defaults to DEFAULT_BASE_URL. */
14
+ baseUrl?: string;
15
+ /** A fetch to use instead of the global one. */
16
+ fetch?: typeof fetch;
17
+ /** Retry network errors, 429s, 502s, 503s and 504s, with an idempotency key on writes. On by default. */
18
+ retries?: boolean;
19
+ }
20
+ /** A response that wasn't a success: its status, the API's message, and the request's id for support. */
21
+ export declare class ContainifyError extends Error {
22
+ readonly status: number;
23
+ readonly body: unknown;
24
+ readonly requestId: string | null;
25
+ constructor(message: string, status: number, body: unknown, requestId: string | null);
26
+ }
27
+ export declare class Containify {
28
+ /** The typed client: cfy.api.GET('/projects/{id}', { params: { path: { id } } }). */
29
+ readonly api: Client;
30
+ constructor(opts: ContainifyOptions);
31
+ /**
32
+ * The body of a successful response, or throw a ContainifyError with the
33
+ * API's message:
34
+ * const { apps } = await cfy.call(cfy.api.GET('/projects/{id}/environments/{envId}/apps', …))
35
+ */
36
+ call<T>(request: Promise<{
37
+ data?: T;
38
+ error?: unknown;
39
+ response: Response;
40
+ }>): Promise<T>;
41
+ /**
42
+ * Follow an operation (what a write that deployed something returned) until
43
+ * it's done, a minute at a time, and return it: check `status` for
44
+ * SUCCEEDED, FAILED or CANCELLED. Throws if it isn't done within timeoutMs.
45
+ */
46
+ waitForOperation(id: string, opts?: {
47
+ timeoutMs?: number;
48
+ signal?: AbortSignal;
49
+ }): Promise<Operation>;
50
+ }
package/dist/index.js ADDED
@@ -0,0 +1,78 @@
1
+ // The Containify API, typed. Every route, parameter and response comes from
2
+ // the API's OpenAPI spec (schema.d.ts, `bun run generate`), through
3
+ // openapi-fetch, with retries that are safe for writes (retry.ts), a helper to
4
+ // follow operations, and webhook signature checks (webhooks.ts).
5
+ //
6
+ // import { Containify } from '@containify-platform/sdk'
7
+ // const cfy = new Containify({ token: process.env.CONTAINIFY_TOKEN! })
8
+ // const { project } = await cfy.call(cfy.api.POST('/projects', { body: { name: 'acme', workspaceId } }))
9
+ //
10
+ // Docs: https://containify.cloud/docs/api/sdks
11
+ import createClient from 'openapi-fetch';
12
+ import { withRetries } from './retry.js';
13
+ export { withRetries } from './retry.js';
14
+ export { verifyWebhook, WebhookVerificationError } from './webhooks.js';
15
+ /** The API's address. */
16
+ export const DEFAULT_BASE_URL = 'https://api.containify.cloud';
17
+ /** A response that wasn't a success: its status, the API's message, and the request's id for support. */
18
+ export class ContainifyError extends Error {
19
+ status;
20
+ body;
21
+ requestId;
22
+ constructor(message, status, body, requestId) {
23
+ super(message);
24
+ this.status = status;
25
+ this.body = body;
26
+ this.requestId = requestId;
27
+ this.name = 'ContainifyError';
28
+ }
29
+ }
30
+ export class Containify {
31
+ /** The typed client: cfy.api.GET('/projects/{id}', { params: { path: { id } } }). */
32
+ api;
33
+ constructor(opts) {
34
+ if (!opts.token)
35
+ throw new Error('Containify: pass an API key as token');
36
+ const base = opts.fetch ?? globalThis.fetch;
37
+ const send = opts.retries === false ? base : withRetries(base);
38
+ this.api = createClient({
39
+ baseUrl: (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ''),
40
+ headers: { Authorization: `Bearer ${opts.token}` },
41
+ fetch: (request) => send(request),
42
+ });
43
+ }
44
+ /**
45
+ * The body of a successful response, or throw a ContainifyError with the
46
+ * API's message:
47
+ * const { apps } = await cfy.call(cfy.api.GET('/projects/{id}/environments/{envId}/apps', …))
48
+ */
49
+ async call(request) {
50
+ const { data, error, response } = await request;
51
+ if (response.ok && data !== undefined)
52
+ return data;
53
+ if (response.ok)
54
+ return undefined;
55
+ const message = error?.error;
56
+ throw new ContainifyError(typeof message === 'string' ? message : `The API answered ${response.status}`, response.status, error, response.headers.get('x-request-id'));
57
+ }
58
+ /**
59
+ * Follow an operation (what a write that deployed something returned) until
60
+ * it's done, a minute at a time, and return it: check `status` for
61
+ * SUCCEEDED, FAILED or CANCELLED. Throws if it isn't done within timeoutMs.
62
+ */
63
+ async waitForOperation(id, opts = {}) {
64
+ const until = Date.now() + (opts.timeoutMs ?? 30 * 60_000);
65
+ for (;;) {
66
+ const left = Math.ceil((until - Date.now()) / 1000);
67
+ const { operation } = await this.call(this.api.GET('/operations/{id}', {
68
+ params: { path: { id }, query: { wait: Math.max(0, Math.min(60, left)) } },
69
+ signal: opts.signal,
70
+ }));
71
+ if (operation.done)
72
+ return operation;
73
+ if (Date.now() >= until)
74
+ throw new Error(`Operation ${id} is still ${operation.status} after the timeout`);
75
+ opts.signal?.throwIfAborted();
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,8 @@
1
+ export interface RetryOptions {
2
+ attempts?: number;
3
+ /** Milliseconds before each retry; the last one repeats. */
4
+ delays?: number[];
5
+ sleep?: (ms: number) => Promise<void>;
6
+ }
7
+ /** Wrap fetch so requests are retried as above. Streamed bodies (uploads) are sent once. */
8
+ export declare function withRetries(inner: typeof fetch, opts?: RetryOptions): (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
package/dist/retry.js ADDED
@@ -0,0 +1,45 @@
1
+ // Retries for the API client (the SDK's, and the CLI's through it). A
2
+ // request that fails on the network or with a 502, 503 or 504 (a proxy or a
3
+ // restarting API) is sent again, twice at most; one rate limited (429) is
4
+ // sent again after its Retry-After, if that's 30 seconds or less. Writes
5
+ // carry an Idempotency-Key, the same on every attempt, so a write that did
6
+ // reach the API before the connection dropped runs once: the retry gets its
7
+ // first answer back (docs: /docs/api/idempotency).
8
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
9
+ const MAX_RETRY_AFTER_MS = 30_000;
10
+ const WRITES = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
11
+ /** Wrap fetch so requests are retried as above. Streamed bodies (uploads) are sent once. */
12
+ export function withRetries(inner, opts = {}) {
13
+ const attempts = opts.attempts ?? 3;
14
+ const delays = opts.delays ?? [500, 1500];
15
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
16
+ return async (input, init) => {
17
+ const request = input instanceof Request ? new Request(input, init) : new Request(String(input), init);
18
+ // A streamed body can't be sent twice.
19
+ if (init?.body instanceof ReadableStream)
20
+ return inner(request);
21
+ if (WRITES.has(request.method) && !request.headers.has('idempotency-key')) {
22
+ request.headers.set('idempotency-key', crypto.randomUUID());
23
+ }
24
+ for (let attempt = 1;; attempt++) {
25
+ const last = attempt >= attempts;
26
+ let wait = delays[Math.min(attempt - 1, delays.length - 1)] ?? 0;
27
+ try {
28
+ const res = await inner((last ? request : request.clone()));
29
+ if (last || !RETRY_STATUSES.has(res.status))
30
+ return res;
31
+ const after = Number(res.headers.get('retry-after'));
32
+ if (res.status === 429 && after > 0) {
33
+ if (after * 1000 > MAX_RETRY_AFTER_MS)
34
+ return res;
35
+ wait = Math.max(wait, after * 1000);
36
+ }
37
+ }
38
+ catch (err) {
39
+ if (last)
40
+ throw err;
41
+ }
42
+ await sleep(wait);
43
+ }
44
+ };
45
+ }