@insforge/instabox-sdk 0.0.0-stage → 0.1.1
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/LICENSE +201 -0
- package/README.md +227 -2
- package/dist/index.cjs +700 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +466 -0
- package/dist/index.d.ts +466 -0
- package/dist/index.js +677 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -4
- package/skills/instabox/SKILL.md +116 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/util.ts","../src/commands.ts","../src/files.ts","../src/http.ts","../src/sandbox.ts"],"sourcesContent":["export { Sandbox, DEFAULT_TEMPLATE } from './sandbox'\nexport type {\n SandboxOpts,\n SandboxConnectOpts,\n SandboxListOpts,\n SandboxInfo,\n ForkOpts,\n CreateSnapshotOpts,\n SshCredentials,\n} from './sandbox'\nexport { Commands } from './commands'\nexport type { CommandOptions, CommandHandle } from './commands'\nexport { Files, MAX_FILE_BYTES } from './files'\nexport type { EntryInfo, WriteInfo } from './files'\nexport { DEFAULT_API_URL } from './http'\nexport type { ConnectionOptions } from './http'\nexport { InstaboxError, InstaboxAuthError, InstaboxQuotaError, InstaboxTimeoutError, CommandExitError } from './errors'\nexport type { CommandResult, InstaboxErrorInit } from './errors'\nexport type * from './types'\n","/** Fields of the instabox API error envelope `{ error: { code, message, requestId, retryable, operationId } }`. */\nexport interface InstaboxErrorInit {\n status?: number\n code?: string\n requestId?: string\n retryable?: boolean\n operationId?: string | null\n cause?: unknown\n}\n\n/** Base class for every error this SDK throws. */\nexport class InstaboxError extends Error {\n /** HTTP status, or 0 when the error did not come from an HTTP response (for example a failed operation). */\n readonly status: number\n /** Machine-readable code from the API, e.g. `not_found`, `operation_conflict`. */\n readonly code: string\n readonly requestId?: string\n readonly retryable: boolean\n /** For `operation_conflict` the active operation, for a failed operation its ID. */\n readonly operationId?: string | null\n\n constructor(message: string, init: InstaboxErrorInit = {}) {\n super(message, init.cause === undefined ? undefined : { cause: init.cause })\n this.name = new.target.name\n this.status = init.status ?? 0\n this.code = init.code ?? 'unknown'\n this.requestId = init.requestId\n this.retryable = init.retryable ?? false\n this.operationId = init.operationId\n }\n}\n\n/** 401 / 403: missing, invalid or revoked API key, or not allowed. */\nexport class InstaboxAuthError extends InstaboxError {}\n\n/** 429 `quota_exceeded`: an account limit was reached (for example the machine limit). */\nexport class InstaboxQuotaError extends InstaboxError {}\n\n/** A request or an operation did not finish in time. */\nexport class InstaboxTimeoutError extends InstaboxError {}\n\n/** Result of a finished command. */\nexport interface CommandResult {\n stdout: string\n stderr: string\n exitCode: number\n timedOut: boolean\n truncated: boolean\n /** Error text reported by the server, if any. */\n error?: string\n}\n\n/** A command exited with a non-zero code. Carries the full result. */\nexport class CommandExitError extends InstaboxError implements CommandResult {\n readonly stdout: string\n readonly stderr: string\n readonly exitCode: number\n readonly timedOut: boolean\n readonly truncated: boolean\n readonly error?: string\n\n constructor(result: CommandResult) {\n const tail = result.stderr.trim().split('\\n').slice(-1)[0] ?? ''\n super(`command exited with code ${result.exitCode}${tail ? `: ${tail}` : ''}`, { code: 'command_exit' })\n this.stdout = result.stdout\n this.stderr = result.stderr\n this.exitCode = result.exitCode\n this.timedOut = result.timedOut\n this.truncated = result.truncated\n this.error = result.error\n }\n}\n\n/** Builds the right error class from an HTTP status and the parsed envelope. */\nexport function errorFromResponse(status: number, body: unknown, fallbackMessage: string): InstaboxError {\n const env = (body as { error?: Record<string, unknown> } | null)?.error\n const init: InstaboxErrorInit = {\n status,\n code: typeof env?.code === 'string' ? env.code : `http_${status}`,\n requestId: typeof env?.requestId === 'string' ? env.requestId : undefined,\n retryable: typeof env?.retryable === 'boolean' ? env.retryable : status >= 502 && status <= 504,\n operationId: typeof env?.operationId === 'string' ? env.operationId : null,\n }\n const message = typeof env?.message === 'string' && env.message ? env.message : fallbackMessage\n if (status === 401 || status === 403) return new InstaboxAuthError(message, init)\n if (status === 429) return new InstaboxQuotaError(message, init)\n return new InstaboxError(message, init)\n}\n","export const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/** Random UUID v4. Uses Web Crypto when present (Node 19+, Bun, Deno, browsers). */\nexport function uuid(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (c && typeof c.randomUUID === 'function') return c.randomUUID()\n const b = new Uint8Array(16)\n if (c && typeof c.getRandomValues === 'function') c.getRandomValues(b)\n else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256)\n b[6] = (b[6]! & 0x0f) | 0x40\n b[8] = (b[8]! & 0x3f) | 0x80\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`\n}\n\nexport function randomSuffix(len = 8): string {\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n return Array.from({ length: len }, () => alphabet[Math.floor(Math.random() * alphabet.length)]).join('')\n}\n\n/** Quotes a string for POSIX sh. */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let bin = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(bin)\n}\n\nexport function base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64.replace(/\\s+/g, ''))\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\nexport function readEnv(name: string): string | undefined {\n const g = globalThis as {\n process?: { env?: Record<string, string | undefined> }\n Deno?: { env?: { get(k: string): string | undefined } }\n }\n try {\n const v = g.process?.env?.[name] ?? g.Deno?.env?.get(name)\n return v === '' ? undefined : v\n } catch {\n return undefined // Deno without --allow-env\n }\n}\n","import { CommandExitError, InstaboxError, type CommandResult } from './errors'\nimport type { HttpClient } from './http'\nimport type { ExecResponse } from './types'\nimport { shellQuote } from './util'\n\nexport interface CommandOptions {\n /** Working directory. Default: the server's default (HOME, `/data/home`). */\n cwd?: string\n /** Extra environment variables, merged over the sandbox-level `envs` from `Sandbox.create`. */\n envs?: Record<string, string>\n /** Command timeout in ms (sent as whole seconds). Default: the server's default. */\n timeoutMs?: number\n /** Text sent to the command's standard input. */\n stdin?: string\n /**\n * Called with stdout once the command finished. Output is not streamed yet:\n * the callback receives the whole stdout in one call.\n */\n onStdout?: (data: string) => void | Promise<void>\n /** Like `onStdout`, for stderr. */\n onStderr?: (data: string) => void | Promise<void>\n /** Start the command detached (nohup) and return right away with its PID. */\n background?: boolean\n}\n\n/** A command started with `background: true`. */\nexport interface CommandHandle {\n pid: number\n /** Sends SIGTERM to the process. Returns false if it had already exited. */\n kill(): Promise<boolean>\n}\n\nexport class Commands {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly sandboxId: string,\n private readonly defaultEnvs: Record<string, string>,\n ) {}\n\n /**\n * Runs a shell command in the sandbox and waits for it to finish.\n * Throws `CommandExitError` (carrying stdout, stderr and exitCode) when it exits non-zero.\n */\n run(cmd: string, opts: CommandOptions & { background: true }): Promise<CommandHandle>\n run(cmd: string, opts?: CommandOptions & { background?: false }): Promise<CommandResult>\n run(cmd: string, opts?: CommandOptions): Promise<CommandResult | CommandHandle>\n async run(cmd: string, opts: CommandOptions = {}): Promise<CommandResult | CommandHandle> {\n if (opts.background) {\n const wrapped = `nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`\n if (opts.stdin !== undefined)\n throw new InstaboxError('stdin is not supported for background commands', { code: 'bad_request' })\n const r = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs })\n if (r.exitCode !== 0) throw new CommandExitError(r)\n const pid = Number.parseInt(r.stdout.trim(), 10)\n if (!Number.isSafeInteger(pid) || pid <= 0)\n throw new InstaboxError('exec returned an invalid background PID', { code: 'invalid_response' })\n return {\n pid,\n kill: async () => (await this.exec(`kill ${pid}`)).exitCode === 0,\n }\n }\n const r = await this.exec(cmd, opts)\n if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout)\n if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n return r\n }\n\n /** @internal Raw exec: never throws on a non-zero exit code. */\n async exec(\n cmd: string,\n opts: Pick<CommandOptions, 'cwd' | 'envs' | 'timeoutMs' | 'stdin'> = {},\n ): Promise<CommandResult> {\n const envs = { ...this.defaultEnvs, ...opts.envs }\n const body: Record<string, unknown> = { cmd }\n if (opts.cwd !== undefined) body.cwd = opts.cwd\n if (Object.keys(envs).length) body.envs = envs\n if (opts.stdin !== undefined) body.stdin = opts.stdin\n if (opts.timeoutMs !== undefined) {\n if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 600_000) {\n throw new InstaboxError('command timeoutMs must be greater than 0 and at most 600 000', { code: 'bad_request' })\n }\n body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1000)\n }\n // Exec has no idempotency contract; a retry can run the command twice.\n const res = await this.http.request<ExecResponse>(\n 'POST',\n `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`,\n {\n body,\n retry: false,\n idempotent: false,\n timeoutMs: (Number(body.timeoutSeconds) || 60) * 1000 + 30_000,\n },\n )\n const out: CommandResult = {\n stdout: res.stdout,\n stderr: res.stderr,\n exitCode: res.exitCode,\n timedOut: res.timedOut,\n truncated: res.truncated,\n }\n if (res.error) out.error = res.error\n return out\n }\n}\n","import type { Commands } from './commands'\nimport { CommandExitError, InstaboxError, type CommandResult } from './errors'\nimport { base64ToBytes, bytesToBase64, shellQuote } from './util'\n\n/** Largest file `files.read` / `files.write` move (files go through exec as base64). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024\n// Base64 payload plus shell quoting must fit the API's 64 KiB command limit.\nconst WRITE_CHUNK_B64 = 48 * 1024\n// Encoded chunks must fit the API's 1 MiB stdout limit.\nconst READ_CHUNK_BYTES = 512 * 1024\n\nexport interface EntryInfo {\n name: string\n path: string\n type: 'file' | 'dir'\n}\n\nexport interface WriteInfo {\n path: string\n}\n\n/**\n * File access inside the sandbox. Implemented on top of exec (base64 over the command\n * channel), capped at 10 MiB per file.\n */\nexport class Files {\n /** @internal */\n constructor(private readonly commands: Commands) {}\n\n /** Reads a file. Returns text (UTF-8) by default, or bytes with `{ format: 'bytes' }`. */\n read(path: string, opts?: { format?: 'text' }): Promise<string>\n read(path: string, opts: { format: 'bytes' }): Promise<Uint8Array>\n async read(path: string, opts: { format?: 'text' | 'bytes' } = {}): Promise<string | Uint8Array> {\n const p = shellQuote(path)\n const r = await this.commands.exec(\n `[ -f ${p} ] || { echo \"no such file: \"${p} >&2; exit 3; }; ` +\n `s=$(wc -c < ${p}) || exit 1; [ \"$s\" -le ${MAX_FILE_BYTES} ] || { echo \"file too large: $s bytes\" >&2; exit 4; }; ` +\n `printf '%s' \"$s\"`,\n )\n if (r.exitCode === 3) throw new InstaboxError(`file not found: ${path}`, { status: 404, code: 'not_found' })\n if (r.exitCode === 4) {\n throw new InstaboxError(`${path} is larger than the ${MAX_FILE_BYTES}-byte limit of files.read`, {\n code: 'file_too_large',\n })\n }\n ensureComplete(r)\n const size = Number(r.stdout.trim())\n if (!Number.isSafeInteger(size) || size < 0 || size > MAX_FILE_BYTES) {\n throw new InstaboxError('invalid file size returned by exec', { code: 'invalid_response' })\n }\n const bytes = new Uint8Array(size)\n for (let offset = 0; offset < size; offset += READ_CHUNK_BYTES) {\n const chunk = await this.commands.exec(\n `dd if=${p} bs=${READ_CHUNK_BYTES} skip=${offset / READ_CHUNK_BYTES} count=1 2>/dev/null | base64 | tr -d '\\\\n'`,\n )\n ensureComplete(chunk)\n const data = base64ToBytes(chunk.stdout)\n if (data.length !== Math.min(READ_CHUNK_BYTES, size - offset)) {\n throw new InstaboxError(`file size changed while reading: ${path}`, { code: 'file_changed' })\n }\n bytes.set(data, offset)\n }\n return opts.format === 'bytes' ? bytes : new TextDecoder().decode(bytes)\n }\n\n /** Writes a file, creating parent directories. Replaces the file atomically (temp file + rename). */\n async write(path: string, data: string | Uint8Array): Promise<WriteInfo> {\n const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data\n if (bytes.length > MAX_FILE_BYTES) {\n throw new InstaboxError(`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write`, {\n code: 'file_too_large',\n })\n }\n const p = shellQuote(path)\n const tmp = shellQuote(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`)\n const b64 = bytesToBase64(bytes)\n const chunks: string[] = []\n for (let i = 0; i < b64.length; i += WRITE_CHUNK_B64) chunks.push(b64.slice(i, i + WRITE_CHUNK_B64))\n if (chunks.length === 0) chunks.push('')\n try {\n for (let i = 0; i < chunks.length; i++) {\n const redirect = i === 0 ? '>' : '>>'\n const prefix = i === 0 ? `mkdir -p \"$(dirname ${p})\" && ` : ''\n const r = await this.commands.exec(`${prefix}printf '%s' '${chunks[i]}' | base64 -d ${redirect} ${tmp}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n }\n const r = await this.commands.exec(`mv -f ${tmp} ${p}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n } catch (err) {\n await this.commands.exec(`rm -f ${tmp}`).catch(() => {})\n throw err\n }\n return { path }\n }\n\n /** Lists the entries of a directory (not recursive). */\n async list(path: string): Promise<EntryInfo[]> {\n const p = shellQuote(path)\n const r = await this.commands.exec(\n `[ -d ${p} ] || { echo \"no such directory: \"${p} >&2; exit 3; }; ` +\n `cd ${p} && for f in .* *; do case \"$f\" in .|..) continue ;; esac; [ -e \"$f\" ] || [ -L \"$f\" ] || continue; ` +\n `if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\0' \"$f\"; else printf 'f\\\\t%s\\\\0' \"$f\"; fi; done`,\n )\n if (r.exitCode === 3) throw new InstaboxError(`directory not found: ${path}`, { status: 404, code: 'not_found' })\n ensureComplete(r)\n const base = path.endsWith('/') ? path.slice(0, -1) : path\n return r.stdout\n .split('\\0')\n .filter(Boolean)\n .map((line) => {\n const tab = line.indexOf('\\t')\n const name = line.slice(tab + 1)\n return { name, path: `${base}/${name}`, type: line.slice(0, tab) === 'd' ? 'dir' : 'file' } as EntryInfo\n })\n }\n\n /** Removes a file or a directory (recursively). Missing paths are fine. */\n async remove(path: string): Promise<void> {\n const r = await this.commands.exec(`rm -rf -- ${shellQuote(path)}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n }\n\n /** True if a file or directory exists at `path`. */\n async exists(path: string): Promise<boolean> {\n const r = await this.commands.exec(`test -e ${shellQuote(path)}`)\n return r.exitCode === 0\n }\n}\n\nfunction ensureComplete(result: CommandResult): void {\n if (result.exitCode !== 0) throw new CommandExitError(result)\n if (result.truncated) throw new InstaboxError('file command output was truncated', { code: 'output_truncated' })\n}\n","import { InstaboxError, InstaboxTimeoutError, errorFromResponse } from './errors'\nimport type { Operation } from './types'\nimport { readEnv, sleep, uuid } from './util'\n\nexport const DEFAULT_API_URL = 'https://api.box.instacloud.com'\n\n/** Options shared by every call that talks to the API. */\nexport interface ConnectionOptions {\n /** API key from the instabox dashboard's API Keys page. Default: env `INSTABOX_API_KEY`. */\n apiKey?: string\n /** API base URL. Default: env `INSTABOX_API_URL`, else `https://api.box.instacloud.com`. */\n apiUrl?: string\n /** Timeout of a single HTTP request in ms. Default 60 000; exec defaults to its command timeout plus 30 000. */\n requestTimeoutMs?: number\n /** Max time to wait for a lifecycle operation (create, pause, resume, fork, kill) in ms. Default 600 000. */\n operationTimeoutMs?: number\n /** Custom fetch implementation (tests, proxies). Default: global `fetch`. */\n fetch?: typeof fetch\n /** Advanced: first delay of operation polling in ms (grows 1.5x to 1 s). Default 250. */\n pollIntervalMs?: number\n /** Advanced: first delay between retries in ms. Default 250. */\n retryDelayMs?: number\n}\n\ninterface RequestOptions {\n timeoutMs?: number\n body?: unknown\n query?: Record<string, string | number | string[] | undefined>\n /** Retry on 502/503/504 and network errors. Default: true for GET and for requests carrying an Idempotency-Key. */\n retry?: boolean\n /** Send an Idempotency-Key. Default: true for every method other than GET/HEAD. */\n idempotent?: boolean\n}\n\nconst MAX_RETRIES = 3\n\nexport class HttpClient {\n readonly apiUrl: string\n readonly operationTimeoutMs: number\n private readonly apiKey: string\n private readonly requestTimeoutMs?: number\n private readonly fetchImpl: typeof fetch\n private readonly pollIntervalMs: number\n private readonly retryDelayMs: number\n\n constructor(opts: ConnectionOptions = {}) {\n const apiKey = opts.apiKey ?? readEnv('INSTABOX_API_KEY')\n if (!apiKey) {\n throw new InstaboxError(\n 'No instabox API key. Set the INSTABOX_API_KEY environment variable or pass { apiKey } (create one on the API Keys page of the instabox dashboard).',\n { code: 'missing_api_key' },\n )\n }\n this.apiKey = apiKey\n this.apiUrl = (opts.apiUrl ?? readEnv('INSTABOX_API_URL') ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n this.requestTimeoutMs = opts.requestTimeoutMs\n this.operationTimeoutMs = opts.operationTimeoutMs ?? 600_000\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\n if (!f) throw new InstaboxError('No global fetch found; use Node 18+ or pass { fetch }.', { code: 'no_fetch' })\n this.fetchImpl = f\n this.pollIntervalMs = opts.pollIntervalMs ?? 250\n this.retryDelayMs = opts.retryDelayMs ?? 250\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await this.send(method, path, opts)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n /** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */\n async send(method: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n const isRead = method === 'GET' || method === 'HEAD'\n const idempotent = opts.idempotent ?? !isRead\n const retry = opts.retry ?? (isRead || idempotent)\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey,\n Accept: 'application/json',\n }\n // One key per intended action, reused by every retry so the server dedupes them.\n if (idempotent) headers['Idempotency-Key'] = uuid()\n let body: string | undefined\n if (opts.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(opts.body)\n }\n let url = this.apiUrl + path\n if (opts.query) {\n const q = new URLSearchParams()\n for (const [k, v] of Object.entries(opts.query)) {\n if (Array.isArray(v)) for (const item of v) q.append(k, item)\n else if (v !== undefined) q.set(k, String(v))\n }\n const s = q.toString()\n if (s) url += `?${s}`\n }\n\n for (let attempt = 0; ; attempt++) {\n const canRetry = retry && attempt < MAX_RETRIES\n const ctrl = new AbortController()\n let timedOut = false\n const timeoutMs = this.requestTimeoutMs ?? opts.timeoutMs ?? 60_000\n const timer = setTimeout(() => {\n timedOut = true\n ctrl.abort()\n }, timeoutMs)\n let res: Response\n try {\n res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal })\n } catch (err) {\n clearTimeout(timer)\n if (canRetry) {\n await sleep(this.backoff(attempt))\n continue\n }\n if (timedOut) {\n throw new InstaboxTimeoutError(`${method} ${path} timed out after ${timeoutMs} ms`, {\n code: 'request_timeout',\n cause: err,\n })\n }\n throw new InstaboxError(`${method} ${path} failed: ${(err as Error)?.message ?? String(err)}`, {\n code: 'network_error',\n retryable: true,\n cause: err,\n })\n }\n clearTimeout(timer)\n if (res.ok) return res\n if (canRetry && res.status >= 502 && res.status <= 504) {\n void res.body?.cancel().catch(() => {})\n await sleep(this.backoff(attempt))\n continue\n }\n const text = await res.text().catch(() => '')\n let parsed: unknown = null\n try {\n parsed = text ? JSON.parse(text) : null\n } catch {\n parsed = null\n }\n throw errorFromResponse(res.status, parsed, `${method} ${path} returned ${res.status}`)\n }\n }\n\n private backoff(attempt: number): number {\n return this.retryDelayMs * 2 ** attempt\n }\n\n /** Polls an operation until it is `succeeded` (returns it) or `failed` (throws). */\n async waitForOperation(op: Operation, timeoutMs = this.operationTimeoutMs): Promise<Operation> {\n const deadline = Date.now() + timeoutMs\n let delay = this.pollIntervalMs\n let cur = op\n while (cur.state !== 'succeeded') {\n if (cur.state === 'failed') {\n const e = cur.error\n throw new InstaboxError(e?.message || `operation ${cur.id} (${cur.type}) failed`, {\n code: e?.code ?? 'operation_failed',\n requestId: e?.requestId,\n retryable: e?.retryable ?? false,\n operationId: cur.id,\n })\n }\n if (Date.now() + delay > deadline) {\n throw new InstaboxTimeoutError(\n `operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ''})`,\n { code: 'operation_timeout', operationId: cur.id },\n )\n }\n await sleep(delay)\n delay = Math.min(Math.round(delay * 1.5), Math.max(1_000, this.pollIntervalMs))\n cur = await this.request<Operation>('GET', `/v1/operations/${encodeURIComponent(cur.id)}`)\n }\n return cur\n }\n}\n","import { Commands } from './commands'\nimport { InstaboxError } from './errors'\nimport { Files } from './files'\nimport { type ConnectionOptions, HttpClient } from './http'\nimport type {\n Connection,\n Machine,\n MachineList,\n MachineState,\n OnTimeout,\n Operation,\n Snapshot,\n SnapshotList,\n Template,\n} from './types'\nimport { randomSuffix } from './util'\n\nexport const DEFAULT_TEMPLATE = 'universal'\n\nexport interface SandboxOpts extends ConnectionOptions {\n /** Machine name. Default `sbx-<random>`. */\n name?: string\n /** String labels stored with the sandbox; filter on them with `Sandbox.list({ metadata })`. */\n metadata?: Record<string, string>\n /** Environment variables applied to every `commands.run` of this Sandbox object (client-side). */\n envs?: Record<string, string>\n /**\n * The server pauses (or with `onTimeout: 'kill'` deletes) the sandbox this long after creation.\n * Sent as whole seconds, 60 s to 24 h. Default: no timeout. Change it with `setTimeout()`.\n */\n timeoutMs?: number\n /** What happens at the timeout: `pause` (default) or `kill`. */\n onTimeout?: OnTimeout\n /** Stop and archive after this many milliseconds, independent of the pause/kill timeout. */\n archiveMs?: number\n /** vCPUs. Default: the template's. */\n vcpus?: number\n /** Memory in MiB. Default: the template's. */\n memMiB?: number\n /** Size of the persistent `/data` disk in GiB. Default: the template's. */\n diskGiB?: number\n /** Root disk size in GiB; may only grow. */\n rootDiskGiB?: number\n}\n\nexport interface SandboxConnectOpts extends ConnectionOptions {\n /** Resume the sandbox if it is paused (suspended) or stopped. Default true. */\n resume?: boolean\n envs?: Record<string, string>\n}\n\nexport interface SandboxListOpts extends ConnectionOptions {\n /** Only sandboxes whose metadata has every one of these key/value pairs. */\n metadata?: Record<string, string>\n}\n\nexport interface SandboxInfo {\n sandboxId: string\n /** Template the sandbox runs (`template.id`). */\n templateId: string\n /** Snapshot the sandbox was created from, if any. */\n snapshotId?: string\n name: string\n /** String labels stored with the sandbox. */\n metadata: Record<string, string>\n /** Creation time of the machine. */\n startedAt: Date\n /** When the server pauses or kills the sandbox (see `onTimeout`); undefined for no timeout. */\n endAt?: Date\n archiveAt?: Date\n onTimeout: OnTimeout\n state: MachineState\n /** The raw machine object from the API. */\n machine: Machine\n}\n\nexport interface ForkOpts {\n /** Name of the new sandbox. Default `<name>-fork-<random>`. */\n name?: string\n vcpus?: number\n memMiB?: number\n /** May only grow. */\n diskGiB?: number\n /** Root disk size in GiB; may only grow. */\n rootDiskGiB?: number\n /** Timeout of the copy, as in `SandboxOpts.timeoutMs`. Default: none (the source's is not copied). */\n timeoutMs?: number\n onTimeout?: OnTimeout\n /** Metadata of the copy. Default: the source's; `{}` for none. */\n metadata?: Record<string, string>\n /**\n * A fork needs a stopped source. When true (default), `fork()` stops the source first if needed\n * (running processes end, `/data` is kept) and leaves it stopped; call `resume()` to start it again.\n * When false, a source that is not stopped makes the call fail.\n */\n stopSource?: boolean\n}\n\nexport interface CreateSnapshotOpts {\n name: string\n description?: string\n /** Save only the root disk; omit the persistent /data disk. */\n rootOnly?: boolean\n}\n\nexport interface SshCredentials {\n host: string\n port: number\n /** The machine ID. */\n username: string\n /** OpenSSH user certificate for `publicKey`, in authorized_keys format. Save it as `<key>-cert.pub`. */\n certificate: string\n /** Line for known_hosts that trusts the instabox gateway: `@cert-authority [host]:port <ca key>`. */\n knownHostsLine: string\n expiresAt: Date\n connectionId: string\n}\n\nfunction toInfo(m: Machine): SandboxInfo {\n const info: SandboxInfo = {\n sandboxId: m.id,\n templateId: m.template?.id,\n name: m.name,\n metadata: { ...m.metadata },\n startedAt: new Date(m.createdAt),\n onTimeout: m.onTimeout ?? 'pause',\n state: m.state,\n machine: m,\n }\n if (m.snapshot?.id) info.snapshotId = m.snapshot.id\n if (m.timeoutAt) info.endAt = new Date(m.timeoutAt)\n if (m.archiveAt) info.archiveAt = new Date(m.archiveAt)\n return info\n}\n\n/** Milliseconds to the API's whole seconds (rounded up), checked against the server's 60 s to 24 h range. */\nfunction toSeconds(ms: number, field = 'timeoutMs'): number {\n const s = Math.ceil(ms / 1000)\n if (!Number.isFinite(ms) || s < 60 || s > 86_400) {\n throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {\n code: 'bad_request',\n })\n }\n return s\n}\n\n/** Metadata keys the server accepts; checked before a list filter, where a bad key would silently match nothing. */\nconst METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/\n\nconst enc = encodeURIComponent\n\n/** A instabox dev machine. Create one with `Sandbox.create()` or attach with `Sandbox.connect(id)`. */\nexport class Sandbox {\n /** The machine ID (`m_...`). */\n readonly sandboxId: string\n /** Run shell commands. Needs a instabox server with the exec endpoint. */\n readonly commands: Commands\n /** Read and write files. Needs a instabox server with the exec endpoint. */\n readonly files: Files\n private machine: Machine\n\n private constructor(\n private readonly http: HttpClient,\n machine: Machine,\n opts: { envs?: Record<string, string> } = {},\n ) {\n this.sandboxId = machine.id\n this.machine = machine\n this.commands = new Commands(http, machine.id, { ...opts.envs })\n this.files = new Files(this.commands)\n }\n\n /**\n * Creates a sandbox and waits until it is running.\n * `template` is a template ID, a private snapshot name or a snapshot ID (`sn_...`).\n * Template IDs take precedence over snapshot names. Default template: `universal`.\n */\n static async create(opts?: SandboxOpts): Promise<Sandbox>\n static async create(template: string, opts?: SandboxOpts): Promise<Sandbox>\n static async create(a?: string | SandboxOpts, b?: SandboxOpts): Promise<Sandbox> {\n const template = typeof a === 'string' ? a : DEFAULT_TEMPLATE\n const opts = (typeof a === 'string' ? b : a) ?? {}\n const http = new HttpClient(opts)\n const body: Record<string, unknown> = { name: opts.name ?? `sbx-${randomSuffix()}` }\n if (opts.timeoutMs !== undefined) body.timeoutSeconds = toSeconds(opts.timeoutMs)\n if (opts.archiveMs !== undefined) body.archiveSeconds = toSeconds(opts.archiveMs, 'archiveMs')\n Object.assign(body, await resolveSource(http, template))\n if (opts.vcpus !== undefined) body.vcpus = opts.vcpus\n if (opts.memMiB !== undefined) body.memMiB = opts.memMiB\n if (opts.diskGiB !== undefined) body.persistentDiskGiB = opts.diskGiB\n if (opts.rootDiskGiB !== undefined) body.rootDiskGiB = opts.rootDiskGiB\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n if (opts.metadata) body.metadata = opts.metadata\n const op = await http.request<Operation>('POST', '/v1/machines', { body })\n const done = await http.waitForOperation(op)\n const machine = await getMachine(http, done.machineId)\n return new Sandbox(http, machine, opts)\n }\n\n /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */\n static async connect(sandboxId: string, opts: SandboxConnectOpts = {}): Promise<Sandbox> {\n const http = new HttpClient(opts)\n const sbx = new Sandbox(http, await getMachine(http, sandboxId), opts)\n await sbx.settle(false)\n if (opts.resume !== false) await sbx.wake()\n return sbx\n }\n\n /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */\n static async list(opts: SandboxListOpts = {}): Promise<SandboxInfo[]> {\n const http = new HttpClient(opts)\n const metadata = Object.entries(opts.metadata ?? {}).map(([k, v]) => {\n if (!METADATA_KEY.test(k))\n throw new InstaboxError(`invalid metadata key ${JSON.stringify(k)}: use 1-64 of [A-Za-z0-9_.-]`, {\n code: 'bad_request',\n })\n return `${k}:${v}`\n })\n const out: SandboxInfo[] = []\n let cursor: string | undefined\n do {\n const page = await http.request<MachineList>('GET', '/v1/machines', { query: { cursor, limit: 100, metadata } })\n out.push(...page.machines.map((m) => toInfo(m)))\n cursor = page.nextCursor ?? undefined\n } while (cursor)\n return out\n }\n\n /** Deletes a sandbox and its disks. Returns false if it did not exist. */\n static async kill(sandboxId: string, opts: ConnectionOptions = {}): Promise<boolean> {\n return killMachine(new HttpClient(opts), sandboxId)\n }\n\n /** Lists the caller's private snapshots. Requires images:read. */\n static async listSnapshots(opts: ConnectionOptions = {}): Promise<Snapshot[]> {\n const result = await new HttpClient(opts).request<SnapshotList>('GET', '/v1/snapshots')\n return result.snapshots\n }\n\n /** Fetches a snapshot by ID. Requires images:read. */\n static async getSnapshot(snapshotId: string, opts: ConnectionOptions = {}): Promise<Snapshot> {\n return new HttpClient(opts).request<Snapshot>('GET', `/v1/snapshots/${enc(snapshotId)}`)\n }\n\n /** Deletes a snapshot. Returns false if absent. Requires images:delete. */\n static async deleteSnapshot(snapshotId: string, opts: ConnectionOptions = {}): Promise<boolean> {\n try {\n await new HttpClient(opts).request<void>('DELETE', `/v1/snapshots/${enc(snapshotId)}`)\n return true\n } catch (err) {\n if (err instanceof InstaboxError && err.status === 404 && err.code === 'not_found') return false\n throw err\n }\n }\n\n /** Saves a stopped sandbox's disks as a private snapshot. Requires images:write. */\n async createSnapshot(opts: CreateSnapshotOpts): Promise<Snapshot> {\n return this.http.request<Snapshot>('POST', `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts })\n }\n\n /** Fetches the current state of the sandbox. */\n async getInfo(): Promise<SandboxInfo> {\n this.machine = await getMachine(this.http, this.sandboxId)\n return toInfo(this.machine)\n }\n\n /**\n * Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.\n * `onTimeout` changes what happens then (`pause` or `kill`).\n */\n async setTimeout(timeoutMs: number, opts: { onTimeout?: OnTimeout } = {}): Promise<void> {\n const body: Record<string, unknown> = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) }\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, { body })\n }\n\n /** Replaces the sandbox's metadata (`{}` clears it). */\n async setMetadata(metadata: Record<string, string>): Promise<void> {\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, {\n body: { metadata },\n })\n }\n\n /** True if the sandbox is running (fetches fresh state). */\n async isRunning(): Promise<boolean> {\n return (await this.getInfo()).state === 'running'\n }\n\n /** Snapshots memory and stops the sandbox (suspend). `resume()` or `Sandbox.connect()` brings it back. */\n async pause(): Promise<void> {\n await this.mutate('POST', 'suspend')\n }\n\n /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */\n async resume(): Promise<void> {\n await this.settle()\n await this.wake()\n }\n\n /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */\n private async wake(): Promise<void> {\n if (this.machine.state === 'suspended') await this.mutate('POST', 'resume')\n else if (this.machine.state === 'stopped') await this.mutate('POST', 'start')\n }\n\n /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */\n async stop(): Promise<void> {\n await this.settle()\n if (this.machine.state === 'suspended') await this.mutate('POST', 'start')\n await this.mutate('POST', 'stop')\n }\n\n /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */\n async fork(opts: ForkOpts = {}): Promise<Sandbox> {\n if (opts.timeoutMs !== undefined) toSeconds(opts.timeoutMs)\n await this.settle()\n if (this.machine.state !== 'stopped') {\n if (opts.stopSource === false) {\n throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {\n code: 'operation_conflict',\n })\n }\n await this.stop()\n }\n const body: Record<string, unknown> = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` }\n if (opts.vcpus !== undefined) body.vcpus = opts.vcpus\n if (opts.memMiB !== undefined) body.memMiB = opts.memMiB\n if (opts.diskGiB !== undefined) body.persistentDiskGiB = opts.diskGiB\n if (opts.rootDiskGiB !== undefined) body.rootDiskGiB = opts.rootDiskGiB\n if (opts.timeoutMs !== undefined) body.timeoutSeconds = toSeconds(opts.timeoutMs)\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n if (opts.metadata) body.metadata = opts.metadata\n const op = await this.http.request<Operation>('POST', `/v1/machines/${enc(this.sandboxId)}/fork`, { body })\n const done = await this.http.waitForOperation(op)\n return new Sandbox(this.http, await getMachine(this.http, done.machineId))\n }\n\n /** Deletes the sandbox and its disks. Returns false if it was already gone. */\n async kill(): Promise<boolean> {\n return killMachine(this.http, this.sandboxId)\n }\n\n /**\n * Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).\n * Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding\n * `knownHostsLine` to known_hosts. The sandbox must be running.\n */\n async sshCredentials(publicKey: string, opts: { ttlSeconds?: number } = {}): Promise<SshCredentials> {\n const body: Record<string, unknown> = { publicKey: publicKey.trim() }\n if (opts.ttlSeconds) body.ttlSeconds = opts.ttlSeconds\n const c = await this.http.request<Connection>('POST', `/v1/machines/${enc(this.sandboxId)}/connections`, { body })\n return {\n host: c.host,\n port: c.port,\n username: c.username,\n certificate: c.certificate,\n knownHostsLine: `@cert-authority [${c.host}]:${c.port} ${c.hostTrust.publicKey}`,\n expiresAt: new Date(c.expiresAt),\n connectionId: c.id,\n }\n }\n\n /**\n * Re-reads the machine from the server (other handles or the dashboard may have changed it),\n * waits for its active operation if one is running, and leaves the fresh state cached.\n * Every state-dependent method calls this first, so it never decides from a stale cache.\n */\n private async settle(refresh = true): Promise<void> {\n if (refresh) this.machine = await getMachine(this.http, this.sandboxId)\n if (this.machine.operationId) {\n const op = await this.http.request<Operation>('GET', `/v1/operations/${enc(this.machine.operationId)}`)\n await this.http.waitForOperation(op).catch(() => {})\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n }\n\n private async mutate(method: string, action: string): Promise<void> {\n const op = await this.http.request<Operation>(method, `/v1/machines/${enc(this.sandboxId)}/${action}`)\n await this.http.waitForOperation(op)\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n}\n\nasync function getMachine(http: HttpClient, id: string): Promise<Machine> {\n return http.request<Machine>('GET', `/v1/machines/${enc(id)}`)\n}\n\nasync function killMachine(http: HttpClient, id: string): Promise<boolean> {\n try {\n const op = await http.request<Operation>('DELETE', `/v1/machines/${enc(id)}`)\n await http.waitForOperation(op)\n return true\n } catch (err) {\n if (err instanceof InstaboxError && err.status === 404 && err.code === 'not_found') return false\n throw err\n }\n}\n\nasync function resolveSource(http: HttpClient, ref: string): Promise<{ templateId: string } | { snapshotId: string }> {\n if (/^sn_[a-z2-7]{26}$/.test(ref)) return { snapshotId: ref }\n const { templates } = await http.request<{ templates: Template[] }>('GET', '/v1/templates')\n if (templates.some((template) => template.id === ref)) return { templateId: ref }\n const { snapshots } = await http.request<SnapshotList>('GET', '/v1/snapshots')\n const matches = snapshots.filter((snapshot) => snapshot.name === ref)\n if (matches.length > 1) {\n throw new InstaboxError(`multiple snapshots named ${ref}; use a snapshot ID`, { code: 'ambiguous_snapshot' })\n }\n if (matches[0]) return { snapshotId: matches[0].id }\n throw new InstaboxError(`template or snapshot not found: ${ref}`, { status: 404, code: 'not_found' })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,gBAAN,cAA4B,MAAM;AAAA;AAAA,EAE9B;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,OAA0B,CAAC,GAAG;AACzD,UAAM,SAAS,KAAK,UAAU,SAAY,SAAY,EAAE,OAAO,KAAK,MAAM,CAAC;AAC3E,SAAK,OAAO,WAAW;AACvB,SAAK,SAAS,KAAK,UAAU;AAC7B,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,YAAY,KAAK;AACtB,SAAK,YAAY,KAAK,aAAa;AACnC,SAAK,cAAc,KAAK;AAAA,EAC1B;AACF;AAGO,IAAM,o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,SAAS,GAAG;AACpE,MAAI,QAAQ,SAAS,GAAG;AACtB,UAAM,IAAI,cAAc,4BAA4B,GAAG,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAAA,EAC9G;AACA,MAAI,QAAQ,CAAC,EAAG,QAAO,EAAE,YAAY,QAAQ,CAAC,EAAE,GAAG;AACnD,QAAM,IAAI,cAAc,mCAAmC,GAAG,IAAI,EAAE,QAAQ,KAAK,MAAM,YAAY,CAAC;AACtG;","names":["r","r"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
/** Fields of the instabox API error envelope `{ error: { code, message, requestId, retryable, operationId } }`. */
|
|
2
|
+
interface InstaboxErrorInit {
|
|
3
|
+
status?: number;
|
|
4
|
+
code?: string;
|
|
5
|
+
requestId?: string;
|
|
6
|
+
retryable?: boolean;
|
|
7
|
+
operationId?: string | null;
|
|
8
|
+
cause?: unknown;
|
|
9
|
+
}
|
|
10
|
+
/** Base class for every error this SDK throws. */
|
|
11
|
+
declare class InstaboxError extends Error {
|
|
12
|
+
/** HTTP status, or 0 when the error did not come from an HTTP response (for example a failed operation). */
|
|
13
|
+
readonly status: number;
|
|
14
|
+
/** Machine-readable code from the API, e.g. `not_found`, `operation_conflict`. */
|
|
15
|
+
readonly code: string;
|
|
16
|
+
readonly requestId?: string;
|
|
17
|
+
readonly retryable: boolean;
|
|
18
|
+
/** For `operation_conflict` the active operation, for a failed operation its ID. */
|
|
19
|
+
readonly operationId?: string | null;
|
|
20
|
+
constructor(message: string, init?: InstaboxErrorInit);
|
|
21
|
+
}
|
|
22
|
+
/** 401 / 403: missing, invalid or revoked API key, or not allowed. */
|
|
23
|
+
declare class InstaboxAuthError extends InstaboxError {
|
|
24
|
+
}
|
|
25
|
+
/** 429 `quota_exceeded`: an account limit was reached (for example the machine limit). */
|
|
26
|
+
declare class InstaboxQuotaError extends InstaboxError {
|
|
27
|
+
}
|
|
28
|
+
/** A request or an operation did not finish in time. */
|
|
29
|
+
declare class InstaboxTimeoutError extends InstaboxError {
|
|
30
|
+
}
|
|
31
|
+
/** Result of a finished command. */
|
|
32
|
+
interface CommandResult {
|
|
33
|
+
stdout: string;
|
|
34
|
+
stderr: string;
|
|
35
|
+
exitCode: number;
|
|
36
|
+
timedOut: boolean;
|
|
37
|
+
truncated: boolean;
|
|
38
|
+
/** Error text reported by the server, if any. */
|
|
39
|
+
error?: string;
|
|
40
|
+
}
|
|
41
|
+
/** A command exited with a non-zero code. Carries the full result. */
|
|
42
|
+
declare class CommandExitError extends InstaboxError implements CommandResult {
|
|
43
|
+
readonly stdout: string;
|
|
44
|
+
readonly stderr: string;
|
|
45
|
+
readonly exitCode: number;
|
|
46
|
+
readonly timedOut: boolean;
|
|
47
|
+
readonly truncated: boolean;
|
|
48
|
+
readonly error?: string;
|
|
49
|
+
constructor(result: CommandResult);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type MachineState = 'creating' | 'starting' | 'running' | 'stopping' | 'stopped' | 'suspending' | 'suspended' | 'resuming' | 'deleting' | 'deleted' | 'error';
|
|
53
|
+
interface ApiError {
|
|
54
|
+
code: string;
|
|
55
|
+
message: string;
|
|
56
|
+
requestId: string;
|
|
57
|
+
retryable: boolean;
|
|
58
|
+
operationId: string | null;
|
|
59
|
+
}
|
|
60
|
+
interface MachineSpec {
|
|
61
|
+
vcpus: number;
|
|
62
|
+
memMiB: number;
|
|
63
|
+
persistentDiskGiB: number;
|
|
64
|
+
rootDiskGiB?: number;
|
|
65
|
+
}
|
|
66
|
+
interface TemplateRef {
|
|
67
|
+
id: string;
|
|
68
|
+
version: string;
|
|
69
|
+
digest: string;
|
|
70
|
+
}
|
|
71
|
+
interface Machine {
|
|
72
|
+
id: string;
|
|
73
|
+
name: string;
|
|
74
|
+
desiredState: MachineState;
|
|
75
|
+
state: MachineState;
|
|
76
|
+
revision: number;
|
|
77
|
+
operationId: string | null;
|
|
78
|
+
template: TemplateRef;
|
|
79
|
+
snapshot?: {
|
|
80
|
+
id: string;
|
|
81
|
+
};
|
|
82
|
+
forkedFrom?: {
|
|
83
|
+
machineId: string;
|
|
84
|
+
snapshotSeq: number;
|
|
85
|
+
};
|
|
86
|
+
spec: MachineSpec;
|
|
87
|
+
storage: {
|
|
88
|
+
sizeGiB: number;
|
|
89
|
+
mountPath: string;
|
|
90
|
+
persistent: boolean;
|
|
91
|
+
synced: boolean;
|
|
92
|
+
snapshotSeq?: number;
|
|
93
|
+
};
|
|
94
|
+
runtime: {
|
|
95
|
+
ready: boolean;
|
|
96
|
+
processesPreserved?: boolean;
|
|
97
|
+
};
|
|
98
|
+
lastError?: ApiError;
|
|
99
|
+
/** When the server pauses or deletes the machine (see `onTimeout`); null for no timeout. */
|
|
100
|
+
timeoutAt?: string | null;
|
|
101
|
+
archiveAt?: string | null;
|
|
102
|
+
onTimeout?: OnTimeout;
|
|
103
|
+
/** String labels, stored by the server. */
|
|
104
|
+
metadata?: Record<string, string>;
|
|
105
|
+
createdAt: string;
|
|
106
|
+
updatedAt: string;
|
|
107
|
+
}
|
|
108
|
+
/** What happens at `timeoutAt`: `pause` suspends the machine, `kill` deletes it. */
|
|
109
|
+
type OnTimeout = 'pause' | 'kill';
|
|
110
|
+
interface MachineList {
|
|
111
|
+
machines: Machine[];
|
|
112
|
+
nextCursor: string | null;
|
|
113
|
+
}
|
|
114
|
+
interface Operation {
|
|
115
|
+
id: string;
|
|
116
|
+
machineId: string;
|
|
117
|
+
type: 'create' | 'start' | 'stop' | 'suspend' | 'resume' | 'delete' | 'fork';
|
|
118
|
+
state: 'queued' | 'running' | 'succeeded' | 'failed';
|
|
119
|
+
phase?: string;
|
|
120
|
+
error: ApiError | null;
|
|
121
|
+
createdAt: string;
|
|
122
|
+
updatedAt: string;
|
|
123
|
+
machine?: Machine;
|
|
124
|
+
}
|
|
125
|
+
interface Snapshot {
|
|
126
|
+
id: string;
|
|
127
|
+
name: string;
|
|
128
|
+
description?: string;
|
|
129
|
+
sourceMachineId: string;
|
|
130
|
+
sourceSnapshotSeq: number;
|
|
131
|
+
template: TemplateRef;
|
|
132
|
+
rootSizeBytes: number;
|
|
133
|
+
dataSizeBytes?: number;
|
|
134
|
+
exclusiveBytes?: number;
|
|
135
|
+
defaultSpec?: MachineSpec;
|
|
136
|
+
createdAt: string;
|
|
137
|
+
}
|
|
138
|
+
interface Template {
|
|
139
|
+
id: string;
|
|
140
|
+
version: string;
|
|
141
|
+
digest: string;
|
|
142
|
+
arch: string;
|
|
143
|
+
defaultSpec: MachineSpec;
|
|
144
|
+
}
|
|
145
|
+
interface SnapshotList {
|
|
146
|
+
snapshots: Snapshot[];
|
|
147
|
+
}
|
|
148
|
+
interface HostTrust {
|
|
149
|
+
type: 'ca';
|
|
150
|
+
publicKey: string;
|
|
151
|
+
principals: string[];
|
|
152
|
+
}
|
|
153
|
+
interface Connection {
|
|
154
|
+
id: string;
|
|
155
|
+
machineId: string;
|
|
156
|
+
transport: 'ssh';
|
|
157
|
+
host: string;
|
|
158
|
+
port: number;
|
|
159
|
+
username: string;
|
|
160
|
+
certificate: string;
|
|
161
|
+
expiresAt: string;
|
|
162
|
+
hostTrust: HostTrust;
|
|
163
|
+
}
|
|
164
|
+
/** Response of `POST /v1/machines/{id}/exec`. */
|
|
165
|
+
interface ExecResponse {
|
|
166
|
+
stdout: string;
|
|
167
|
+
stderr: string;
|
|
168
|
+
exitCode: number;
|
|
169
|
+
timedOut: boolean;
|
|
170
|
+
truncated: boolean;
|
|
171
|
+
error?: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
declare const DEFAULT_API_URL = "https://api.box.instacloud.com";
|
|
175
|
+
/** Options shared by every call that talks to the API. */
|
|
176
|
+
interface ConnectionOptions {
|
|
177
|
+
/** API key from the instabox dashboard's API Keys page. Default: env `INSTABOX_API_KEY`. */
|
|
178
|
+
apiKey?: string;
|
|
179
|
+
/** API base URL. Default: env `INSTABOX_API_URL`, else `https://api.box.instacloud.com`. */
|
|
180
|
+
apiUrl?: string;
|
|
181
|
+
/** Timeout of a single HTTP request in ms. Default 60 000; exec defaults to its command timeout plus 30 000. */
|
|
182
|
+
requestTimeoutMs?: number;
|
|
183
|
+
/** Max time to wait for a lifecycle operation (create, pause, resume, fork, kill) in ms. Default 600 000. */
|
|
184
|
+
operationTimeoutMs?: number;
|
|
185
|
+
/** Custom fetch implementation (tests, proxies). Default: global `fetch`. */
|
|
186
|
+
fetch?: typeof fetch;
|
|
187
|
+
/** Advanced: first delay of operation polling in ms (grows 1.5x to 1 s). Default 250. */
|
|
188
|
+
pollIntervalMs?: number;
|
|
189
|
+
/** Advanced: first delay between retries in ms. Default 250. */
|
|
190
|
+
retryDelayMs?: number;
|
|
191
|
+
}
|
|
192
|
+
interface RequestOptions {
|
|
193
|
+
timeoutMs?: number;
|
|
194
|
+
body?: unknown;
|
|
195
|
+
query?: Record<string, string | number | string[] | undefined>;
|
|
196
|
+
/** Retry on 502/503/504 and network errors. Default: true for GET and for requests carrying an Idempotency-Key. */
|
|
197
|
+
retry?: boolean;
|
|
198
|
+
/** Send an Idempotency-Key. Default: true for every method other than GET/HEAD. */
|
|
199
|
+
idempotent?: boolean;
|
|
200
|
+
}
|
|
201
|
+
declare class HttpClient {
|
|
202
|
+
readonly apiUrl: string;
|
|
203
|
+
readonly operationTimeoutMs: number;
|
|
204
|
+
private readonly apiKey;
|
|
205
|
+
private readonly requestTimeoutMs?;
|
|
206
|
+
private readonly fetchImpl;
|
|
207
|
+
private readonly pollIntervalMs;
|
|
208
|
+
private readonly retryDelayMs;
|
|
209
|
+
constructor(opts?: ConnectionOptions);
|
|
210
|
+
request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;
|
|
211
|
+
/** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */
|
|
212
|
+
send(method: string, path: string, opts?: RequestOptions): Promise<Response>;
|
|
213
|
+
private backoff;
|
|
214
|
+
/** Polls an operation until it is `succeeded` (returns it) or `failed` (throws). */
|
|
215
|
+
waitForOperation(op: Operation, timeoutMs?: number): Promise<Operation>;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
interface CommandOptions {
|
|
219
|
+
/** Working directory. Default: the server's default (HOME, `/data/home`). */
|
|
220
|
+
cwd?: string;
|
|
221
|
+
/** Extra environment variables, merged over the sandbox-level `envs` from `Sandbox.create`. */
|
|
222
|
+
envs?: Record<string, string>;
|
|
223
|
+
/** Command timeout in ms (sent as whole seconds). Default: the server's default. */
|
|
224
|
+
timeoutMs?: number;
|
|
225
|
+
/** Text sent to the command's standard input. */
|
|
226
|
+
stdin?: string;
|
|
227
|
+
/**
|
|
228
|
+
* Called with stdout once the command finished. Output is not streamed yet:
|
|
229
|
+
* the callback receives the whole stdout in one call.
|
|
230
|
+
*/
|
|
231
|
+
onStdout?: (data: string) => void | Promise<void>;
|
|
232
|
+
/** Like `onStdout`, for stderr. */
|
|
233
|
+
onStderr?: (data: string) => void | Promise<void>;
|
|
234
|
+
/** Start the command detached (nohup) and return right away with its PID. */
|
|
235
|
+
background?: boolean;
|
|
236
|
+
}
|
|
237
|
+
/** A command started with `background: true`. */
|
|
238
|
+
interface CommandHandle {
|
|
239
|
+
pid: number;
|
|
240
|
+
/** Sends SIGTERM to the process. Returns false if it had already exited. */
|
|
241
|
+
kill(): Promise<boolean>;
|
|
242
|
+
}
|
|
243
|
+
declare class Commands {
|
|
244
|
+
private readonly http;
|
|
245
|
+
private readonly sandboxId;
|
|
246
|
+
private readonly defaultEnvs;
|
|
247
|
+
/** @internal */
|
|
248
|
+
constructor(http: HttpClient, sandboxId: string, defaultEnvs: Record<string, string>);
|
|
249
|
+
/**
|
|
250
|
+
* Runs a shell command in the sandbox and waits for it to finish.
|
|
251
|
+
* Throws `CommandExitError` (carrying stdout, stderr and exitCode) when it exits non-zero.
|
|
252
|
+
*/
|
|
253
|
+
run(cmd: string, opts: CommandOptions & {
|
|
254
|
+
background: true;
|
|
255
|
+
}): Promise<CommandHandle>;
|
|
256
|
+
run(cmd: string, opts?: CommandOptions & {
|
|
257
|
+
background?: false;
|
|
258
|
+
}): Promise<CommandResult>;
|
|
259
|
+
run(cmd: string, opts?: CommandOptions): Promise<CommandResult | CommandHandle>;
|
|
260
|
+
/** @internal Raw exec: never throws on a non-zero exit code. */
|
|
261
|
+
exec(cmd: string, opts?: Pick<CommandOptions, 'cwd' | 'envs' | 'timeoutMs' | 'stdin'>): Promise<CommandResult>;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Largest file `files.read` / `files.write` move (files go through exec as base64). */
|
|
265
|
+
declare const MAX_FILE_BYTES: number;
|
|
266
|
+
interface EntryInfo {
|
|
267
|
+
name: string;
|
|
268
|
+
path: string;
|
|
269
|
+
type: 'file' | 'dir';
|
|
270
|
+
}
|
|
271
|
+
interface WriteInfo {
|
|
272
|
+
path: string;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* File access inside the sandbox. Implemented on top of exec (base64 over the command
|
|
276
|
+
* channel), capped at 10 MiB per file.
|
|
277
|
+
*/
|
|
278
|
+
declare class Files {
|
|
279
|
+
private readonly commands;
|
|
280
|
+
/** @internal */
|
|
281
|
+
constructor(commands: Commands);
|
|
282
|
+
/** Reads a file. Returns text (UTF-8) by default, or bytes with `{ format: 'bytes' }`. */
|
|
283
|
+
read(path: string, opts?: {
|
|
284
|
+
format?: 'text';
|
|
285
|
+
}): Promise<string>;
|
|
286
|
+
read(path: string, opts: {
|
|
287
|
+
format: 'bytes';
|
|
288
|
+
}): Promise<Uint8Array>;
|
|
289
|
+
/** Writes a file, creating parent directories. Replaces the file atomically (temp file + rename). */
|
|
290
|
+
write(path: string, data: string | Uint8Array): Promise<WriteInfo>;
|
|
291
|
+
/** Lists the entries of a directory (not recursive). */
|
|
292
|
+
list(path: string): Promise<EntryInfo[]>;
|
|
293
|
+
/** Removes a file or a directory (recursively). Missing paths are fine. */
|
|
294
|
+
remove(path: string): Promise<void>;
|
|
295
|
+
/** True if a file or directory exists at `path`. */
|
|
296
|
+
exists(path: string): Promise<boolean>;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
declare const DEFAULT_TEMPLATE = "universal";
|
|
300
|
+
interface SandboxOpts extends ConnectionOptions {
|
|
301
|
+
/** Machine name. Default `sbx-<random>`. */
|
|
302
|
+
name?: string;
|
|
303
|
+
/** String labels stored with the sandbox; filter on them with `Sandbox.list({ metadata })`. */
|
|
304
|
+
metadata?: Record<string, string>;
|
|
305
|
+
/** Environment variables applied to every `commands.run` of this Sandbox object (client-side). */
|
|
306
|
+
envs?: Record<string, string>;
|
|
307
|
+
/**
|
|
308
|
+
* The server pauses (or with `onTimeout: 'kill'` deletes) the sandbox this long after creation.
|
|
309
|
+
* Sent as whole seconds, 60 s to 24 h. Default: no timeout. Change it with `setTimeout()`.
|
|
310
|
+
*/
|
|
311
|
+
timeoutMs?: number;
|
|
312
|
+
/** What happens at the timeout: `pause` (default) or `kill`. */
|
|
313
|
+
onTimeout?: OnTimeout;
|
|
314
|
+
/** Stop and archive after this many milliseconds, independent of the pause/kill timeout. */
|
|
315
|
+
archiveMs?: number;
|
|
316
|
+
/** vCPUs. Default: the template's. */
|
|
317
|
+
vcpus?: number;
|
|
318
|
+
/** Memory in MiB. Default: the template's. */
|
|
319
|
+
memMiB?: number;
|
|
320
|
+
/** Size of the persistent `/data` disk in GiB. Default: the template's. */
|
|
321
|
+
diskGiB?: number;
|
|
322
|
+
/** Root disk size in GiB; may only grow. */
|
|
323
|
+
rootDiskGiB?: number;
|
|
324
|
+
}
|
|
325
|
+
interface SandboxConnectOpts extends ConnectionOptions {
|
|
326
|
+
/** Resume the sandbox if it is paused (suspended) or stopped. Default true. */
|
|
327
|
+
resume?: boolean;
|
|
328
|
+
envs?: Record<string, string>;
|
|
329
|
+
}
|
|
330
|
+
interface SandboxListOpts extends ConnectionOptions {
|
|
331
|
+
/** Only sandboxes whose metadata has every one of these key/value pairs. */
|
|
332
|
+
metadata?: Record<string, string>;
|
|
333
|
+
}
|
|
334
|
+
interface SandboxInfo {
|
|
335
|
+
sandboxId: string;
|
|
336
|
+
/** Template the sandbox runs (`template.id`). */
|
|
337
|
+
templateId: string;
|
|
338
|
+
/** Snapshot the sandbox was created from, if any. */
|
|
339
|
+
snapshotId?: string;
|
|
340
|
+
name: string;
|
|
341
|
+
/** String labels stored with the sandbox. */
|
|
342
|
+
metadata: Record<string, string>;
|
|
343
|
+
/** Creation time of the machine. */
|
|
344
|
+
startedAt: Date;
|
|
345
|
+
/** When the server pauses or kills the sandbox (see `onTimeout`); undefined for no timeout. */
|
|
346
|
+
endAt?: Date;
|
|
347
|
+
archiveAt?: Date;
|
|
348
|
+
onTimeout: OnTimeout;
|
|
349
|
+
state: MachineState;
|
|
350
|
+
/** The raw machine object from the API. */
|
|
351
|
+
machine: Machine;
|
|
352
|
+
}
|
|
353
|
+
interface ForkOpts {
|
|
354
|
+
/** Name of the new sandbox. Default `<name>-fork-<random>`. */
|
|
355
|
+
name?: string;
|
|
356
|
+
vcpus?: number;
|
|
357
|
+
memMiB?: number;
|
|
358
|
+
/** May only grow. */
|
|
359
|
+
diskGiB?: number;
|
|
360
|
+
/** Root disk size in GiB; may only grow. */
|
|
361
|
+
rootDiskGiB?: number;
|
|
362
|
+
/** Timeout of the copy, as in `SandboxOpts.timeoutMs`. Default: none (the source's is not copied). */
|
|
363
|
+
timeoutMs?: number;
|
|
364
|
+
onTimeout?: OnTimeout;
|
|
365
|
+
/** Metadata of the copy. Default: the source's; `{}` for none. */
|
|
366
|
+
metadata?: Record<string, string>;
|
|
367
|
+
/**
|
|
368
|
+
* A fork needs a stopped source. When true (default), `fork()` stops the source first if needed
|
|
369
|
+
* (running processes end, `/data` is kept) and leaves it stopped; call `resume()` to start it again.
|
|
370
|
+
* When false, a source that is not stopped makes the call fail.
|
|
371
|
+
*/
|
|
372
|
+
stopSource?: boolean;
|
|
373
|
+
}
|
|
374
|
+
interface CreateSnapshotOpts {
|
|
375
|
+
name: string;
|
|
376
|
+
description?: string;
|
|
377
|
+
/** Save only the root disk; omit the persistent /data disk. */
|
|
378
|
+
rootOnly?: boolean;
|
|
379
|
+
}
|
|
380
|
+
interface SshCredentials {
|
|
381
|
+
host: string;
|
|
382
|
+
port: number;
|
|
383
|
+
/** The machine ID. */
|
|
384
|
+
username: string;
|
|
385
|
+
/** OpenSSH user certificate for `publicKey`, in authorized_keys format. Save it as `<key>-cert.pub`. */
|
|
386
|
+
certificate: string;
|
|
387
|
+
/** Line for known_hosts that trusts the instabox gateway: `@cert-authority [host]:port <ca key>`. */
|
|
388
|
+
knownHostsLine: string;
|
|
389
|
+
expiresAt: Date;
|
|
390
|
+
connectionId: string;
|
|
391
|
+
}
|
|
392
|
+
/** A instabox dev machine. Create one with `Sandbox.create()` or attach with `Sandbox.connect(id)`. */
|
|
393
|
+
declare class Sandbox {
|
|
394
|
+
private readonly http;
|
|
395
|
+
/** The machine ID (`m_...`). */
|
|
396
|
+
readonly sandboxId: string;
|
|
397
|
+
/** Run shell commands. Needs a instabox server with the exec endpoint. */
|
|
398
|
+
readonly commands: Commands;
|
|
399
|
+
/** Read and write files. Needs a instabox server with the exec endpoint. */
|
|
400
|
+
readonly files: Files;
|
|
401
|
+
private machine;
|
|
402
|
+
private constructor();
|
|
403
|
+
/**
|
|
404
|
+
* Creates a sandbox and waits until it is running.
|
|
405
|
+
* `template` is a template ID, a private snapshot name or a snapshot ID (`sn_...`).
|
|
406
|
+
* Template IDs take precedence over snapshot names. Default template: `universal`.
|
|
407
|
+
*/
|
|
408
|
+
static create(opts?: SandboxOpts): Promise<Sandbox>;
|
|
409
|
+
static create(template: string, opts?: SandboxOpts): Promise<Sandbox>;
|
|
410
|
+
/** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
|
|
411
|
+
static connect(sandboxId: string, opts?: SandboxConnectOpts): Promise<Sandbox>;
|
|
412
|
+
/** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
|
|
413
|
+
static list(opts?: SandboxListOpts): Promise<SandboxInfo[]>;
|
|
414
|
+
/** Deletes a sandbox and its disks. Returns false if it did not exist. */
|
|
415
|
+
static kill(sandboxId: string, opts?: ConnectionOptions): Promise<boolean>;
|
|
416
|
+
/** Lists the caller's private snapshots. Requires images:read. */
|
|
417
|
+
static listSnapshots(opts?: ConnectionOptions): Promise<Snapshot[]>;
|
|
418
|
+
/** Fetches a snapshot by ID. Requires images:read. */
|
|
419
|
+
static getSnapshot(snapshotId: string, opts?: ConnectionOptions): Promise<Snapshot>;
|
|
420
|
+
/** Deletes a snapshot. Returns false if absent. Requires images:delete. */
|
|
421
|
+
static deleteSnapshot(snapshotId: string, opts?: ConnectionOptions): Promise<boolean>;
|
|
422
|
+
/** Saves a stopped sandbox's disks as a private snapshot. Requires images:write. */
|
|
423
|
+
createSnapshot(opts: CreateSnapshotOpts): Promise<Snapshot>;
|
|
424
|
+
/** Fetches the current state of the sandbox. */
|
|
425
|
+
getInfo(): Promise<SandboxInfo>;
|
|
426
|
+
/**
|
|
427
|
+
* Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.
|
|
428
|
+
* `onTimeout` changes what happens then (`pause` or `kill`).
|
|
429
|
+
*/
|
|
430
|
+
setTimeout(timeoutMs: number, opts?: {
|
|
431
|
+
onTimeout?: OnTimeout;
|
|
432
|
+
}): Promise<void>;
|
|
433
|
+
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
434
|
+
setMetadata(metadata: Record<string, string>): Promise<void>;
|
|
435
|
+
/** True if the sandbox is running (fetches fresh state). */
|
|
436
|
+
isRunning(): Promise<boolean>;
|
|
437
|
+
/** Snapshots memory and stops the sandbox (suspend). `resume()` or `Sandbox.connect()` brings it back. */
|
|
438
|
+
pause(): Promise<void>;
|
|
439
|
+
/** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
|
|
440
|
+
resume(): Promise<void>;
|
|
441
|
+
/** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
|
|
442
|
+
private wake;
|
|
443
|
+
/** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
|
|
444
|
+
stop(): Promise<void>;
|
|
445
|
+
/** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
|
|
446
|
+
fork(opts?: ForkOpts): Promise<Sandbox>;
|
|
447
|
+
/** Deletes the sandbox and its disks. Returns false if it was already gone. */
|
|
448
|
+
kill(): Promise<boolean>;
|
|
449
|
+
/**
|
|
450
|
+
* Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).
|
|
451
|
+
* Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding
|
|
452
|
+
* `knownHostsLine` to known_hosts. The sandbox must be running.
|
|
453
|
+
*/
|
|
454
|
+
sshCredentials(publicKey: string, opts?: {
|
|
455
|
+
ttlSeconds?: number;
|
|
456
|
+
}): Promise<SshCredentials>;
|
|
457
|
+
/**
|
|
458
|
+
* Re-reads the machine from the server (other handles or the dashboard may have changed it),
|
|
459
|
+
* waits for its active operation if one is running, and leaves the fresh state cached.
|
|
460
|
+
* Every state-dependent method calls this first, so it never decides from a stale cache.
|
|
461
|
+
*/
|
|
462
|
+
private settle;
|
|
463
|
+
private mutate;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export { type ApiError, CommandExitError, type CommandHandle, type CommandOptions, type CommandResult, Commands, type Connection, type ConnectionOptions, type CreateSnapshotOpts, DEFAULT_API_URL, DEFAULT_TEMPLATE, type EntryInfo, type ExecResponse, Files, type ForkOpts, type HostTrust, InstaboxAuthError, InstaboxError, type InstaboxErrorInit, InstaboxQuotaError, InstaboxTimeoutError, MAX_FILE_BYTES, type Machine, type MachineList, type MachineSpec, type MachineState, type OnTimeout, type Operation, Sandbox, type SandboxConnectOpts, type SandboxInfo, type SandboxListOpts, type SandboxOpts, type Snapshot, type SnapshotList, type SshCredentials, type Template, type TemplateRef, type WriteInfo };
|