@tinify-dev/client 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/CHANGELOG.md +31 -0
- package/LICENSE +21 -0
- package/README.md +232 -0
- package/dist/chunk-NYRKB5BB.js +573 -0
- package/dist/chunk-NYRKB5BB.js.map +1 -0
- package/dist/cli.cjs +885 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +37 -0
- package/dist/cli.d.ts +37 -0
- package/dist/cli.js +307 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +586 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +130 -0
- package/dist/index.d.ts +130 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/types-D58KVL3U.d.cts +219 -0
- package/dist/types-D58KVL3U.d.ts +219 -0
- package/package.json +64 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/errors.ts","../src/inputs.ts","../src/batches.ts","../src/http.ts","../src/client.ts"],"names":[],"mappings":";;;AACO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,WAAA,GAAc,gBAAA;AAGpB,IAAM,YAAA,GAAe,iBAAA;AAGrB,IAAM,mBAAA,GAAsB,CAAA;AAG5B,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,eAAA,GAAkB,GAAA;AAGxB,IAAM,cAAA,GAAiB,GAAA;AAGvB,IAAM,cAAA,GAAiB;AAGvB,IAAM,eAAA,GAAkB;AAGxB,IAAM,0BAAA,GAA6B,CAAA;AAGnC,IAAM,wBAAA,GAA2B,GAAA;AACjC,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,4BAAA,GAA+B,GAAA;AACrC,IAAM,uBAAA,GAA0B,GAAA;AAGhC,IAAM,uBAAA,GAA0B;AAAA,EACrC,WAAA;AAAA,EACA,qBAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA;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AAA,EAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,MACzD;AACA,MAAA,OAAO,IAAA;AAAA,IACT,CAAA;AACA,IAAA,MAAM,EAAE,MAAM,SAAA,EAAW,SAAA,KAAc,MAAM,IAAA,CAAK,KAAK,WAAA,CAA2B;AAAA,MAChF,MAAA,EAAQ,MAAA;AAAA,MACR,IAAA,EAAM,kBAAkB,SAAS,CAAA,CAAA;AAAA,MACjC,IAAA,EAAM,QAAA;AAAA,MACN,cAAA,EAAgB,QAAQ,cAAA,IAAkB,MAAA;AAAA,MAC1C,GAAI,QAAQ,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAO,GAAI;AAAC,KAClE,CAAA;AACD,IAAA,OAAO,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,WAAW,SAAA,EAAU;AAAA,EACjD;AACF","file":"index.cjs","sourcesContent":["/** Default API origin. Override with `baseUrl` or the `TINIFY_BASE_URL` env var. */\nexport const DEFAULT_BASE_URL = \"https://api.tinify.dev\";\n\n/** Environment variable read when `apiKey` is not passed explicitly. */\nexport const ENV_API_KEY = \"TINIFY_API_KEY\";\n\n/** Environment variable read when `baseUrl` is not passed explicitly. */\nexport const ENV_BASE_URL = \"TINIFY_BASE_URL\";\n\n/** Retries performed after the initial attempt for 429/503/network failures. */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/** Per-attempt request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 60_000;\n\n/** Initial retry backoff in milliseconds (exponential, full jitter). */\nexport const BACKOFF_BASE_MS = 500;\n\n/** Retry backoff ceiling in milliseconds. */\nexport const BACKOFF_CAP_MS = 8_000;\n\n/** Maximum accepted image size in bytes (40 MiB), matching the server limit. */\nexport const MAX_FILE_BYTES = 41_943_040;\n\n/** Maximum number of files per batch. */\nexport const MAX_BATCH_FILES = 200;\n\n/** Default concurrency for presigned batch uploads. */\nexport const DEFAULT_UPLOAD_CONCURRENCY = 4;\n\n/** Batch polling defaults: 1s start, x1.5 growth, 10s cap, 10 min budget. */\nexport const DEFAULT_POLL_INTERVAL_MS = 1_000;\nexport const DEFAULT_POLL_GROWTH = 1.5;\nexport const DEFAULT_MAX_POLL_INTERVAL_MS = 10_000;\nexport const DEFAULT_WAIT_TIMEOUT_MS = 600_000;\n\n/** Batch statuses that will never change again. */\nexport const BATCH_TERMINAL_STATUSES = [\n \"succeeded\",\n \"partially_succeeded\",\n \"failed\",\n \"canceled\",\n \"expired\",\n] as const;\n\n/** Idempotency-Key constraints enforced by the API. */\nexport const IDEMPOTENCY_KEY_MIN_LENGTH = 8;\nexport const IDEMPOTENCY_KEY_MAX_LENGTH = 160;\n","import type { TinifyErrorCode } from \"./types\";\n\n/** Base class for every error thrown by this SDK. */\nexport class TinifyError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TinifyError\";\n }\n}\n\nexport interface TinifyApiErrorInit {\n status: number;\n code: TinifyErrorCode;\n message: string;\n requestId: string;\n details?: Record<string, unknown>;\n /** Seconds to wait before retrying, parsed from Retry-After when present. */\n retryAfter?: number;\n}\n\n/**\n * A structured error envelope returned by the API:\n * `{ error: { code, message, details }, request_id }`.\n */\nexport class TinifyApiError extends TinifyError {\n readonly status: number;\n readonly code: TinifyErrorCode;\n readonly requestId: string;\n readonly details: Record<string, unknown>;\n readonly retryAfter?: number;\n\n constructor(init: TinifyApiErrorInit) {\n super(`${init.code} (HTTP ${init.status}): ${init.message} [request_id: ${init.requestId}]`);\n this.name = \"TinifyApiError\";\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId;\n this.details = init.details ?? {};\n if (init.retryAfter !== undefined) this.retryAfter = init.retryAfter;\n }\n}\n\n/** The request never produced an HTTP response (DNS, TLS, socket resets...). */\nexport class TinifyNetworkError extends TinifyError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TinifyNetworkError\";\n }\n}\n\n/** A per-attempt timeout or a `waitForBatch` budget was exceeded. */\nexport class TinifyTimeoutError extends TinifyError {\n readonly timeoutMs: number;\n\n constructor(message: string, timeoutMs: number) {\n super(message);\n this.name = \"TinifyTimeoutError\";\n this.timeoutMs = timeoutMs;\n }\n}\n","import { TinifyError } from \"./errors\";\n\n/**\n * Anything the client accepts as an image input:\n * - a file path (Node.js only),\n * - raw bytes (`Buffer`, `Uint8Array`, `ArrayBuffer`),\n * - a `Blob` / `File`.\n */\nexport type TinifyInput = string | Uint8Array | ArrayBuffer | Blob;\n\nexport interface NormalizedInput {\n blob: Blob;\n filename: string;\n}\n\nconst DEFAULT_FILENAME = \"image\";\n\n/**\n * Normalizes any {@link TinifyInput} into a `Blob` plus multipart filename.\n * File paths lazily import `node:fs` so browser bundles never pull it in;\n * passing a path outside Node.js throws a clear error instead.\n */\nexport async function normalizeInput(\n input: TinifyInput,\n filename?: string,\n): Promise<NormalizedInput> {\n if (typeof input === \"string\") {\n let fs: typeof import(\"node:fs/promises\");\n let path: typeof import(\"node:path\");\n try {\n fs = await import(\"node:fs/promises\");\n path = await import(\"node:path\");\n } catch {\n throw new TinifyError(\n \"File path inputs are only supported in Node.js. Pass a Blob or File instead.\",\n );\n }\n const bytes = await fs.readFile(input);\n return {\n blob: new Blob([bytesToView(bytes)]),\n filename: filename ?? path.basename(input),\n };\n }\n\n if (typeof Blob !== \"undefined\" && input instanceof Blob) {\n const name =\n filename ??\n (typeof File !== \"undefined\" && input instanceof File && input.name\n ? input.name\n : DEFAULT_FILENAME);\n return { blob: input, filename: name };\n }\n\n if (input instanceof ArrayBuffer) {\n return { blob: new Blob([input]), filename: filename ?? DEFAULT_FILENAME };\n }\n\n if (ArrayBuffer.isView(input)) {\n return {\n blob: new Blob([bytesToView(input)]),\n filename: filename ?? DEFAULT_FILENAME,\n };\n }\n\n throw new TypeError(\n \"Unsupported input: expected a file path, Uint8Array, ArrayBuffer, Blob, or File.\",\n );\n}\n\n/**\n * Re-views bytes over a plain ArrayBuffer so the value satisfies `BlobPart`\n * (Buffers may be backed by a pooled or shared ArrayBuffer).\n */\nfunction bytesToView(view: ArrayBufferView): Uint8Array {\n const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n if (\n bytes.buffer instanceof ArrayBuffer &&\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength\n ) {\n return bytes;\n }\n // Copy when the view is offset into a pooled buffer (Buffer.from) or shared.\n const copy = new Uint8Array(new ArrayBuffer(bytes.byteLength));\n copy.set(bytes);\n return copy;\n}\n","import { BATCH_TERMINAL_STATUSES, DEFAULT_UPLOAD_CONCURRENCY } from \"./constants\";\nimport { TinifyError, TinifyNetworkError } from \"./errors\";\nimport { normalizeInput, type TinifyInput } from \"./inputs\";\nimport type {\n BatchStatus,\n BatchTerminalStatus,\n BatchUpload,\n BatchUploadSession,\n FetchFunction,\n UploadBatchFilesOptions,\n} from \"./types\";\n\nconst TERMINAL: ReadonlySet<string> = new Set(BATCH_TERMINAL_STATUSES);\n\nexport function isTerminalBatchStatus(status: BatchStatus): status is BatchTerminalStatus {\n return TERMINAL.has(status);\n}\n\n/**\n * Uploads batch files to their presigned URLs.\n *\n * Each PUT sends the raw bytes with exactly the headers the API returned for\n * that slot. The Authorization header is deliberately never sent: these are\n * presigned object-storage URLs and an extra auth mechanism would be rejected.\n */\nexport async function uploadBatchFiles(\n fetchImpl: FetchFunction,\n session: BatchUploadSession,\n files: Record<string, TinifyInput>,\n options: UploadBatchFilesOptions = {},\n): Promise<void> {\n const missing = session.uploads\n .map((upload) => upload.client_id)\n .filter((clientId) => !(clientId in files));\n if (missing.length > 0) {\n throw new TinifyError(\n `Missing input for batch client_id(s): ${missing.join(\", \")}. ` +\n \"Pass a { client_id: input } record covering every file in the session.\",\n );\n }\n\n const queue = [...session.uploads];\n const concurrency = Math.max(\n 1,\n Math.min(options.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY, queue.length),\n );\n\n const workers = Array.from({ length: concurrency }, async () => {\n for (;;) {\n const upload = queue.shift();\n if (upload === undefined) return;\n options.signal?.throwIfAborted();\n await putOne(fetchImpl, upload, files[upload.client_id]!, options.signal);\n }\n });\n await Promise.all(workers);\n}\n\nasync function putOne(\n fetchImpl: FetchFunction,\n upload: BatchUpload,\n input: TinifyInput,\n signal?: AbortSignal,\n): Promise<void> {\n const { blob } = await normalizeInput(input);\n let response: Response;\n try {\n response = await fetchImpl(upload.upload_url, {\n method: \"PUT\",\n headers: upload.headers,\n body: blob,\n ...(signal !== undefined ? { signal } : {}),\n });\n } catch (error) {\n throw new TinifyNetworkError(\n `Upload for client_id \"${upload.client_id}\" failed: ` +\n `${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new TinifyError(\n `Upload for client_id \"${upload.client_id}\" was rejected with HTTP ${response.status}` +\n (text ? `: ${text.slice(0, 200)}` : \".\"),\n );\n }\n // Drain any remaining body.\n await response.arrayBuffer().catch(() => undefined);\n}\n","import {\n BACKOFF_BASE_MS,\n BACKOFF_CAP_MS,\n IDEMPOTENCY_KEY_MAX_LENGTH,\n IDEMPOTENCY_KEY_MIN_LENGTH,\n} from \"./constants\";\nimport { TinifyApiError, TinifyError, TinifyNetworkError, TinifyTimeoutError } from \"./errors\";\nimport type { FetchFunction, RateLimitInfo } from \"./types\";\n\nexport interface HttpClientConfig {\n apiKey: string;\n baseUrl: string;\n maxRetries: number;\n timeoutMs: number;\n fetchImpl: FetchFunction;\n}\n\nexport type RequestBody = string | FormData | Blob | Uint8Array;\n\nexport interface HttpRequestOptions {\n method: \"GET\" | \"POST\" | \"DELETE\";\n path: string;\n /** Rebuilt per attempt so multipart bodies survive retries. */\n body?: () => RequestBody;\n contentType?: string;\n /**\n * When set, the header is sent. `\"auto\"` generates a UUID once per logical\n * call and reuses it across every retry.\n */\n idempotencyKey?: string | \"auto\";\n signal?: AbortSignal;\n}\n\nexport interface HttpResult {\n response: Response;\n requestIdHeader: string | null;\n rateLimit: RateLimitInfo | null;\n}\n\nconst RETRYABLE_STATUSES = new Set([429, 503]);\n\nexport function generateIdempotencyKey(): string {\n return globalThis.crypto.randomUUID();\n}\n\nexport function validateIdempotencyKey(key: string): void {\n if (key.length < IDEMPOTENCY_KEY_MIN_LENGTH || key.length > IDEMPOTENCY_KEY_MAX_LENGTH) {\n throw new TinifyError(\n `Idempotency keys must be ${IDEMPOTENCY_KEY_MIN_LENGTH}-${IDEMPOTENCY_KEY_MAX_LENGTH} characters (got ${key.length}).`,\n );\n }\n}\n\n/** Parses Retry-After (delta-seconds or HTTP-date) into milliseconds. */\nexport function parseRetryAfterMs(header: string | null): number | undefined {\n if (header === null || header.trim() === \"\") return undefined;\n const value = header.trim();\n if (/^\\d+$/.test(value)) return Number(value) * 1000;\n const date = Date.parse(value);\n if (Number.isNaN(date)) return undefined;\n return Math.max(0, date - Date.now());\n}\n\n/** Exponential backoff with full jitter: random(0, min(cap, base * 2^attempt)). */\nexport function backoffMs(attempt: number): number {\n const ceiling = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);\n return Math.random() * ceiling;\n}\n\nexport function rateLimitFromHeaders(headers: Headers): RateLimitInfo | null {\n const limit = headers.get(\"x-ratelimit-limit\");\n const remaining = headers.get(\"x-ratelimit-remaining\");\n const reset = headers.get(\"x-ratelimit-reset\");\n if (limit === null || remaining === null || reset === null) return null;\n return { limit: Number(limit), remaining: Number(remaining), reset: Number(reset) };\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(abortReason(signal!));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new TinifyError(\"The operation was aborted.\");\n}\n\n/** Builds and throws a TinifyApiError from a non-2xx response. */\nexport async function throwApiError(response: Response): Promise<never> {\n const text = await response.text().catch(() => \"\");\n let body: unknown;\n try {\n body = text ? JSON.parse(text) : undefined;\n } catch {\n body = undefined;\n }\n const envelope = (body ?? {}) as {\n error?: { code?: string; message?: string; details?: Record<string, unknown> };\n request_id?: string;\n };\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n throw new TinifyApiError({\n status: response.status,\n code: envelope.error?.code ?? \"unknown_error\",\n message: envelope.error?.message ?? `Unexpected HTTP ${response.status} response.`,\n requestId:\n envelope.request_id ?? response.headers.get(\"x-request-id\") ?? \"unavailable\",\n details: envelope.error?.details ?? {},\n ...(retryAfterMs !== undefined ? { retryAfter: retryAfterMs / 1000 } : {}),\n });\n}\n\nexport class HttpClient {\n private readonly config: HttpClientConfig;\n\n constructor(config: HttpClientConfig) {\n this.config = config;\n }\n\n get baseUrl(): string {\n return this.config.baseUrl;\n }\n\n get fetchImpl(): FetchFunction {\n return this.config.fetchImpl;\n }\n\n /**\n * Performs a request with retry semantics:\n * - retries 429/503 (honoring Retry-After) and network failures,\n * - never retries any other 4xx/5xx,\n * - reuses one Idempotency-Key across every attempt of the call.\n */\n async request(options: HttpRequestOptions): Promise<HttpResult> {\n const url = new URL(options.path, `${this.config.baseUrl}/`).toString();\n let idempotencyKey: string | undefined;\n if (options.idempotencyKey === \"auto\") {\n idempotencyKey = generateIdempotencyKey();\n } else if (options.idempotencyKey !== undefined) {\n validateIdempotencyKey(options.idempotencyKey);\n idempotencyKey = options.idempotencyKey;\n }\n\n let attempt = 0;\n // One extra loop iteration per allowed retry.\n for (;;) {\n options.signal?.throwIfAborted();\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.config.apiKey}`,\n accept: \"application/json\",\n \"user-agent\": \"@tinify-dev/client/0.1.0\",\n };\n if (idempotencyKey !== undefined) headers[\"idempotency-key\"] = idempotencyKey;\n if (options.contentType !== undefined) headers[\"content-type\"] = options.contentType;\n\n let response: Response;\n try {\n response = await this.fetchWithTimeout(\n url,\n {\n method: options.method,\n headers,\n ...(options.body !== undefined ? { body: options.body() } : {}),\n },\n options.signal,\n );\n } catch (error) {\n if (error instanceof TinifyTimeoutError) throw error;\n if (options.signal?.aborted) throw error;\n if (attempt < this.config.maxRetries) {\n await sleep(backoffMs(attempt), options.signal);\n attempt += 1;\n continue;\n }\n throw new TinifyNetworkError(\n `Request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n if (RETRYABLE_STATUSES.has(response.status) && attempt < this.config.maxRetries) {\n const retryAfter = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n // Drain the body so the failed attempt does not leak resources.\n await response.arrayBuffer().catch(() => undefined);\n await sleep(retryAfter ?? backoffMs(attempt), options.signal);\n attempt += 1;\n continue;\n }\n\n if (!response.ok) await throwApiError(response);\n\n return {\n response,\n requestIdHeader: response.headers.get(\"x-request-id\"),\n rateLimit: rateLimitFromHeaders(response.headers),\n };\n }\n }\n\n /** JSON-parsing wrapper around {@link request}. */\n async requestJson<T>(options: HttpRequestOptions): Promise<{\n body: T;\n requestId: string;\n rateLimit: RateLimitInfo | null;\n }> {\n const result = await this.request(options);\n let body: T;\n if (result.response.status === 204) {\n body = undefined as T;\n } else {\n body = (await result.response.json()) as T;\n }\n const bodyRequestId = (body as { request_id?: string } | undefined)?.request_id;\n return {\n body,\n requestId: bodyRequestId ?? result.requestIdHeader ?? \"unavailable\",\n rateLimit: result.rateLimit,\n };\n }\n\n private async fetchWithTimeout(\n url: string,\n init: RequestInit,\n signal?: AbortSignal,\n ): Promise<Response> {\n const controller = new AbortController();\n const timeoutError = new TinifyTimeoutError(\n `Request timed out after ${this.config.timeoutMs} ms.`,\n this.config.timeoutMs,\n );\n const timer = setTimeout(() => controller.abort(timeoutError), this.config.timeoutMs);\n const onAbort = (): void => controller.abort(abortReason(signal!));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n return await this.config.fetchImpl(url, { ...init, signal: controller.signal });\n } catch (error) {\n // undici surfaces the abort reason directly; rethrow our sentinel as-is.\n if (error === timeoutError) throw error;\n if (controller.signal.aborted && controller.signal.reason === timeoutError) {\n throw timeoutError;\n }\n throw error;\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }\n}\n","import { isTerminalBatchStatus, uploadBatchFiles } from \"./batches\";\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_MAX_POLL_INTERVAL_MS,\n DEFAULT_MAX_RETRIES,\n DEFAULT_POLL_GROWTH,\n DEFAULT_POLL_INTERVAL_MS,\n DEFAULT_TIMEOUT_MS,\n DEFAULT_WAIT_TIMEOUT_MS,\n ENV_API_KEY,\n ENV_BASE_URL,\n} from \"./constants\";\nimport { TinifyError, TinifyTimeoutError } from \"./errors\";\nimport { HttpClient, sleep, throwApiError } from \"./http\";\nimport { normalizeInput, type TinifyInput } from \"./inputs\";\nimport type {\n Batch,\n BatchUploadSession,\n CommitBatchResult,\n CompressOptions,\n ConvertOptions,\n CreateBatchParams,\n CropOptions,\n FetchFunction,\n ImageResultData,\n RequestOptions,\n ResizeOptions,\n TinifyClientOptions,\n TinifyResponse,\n UploadBatchFilesOptions,\n Usage,\n WaitForBatchOptions,\n} from \"./types\";\n\ninterface ImageEnvelope {\n data: ImageResultData;\n request_id?: string;\n}\n\n/**\n * Client for the Tinify.dev image API (https://tinify.dev/developers).\n *\n * Zero runtime dependencies; uses the platform `fetch`, `FormData`, and\n * `Blob`. Works in Node.js >= 20. Browser use is limited to trusted origins:\n * the API rejects untrusted browser origins, so call it server-side.\n */\nexport class TinifyClient {\n private readonly http: HttpClient;\n\n constructor(options: TinifyClientOptions = {}) {\n const env =\n typeof process !== \"undefined\" && process.env !== undefined ? process.env : {};\n const apiKey = options.apiKey ?? env[ENV_API_KEY];\n if (apiKey === undefined || apiKey === \"\") {\n throw new TinifyError(\n `Missing API key. Pass { apiKey } or set ${ENV_API_KEY}. ` +\n \"Keys are created at https://tinify.dev/developers.\",\n );\n }\n const baseUrl = (options.baseUrl ?? env[ENV_BASE_URL] ?? DEFAULT_BASE_URL).replace(\n /\\/+$/,\n \"\",\n );\n const fetchImpl: FetchFunction =\n options.fetch ?? ((input, init) => globalThis.fetch(input, init));\n this.http = new HttpClient({\n apiKey,\n baseUrl,\n maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n fetchImpl,\n });\n }\n\n // -------------------------------------------------------------------------\n // Synchronous image operations\n // -------------------------------------------------------------------------\n\n /** Compresses an image. Never returns more bytes than the input. */\n compress(\n input: TinifyInput,\n options: CompressOptions & RequestOptions = {},\n ): Promise<TinifyResponse<ImageResultData>> {\n return this.imageOperation(\n \"compress\",\n input,\n {\n quality_mode: options.quality_mode,\n target_size_bytes: options.target_size_bytes,\n },\n options,\n );\n }\n\n /** Resizes an image by width/height/scale. */\n resize(\n input: TinifyInput,\n options: ResizeOptions & RequestOptions = {},\n ): Promise<TinifyResponse<ImageResultData>> {\n return this.imageOperation(\n \"resize\",\n input,\n {\n width: options.width,\n height: options.height,\n scale: options.scale,\n keep_aspect_ratio: options.keep_aspect_ratio,\n optimize: options.optimize,\n },\n options,\n );\n }\n\n /** Crops an image to the given rectangle. */\n crop(\n input: TinifyInput,\n options: CropOptions & RequestOptions,\n ): Promise<TinifyResponse<ImageResultData>> {\n return this.imageOperation(\n \"crop\",\n input,\n {\n x: options.x,\n y: options.y,\n width: options.width,\n height: options.height,\n },\n options,\n );\n }\n\n /**\n * Converts an image to another format (AVIF, WebP, JPEG, or PNG).\n *\n * @beta The `/api/v1/images/convert` endpoint is rolling out server-side\n * and may not be available on every account yet.\n */\n convert(\n input: TinifyInput,\n options: ConvertOptions & RequestOptions,\n ): Promise<TinifyResponse<ImageResultData>> {\n return this.imageOperation(\n \"convert\",\n input,\n {\n format: options.format,\n quality_mode: options.quality_mode,\n },\n options,\n );\n }\n\n /** Returns the account's current billing-period usage. */\n async usage(options: Pick<RequestOptions, \"signal\"> = {}): Promise<TinifyResponse<Usage>> {\n const { body, requestId, rateLimit } = await this.http.requestJson<Usage>({\n method: \"GET\",\n path: \"/api/v1/usage\",\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n return { data: body, requestId, rateLimit };\n }\n\n /**\n * Downloads a result as a `Blob`. Accepts a result object, a response\n * envelope, or a download URL. Download URLs are unauthenticated and\n * expire two hours after the operation.\n */\n async download(\n resultOrUrl: string | ImageResultData | TinifyResponse<ImageResultData>,\n options: Pick<RequestOptions, \"signal\"> = {},\n ): Promise<Blob> {\n const raw =\n typeof resultOrUrl === \"string\"\n ? resultOrUrl\n : \"download_url\" in resultOrUrl\n ? resultOrUrl.download_url\n : resultOrUrl.data.download_url;\n const url = new URL(raw, `${this.http.baseUrl}/`).toString();\n // Deliberately no Authorization header: result URLs are self-contained\n // and presigned URLs reject requests carrying extra auth.\n const response = await this.http.fetchImpl(url, {\n method: \"GET\",\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n if (!response.ok) await throwApiError(response);\n return response.blob();\n }\n\n // -------------------------------------------------------------------------\n // Batches\n // -------------------------------------------------------------------------\n\n /**\n * Creates a durable batch. Returns one presigned upload slot per file;\n * upload the bytes, then {@link commitBatch}. Requires a paid plan.\n */\n async createBatch(\n params: CreateBatchParams,\n options: RequestOptions = {},\n ): Promise<TinifyResponse<BatchUploadSession>> {\n const { body, requestId, rateLimit } = await this.http.requestJson<BatchUploadSession>({\n method: \"POST\",\n path: \"/api/v1/batches\",\n contentType: \"application/json\",\n body: () => JSON.stringify(params),\n idempotencyKey: options.idempotencyKey ?? \"auto\",\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n return { data: body, requestId, rateLimit };\n }\n\n /**\n * Uploads file bytes to the presigned URLs of an upload session, keyed by\n * `client_id`. Runs up to `concurrency` (default 4) PUTs in parallel.\n */\n uploadBatchFiles(\n session: BatchUploadSession,\n files: Record<string, TinifyInput>,\n options: UploadBatchFilesOptions = {},\n ): Promise<void> {\n return uploadBatchFiles(this.http.fetchImpl, session, files, options);\n }\n\n /** Commits an uploaded batch for processing. */\n async commitBatch(\n batchId: string,\n options: RequestOptions = {},\n ): Promise<TinifyResponse<CommitBatchResult>> {\n const { body, requestId, rateLimit } = await this.http.requestJson<CommitBatchResult>({\n method: \"POST\",\n path: `/api/v1/batches/${encodeURIComponent(batchId)}/commit`,\n idempotencyKey: options.idempotencyKey ?? \"auto\",\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n return { data: body, requestId, rateLimit };\n }\n\n /** Fetches a batch with per-file state. */\n async getBatch(\n batchId: string,\n options: Pick<RequestOptions, \"signal\"> = {},\n ): Promise<TinifyResponse<Batch>> {\n const { body, requestId, rateLimit } = await this.http.requestJson<Batch>({\n method: \"GET\",\n path: `/api/v1/batches/${encodeURIComponent(batchId)}`,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n return { data: body, requestId, rateLimit };\n }\n\n /** Cancels a batch. Idempotent: canceling a terminal batch is a no-op. */\n async cancelBatch(\n batchId: string,\n options: Pick<RequestOptions, \"signal\"> = {},\n ): Promise<void> {\n await this.http.request({\n method: \"DELETE\",\n path: `/api/v1/batches/${encodeURIComponent(batchId)}`,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n }\n\n /**\n * Polls {@link getBatch} until the batch reaches a terminal status\n * (`succeeded`, `partially_succeeded`, `failed`, `canceled`, `expired`).\n * Polls start at 1s and grow x1.5 up to 10s; gives up after `timeoutMs`\n * (default 10 minutes) with a {@link TinifyTimeoutError}.\n */\n async waitForBatch(\n batchId: string,\n options: WaitForBatchOptions = {},\n ): Promise<TinifyResponse<Batch>> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const maxInterval = options.maxPollIntervalMs ?? DEFAULT_MAX_POLL_INTERVAL_MS;\n let interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const startedAt = Date.now();\n for (;;) {\n const result = await this.getBatch(batchId, options);\n if (isTerminalBatchStatus(result.data.status)) return result;\n const elapsed = Date.now() - startedAt;\n if (elapsed + interval > timeoutMs) {\n throw new TinifyTimeoutError(\n `Batch ${batchId} did not reach a terminal status within ${timeoutMs} ms ` +\n `(last status: ${result.data.status}).`,\n timeoutMs,\n );\n }\n await sleep(interval, options.signal);\n interval = Math.min(interval * DEFAULT_POLL_GROWTH, maxInterval);\n }\n }\n\n /**\n * Downloads the ZIP archive of a completed batch's successful results.\n * The batch must be in `succeeded`, `partially_succeeded`, or `failed`\n * state and contain at least one successful file.\n */\n async downloadBatchArchive(\n batchId: string,\n options: Pick<RequestOptions, \"signal\"> = {},\n ): Promise<Blob> {\n const result = await this.http.request({\n method: \"GET\",\n path: `/api/v1/batches/${encodeURIComponent(batchId)}/archive`,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n return result.response.blob();\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async imageOperation(\n operation: \"compress\" | \"resize\" | \"crop\" | \"convert\",\n input: TinifyInput,\n fields: Record<string, string | number | boolean | undefined>,\n options: RequestOptions,\n ): Promise<TinifyResponse<ImageResultData>> {\n const { blob, filename } = await normalizeInput(input, options.filename);\n const makeForm = (): FormData => {\n const form = new FormData();\n form.append(\"file\", blob, filename);\n for (const [key, value] of Object.entries(fields)) {\n if (value !== undefined) form.append(key, String(value));\n }\n return form;\n };\n const { body, requestId, rateLimit } = await this.http.requestJson<ImageEnvelope>({\n method: \"POST\",\n path: `/api/v1/images/${operation}`,\n body: makeForm,\n idempotencyKey: options.idempotencyKey ?? \"auto\",\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n return { data: body.data, requestId, rateLimit };\n }\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { a as TinifyClientOptions, C as CompressOptions, R as RequestOptions, b as TinifyResponse, I as ImageResultData, c as ResizeOptions, d as CropOptions, e as ConvertOptions, U as Usage, f as CreateBatchParams, B as BatchUploadSession, g as UploadBatchFilesOptions, h as CommitBatchResult, i as Batch, W as WaitForBatchOptions, j as TinifyErrorCode, k as BatchStatus, l as BatchTerminalStatus, F as FetchFunction } from './types-D58KVL3U.cjs';
|
|
2
|
+
export { m as BATCH_TERMINAL_STATUSES, n as BatchContentType, o as BatchFile, p as BatchFileError, q as BatchFileManifestEntry, r as BatchOperation, s as BatchUpload, D as DEFAULT_BASE_URL, t as ImageOperation, K as KnownTinifyErrorCode, M as MAX_BATCH_FILES, u as MAX_FILE_BYTES, Q as QualityMode, v as RateLimitInfo, T as TargetFormat } from './types-D58KVL3U.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Anything the client accepts as an image input:
|
|
6
|
+
* - a file path (Node.js only),
|
|
7
|
+
* - raw bytes (`Buffer`, `Uint8Array`, `ArrayBuffer`),
|
|
8
|
+
* - a `Blob` / `File`.
|
|
9
|
+
*/
|
|
10
|
+
type TinifyInput = string | Uint8Array | ArrayBuffer | Blob;
|
|
11
|
+
interface NormalizedInput {
|
|
12
|
+
blob: Blob;
|
|
13
|
+
filename: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Normalizes any {@link TinifyInput} into a `Blob` plus multipart filename.
|
|
17
|
+
* File paths lazily import `node:fs` so browser bundles never pull it in;
|
|
18
|
+
* passing a path outside Node.js throws a clear error instead.
|
|
19
|
+
*/
|
|
20
|
+
declare function normalizeInput(input: TinifyInput, filename?: string): Promise<NormalizedInput>;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Client for the Tinify.dev image API (https://tinify.dev/developers).
|
|
24
|
+
*
|
|
25
|
+
* Zero runtime dependencies; uses the platform `fetch`, `FormData`, and
|
|
26
|
+
* `Blob`. Works in Node.js >= 20. Browser use is limited to trusted origins:
|
|
27
|
+
* the API rejects untrusted browser origins, so call it server-side.
|
|
28
|
+
*/
|
|
29
|
+
declare class TinifyClient {
|
|
30
|
+
private readonly http;
|
|
31
|
+
constructor(options?: TinifyClientOptions);
|
|
32
|
+
/** Compresses an image. Never returns more bytes than the input. */
|
|
33
|
+
compress(input: TinifyInput, options?: CompressOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
34
|
+
/** Resizes an image by width/height/scale. */
|
|
35
|
+
resize(input: TinifyInput, options?: ResizeOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
36
|
+
/** Crops an image to the given rectangle. */
|
|
37
|
+
crop(input: TinifyInput, options: CropOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
38
|
+
/**
|
|
39
|
+
* Converts an image to another format (AVIF, WebP, JPEG, or PNG).
|
|
40
|
+
*
|
|
41
|
+
* @beta The `/api/v1/images/convert` endpoint is rolling out server-side
|
|
42
|
+
* and may not be available on every account yet.
|
|
43
|
+
*/
|
|
44
|
+
convert(input: TinifyInput, options: ConvertOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
45
|
+
/** Returns the account's current billing-period usage. */
|
|
46
|
+
usage(options?: Pick<RequestOptions, "signal">): Promise<TinifyResponse<Usage>>;
|
|
47
|
+
/**
|
|
48
|
+
* Downloads a result as a `Blob`. Accepts a result object, a response
|
|
49
|
+
* envelope, or a download URL. Download URLs are unauthenticated and
|
|
50
|
+
* expire two hours after the operation.
|
|
51
|
+
*/
|
|
52
|
+
download(resultOrUrl: string | ImageResultData | TinifyResponse<ImageResultData>, options?: Pick<RequestOptions, "signal">): Promise<Blob>;
|
|
53
|
+
/**
|
|
54
|
+
* Creates a durable batch. Returns one presigned upload slot per file;
|
|
55
|
+
* upload the bytes, then {@link commitBatch}. Requires a paid plan.
|
|
56
|
+
*/
|
|
57
|
+
createBatch(params: CreateBatchParams, options?: RequestOptions): Promise<TinifyResponse<BatchUploadSession>>;
|
|
58
|
+
/**
|
|
59
|
+
* Uploads file bytes to the presigned URLs of an upload session, keyed by
|
|
60
|
+
* `client_id`. Runs up to `concurrency` (default 4) PUTs in parallel.
|
|
61
|
+
*/
|
|
62
|
+
uploadBatchFiles(session: BatchUploadSession, files: Record<string, TinifyInput>, options?: UploadBatchFilesOptions): Promise<void>;
|
|
63
|
+
/** Commits an uploaded batch for processing. */
|
|
64
|
+
commitBatch(batchId: string, options?: RequestOptions): Promise<TinifyResponse<CommitBatchResult>>;
|
|
65
|
+
/** Fetches a batch with per-file state. */
|
|
66
|
+
getBatch(batchId: string, options?: Pick<RequestOptions, "signal">): Promise<TinifyResponse<Batch>>;
|
|
67
|
+
/** Cancels a batch. Idempotent: canceling a terminal batch is a no-op. */
|
|
68
|
+
cancelBatch(batchId: string, options?: Pick<RequestOptions, "signal">): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Polls {@link getBatch} until the batch reaches a terminal status
|
|
71
|
+
* (`succeeded`, `partially_succeeded`, `failed`, `canceled`, `expired`).
|
|
72
|
+
* Polls start at 1s and grow x1.5 up to 10s; gives up after `timeoutMs`
|
|
73
|
+
* (default 10 minutes) with a {@link TinifyTimeoutError}.
|
|
74
|
+
*/
|
|
75
|
+
waitForBatch(batchId: string, options?: WaitForBatchOptions): Promise<TinifyResponse<Batch>>;
|
|
76
|
+
/**
|
|
77
|
+
* Downloads the ZIP archive of a completed batch's successful results.
|
|
78
|
+
* The batch must be in `succeeded`, `partially_succeeded`, or `failed`
|
|
79
|
+
* state and contain at least one successful file.
|
|
80
|
+
*/
|
|
81
|
+
downloadBatchArchive(batchId: string, options?: Pick<RequestOptions, "signal">): Promise<Blob>;
|
|
82
|
+
private imageOperation;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Base class for every error thrown by this SDK. */
|
|
86
|
+
declare class TinifyError extends Error {
|
|
87
|
+
constructor(message: string, options?: ErrorOptions);
|
|
88
|
+
}
|
|
89
|
+
interface TinifyApiErrorInit {
|
|
90
|
+
status: number;
|
|
91
|
+
code: TinifyErrorCode;
|
|
92
|
+
message: string;
|
|
93
|
+
requestId: string;
|
|
94
|
+
details?: Record<string, unknown>;
|
|
95
|
+
/** Seconds to wait before retrying, parsed from Retry-After when present. */
|
|
96
|
+
retryAfter?: number;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A structured error envelope returned by the API:
|
|
100
|
+
* `{ error: { code, message, details }, request_id }`.
|
|
101
|
+
*/
|
|
102
|
+
declare class TinifyApiError extends TinifyError {
|
|
103
|
+
readonly status: number;
|
|
104
|
+
readonly code: TinifyErrorCode;
|
|
105
|
+
readonly requestId: string;
|
|
106
|
+
readonly details: Record<string, unknown>;
|
|
107
|
+
readonly retryAfter?: number;
|
|
108
|
+
constructor(init: TinifyApiErrorInit);
|
|
109
|
+
}
|
|
110
|
+
/** The request never produced an HTTP response (DNS, TLS, socket resets...). */
|
|
111
|
+
declare class TinifyNetworkError extends TinifyError {
|
|
112
|
+
constructor(message: string, options?: ErrorOptions);
|
|
113
|
+
}
|
|
114
|
+
/** A per-attempt timeout or a `waitForBatch` budget was exceeded. */
|
|
115
|
+
declare class TinifyTimeoutError extends TinifyError {
|
|
116
|
+
readonly timeoutMs: number;
|
|
117
|
+
constructor(message: string, timeoutMs: number);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
declare function isTerminalBatchStatus(status: BatchStatus): status is BatchTerminalStatus;
|
|
121
|
+
/**
|
|
122
|
+
* Uploads batch files to their presigned URLs.
|
|
123
|
+
*
|
|
124
|
+
* Each PUT sends the raw bytes with exactly the headers the API returned for
|
|
125
|
+
* that slot. The Authorization header is deliberately never sent: these are
|
|
126
|
+
* presigned object-storage URLs and an extra auth mechanism would be rejected.
|
|
127
|
+
*/
|
|
128
|
+
declare function uploadBatchFiles(fetchImpl: FetchFunction, session: BatchUploadSession, files: Record<string, TinifyInput>, options?: UploadBatchFilesOptions): Promise<void>;
|
|
129
|
+
|
|
130
|
+
export { Batch, BatchStatus, BatchTerminalStatus, BatchUploadSession, CommitBatchResult, CompressOptions, ConvertOptions, CreateBatchParams, CropOptions, FetchFunction, ImageResultData, type NormalizedInput, RequestOptions, ResizeOptions, TinifyApiError, type TinifyApiErrorInit, TinifyClient, TinifyClientOptions, TinifyError, TinifyErrorCode, type TinifyInput, TinifyNetworkError, TinifyResponse, TinifyTimeoutError, UploadBatchFilesOptions, Usage, WaitForBatchOptions, isTerminalBatchStatus, normalizeInput, uploadBatchFiles };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { a as TinifyClientOptions, C as CompressOptions, R as RequestOptions, b as TinifyResponse, I as ImageResultData, c as ResizeOptions, d as CropOptions, e as ConvertOptions, U as Usage, f as CreateBatchParams, B as BatchUploadSession, g as UploadBatchFilesOptions, h as CommitBatchResult, i as Batch, W as WaitForBatchOptions, j as TinifyErrorCode, k as BatchStatus, l as BatchTerminalStatus, F as FetchFunction } from './types-D58KVL3U.js';
|
|
2
|
+
export { m as BATCH_TERMINAL_STATUSES, n as BatchContentType, o as BatchFile, p as BatchFileError, q as BatchFileManifestEntry, r as BatchOperation, s as BatchUpload, D as DEFAULT_BASE_URL, t as ImageOperation, K as KnownTinifyErrorCode, M as MAX_BATCH_FILES, u as MAX_FILE_BYTES, Q as QualityMode, v as RateLimitInfo, T as TargetFormat } from './types-D58KVL3U.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Anything the client accepts as an image input:
|
|
6
|
+
* - a file path (Node.js only),
|
|
7
|
+
* - raw bytes (`Buffer`, `Uint8Array`, `ArrayBuffer`),
|
|
8
|
+
* - a `Blob` / `File`.
|
|
9
|
+
*/
|
|
10
|
+
type TinifyInput = string | Uint8Array | ArrayBuffer | Blob;
|
|
11
|
+
interface NormalizedInput {
|
|
12
|
+
blob: Blob;
|
|
13
|
+
filename: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Normalizes any {@link TinifyInput} into a `Blob` plus multipart filename.
|
|
17
|
+
* File paths lazily import `node:fs` so browser bundles never pull it in;
|
|
18
|
+
* passing a path outside Node.js throws a clear error instead.
|
|
19
|
+
*/
|
|
20
|
+
declare function normalizeInput(input: TinifyInput, filename?: string): Promise<NormalizedInput>;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Client for the Tinify.dev image API (https://tinify.dev/developers).
|
|
24
|
+
*
|
|
25
|
+
* Zero runtime dependencies; uses the platform `fetch`, `FormData`, and
|
|
26
|
+
* `Blob`. Works in Node.js >= 20. Browser use is limited to trusted origins:
|
|
27
|
+
* the API rejects untrusted browser origins, so call it server-side.
|
|
28
|
+
*/
|
|
29
|
+
declare class TinifyClient {
|
|
30
|
+
private readonly http;
|
|
31
|
+
constructor(options?: TinifyClientOptions);
|
|
32
|
+
/** Compresses an image. Never returns more bytes than the input. */
|
|
33
|
+
compress(input: TinifyInput, options?: CompressOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
34
|
+
/** Resizes an image by width/height/scale. */
|
|
35
|
+
resize(input: TinifyInput, options?: ResizeOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
36
|
+
/** Crops an image to the given rectangle. */
|
|
37
|
+
crop(input: TinifyInput, options: CropOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
38
|
+
/**
|
|
39
|
+
* Converts an image to another format (AVIF, WebP, JPEG, or PNG).
|
|
40
|
+
*
|
|
41
|
+
* @beta The `/api/v1/images/convert` endpoint is rolling out server-side
|
|
42
|
+
* and may not be available on every account yet.
|
|
43
|
+
*/
|
|
44
|
+
convert(input: TinifyInput, options: ConvertOptions & RequestOptions): Promise<TinifyResponse<ImageResultData>>;
|
|
45
|
+
/** Returns the account's current billing-period usage. */
|
|
46
|
+
usage(options?: Pick<RequestOptions, "signal">): Promise<TinifyResponse<Usage>>;
|
|
47
|
+
/**
|
|
48
|
+
* Downloads a result as a `Blob`. Accepts a result object, a response
|
|
49
|
+
* envelope, or a download URL. Download URLs are unauthenticated and
|
|
50
|
+
* expire two hours after the operation.
|
|
51
|
+
*/
|
|
52
|
+
download(resultOrUrl: string | ImageResultData | TinifyResponse<ImageResultData>, options?: Pick<RequestOptions, "signal">): Promise<Blob>;
|
|
53
|
+
/**
|
|
54
|
+
* Creates a durable batch. Returns one presigned upload slot per file;
|
|
55
|
+
* upload the bytes, then {@link commitBatch}. Requires a paid plan.
|
|
56
|
+
*/
|
|
57
|
+
createBatch(params: CreateBatchParams, options?: RequestOptions): Promise<TinifyResponse<BatchUploadSession>>;
|
|
58
|
+
/**
|
|
59
|
+
* Uploads file bytes to the presigned URLs of an upload session, keyed by
|
|
60
|
+
* `client_id`. Runs up to `concurrency` (default 4) PUTs in parallel.
|
|
61
|
+
*/
|
|
62
|
+
uploadBatchFiles(session: BatchUploadSession, files: Record<string, TinifyInput>, options?: UploadBatchFilesOptions): Promise<void>;
|
|
63
|
+
/** Commits an uploaded batch for processing. */
|
|
64
|
+
commitBatch(batchId: string, options?: RequestOptions): Promise<TinifyResponse<CommitBatchResult>>;
|
|
65
|
+
/** Fetches a batch with per-file state. */
|
|
66
|
+
getBatch(batchId: string, options?: Pick<RequestOptions, "signal">): Promise<TinifyResponse<Batch>>;
|
|
67
|
+
/** Cancels a batch. Idempotent: canceling a terminal batch is a no-op. */
|
|
68
|
+
cancelBatch(batchId: string, options?: Pick<RequestOptions, "signal">): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Polls {@link getBatch} until the batch reaches a terminal status
|
|
71
|
+
* (`succeeded`, `partially_succeeded`, `failed`, `canceled`, `expired`).
|
|
72
|
+
* Polls start at 1s and grow x1.5 up to 10s; gives up after `timeoutMs`
|
|
73
|
+
* (default 10 minutes) with a {@link TinifyTimeoutError}.
|
|
74
|
+
*/
|
|
75
|
+
waitForBatch(batchId: string, options?: WaitForBatchOptions): Promise<TinifyResponse<Batch>>;
|
|
76
|
+
/**
|
|
77
|
+
* Downloads the ZIP archive of a completed batch's successful results.
|
|
78
|
+
* The batch must be in `succeeded`, `partially_succeeded`, or `failed`
|
|
79
|
+
* state and contain at least one successful file.
|
|
80
|
+
*/
|
|
81
|
+
downloadBatchArchive(batchId: string, options?: Pick<RequestOptions, "signal">): Promise<Blob>;
|
|
82
|
+
private imageOperation;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Base class for every error thrown by this SDK. */
|
|
86
|
+
declare class TinifyError extends Error {
|
|
87
|
+
constructor(message: string, options?: ErrorOptions);
|
|
88
|
+
}
|
|
89
|
+
interface TinifyApiErrorInit {
|
|
90
|
+
status: number;
|
|
91
|
+
code: TinifyErrorCode;
|
|
92
|
+
message: string;
|
|
93
|
+
requestId: string;
|
|
94
|
+
details?: Record<string, unknown>;
|
|
95
|
+
/** Seconds to wait before retrying, parsed from Retry-After when present. */
|
|
96
|
+
retryAfter?: number;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A structured error envelope returned by the API:
|
|
100
|
+
* `{ error: { code, message, details }, request_id }`.
|
|
101
|
+
*/
|
|
102
|
+
declare class TinifyApiError extends TinifyError {
|
|
103
|
+
readonly status: number;
|
|
104
|
+
readonly code: TinifyErrorCode;
|
|
105
|
+
readonly requestId: string;
|
|
106
|
+
readonly details: Record<string, unknown>;
|
|
107
|
+
readonly retryAfter?: number;
|
|
108
|
+
constructor(init: TinifyApiErrorInit);
|
|
109
|
+
}
|
|
110
|
+
/** The request never produced an HTTP response (DNS, TLS, socket resets...). */
|
|
111
|
+
declare class TinifyNetworkError extends TinifyError {
|
|
112
|
+
constructor(message: string, options?: ErrorOptions);
|
|
113
|
+
}
|
|
114
|
+
/** A per-attempt timeout or a `waitForBatch` budget was exceeded. */
|
|
115
|
+
declare class TinifyTimeoutError extends TinifyError {
|
|
116
|
+
readonly timeoutMs: number;
|
|
117
|
+
constructor(message: string, timeoutMs: number);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
declare function isTerminalBatchStatus(status: BatchStatus): status is BatchTerminalStatus;
|
|
121
|
+
/**
|
|
122
|
+
* Uploads batch files to their presigned URLs.
|
|
123
|
+
*
|
|
124
|
+
* Each PUT sends the raw bytes with exactly the headers the API returned for
|
|
125
|
+
* that slot. The Authorization header is deliberately never sent: these are
|
|
126
|
+
* presigned object-storage URLs and an extra auth mechanism would be rejected.
|
|
127
|
+
*/
|
|
128
|
+
declare function uploadBatchFiles(fetchImpl: FetchFunction, session: BatchUploadSession, files: Record<string, TinifyInput>, options?: UploadBatchFilesOptions): Promise<void>;
|
|
129
|
+
|
|
130
|
+
export { Batch, BatchStatus, BatchTerminalStatus, BatchUploadSession, CommitBatchResult, CompressOptions, ConvertOptions, CreateBatchParams, CropOptions, FetchFunction, ImageResultData, type NormalizedInput, RequestOptions, ResizeOptions, TinifyApiError, type TinifyApiErrorInit, TinifyClient, TinifyClientOptions, TinifyError, TinifyErrorCode, type TinifyInput, TinifyNetworkError, TinifyResponse, TinifyTimeoutError, UploadBatchFilesOptions, Usage, WaitForBatchOptions, isTerminalBatchStatus, normalizeInput, uploadBatchFiles };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { BATCH_TERMINAL_STATUSES, DEFAULT_BASE_URL, MAX_BATCH_FILES, MAX_FILE_BYTES, TinifyApiError, TinifyClient, TinifyError, TinifyNetworkError, TinifyTimeoutError, isTerminalBatchStatus, normalizeInput, uploadBatchFiles } from './chunk-NYRKB5BB.js';
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/** Default API origin. Override with `baseUrl` or the `TINIFY_BASE_URL` env var. */
|
|
2
|
+
declare const DEFAULT_BASE_URL = "https://api.tinify.dev";
|
|
3
|
+
/** Maximum accepted image size in bytes (40 MiB), matching the server limit. */
|
|
4
|
+
declare const MAX_FILE_BYTES = 41943040;
|
|
5
|
+
/** Maximum number of files per batch. */
|
|
6
|
+
declare const MAX_BATCH_FILES = 200;
|
|
7
|
+
/** Batch statuses that will never change again. */
|
|
8
|
+
declare const BATCH_TERMINAL_STATUSES: readonly ["succeeded", "partially_succeeded", "failed", "canceled", "expired"];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Error codes the API is known to return. The union stays open (`string`)
|
|
12
|
+
* because the server may add codes without a client release.
|
|
13
|
+
*/
|
|
14
|
+
type KnownTinifyErrorCode = "missing_authorization" | "invalid_api_key" | "missing_identity" | "insufficient_scope" | "account_unavailable" | "invalid_request" | "invalid_idempotency_key" | "idempotency_conflict" | "validation_failed" | "file_too_large" | "unsupported_media_type" | "invalid_quality_mode" | "lossless_not_supported" | "invalid_resize" | "invalid_crop" | "invalid_operation" | "quota_exhausted" | "too_many_upload_sessions" | "upload_session_storage_limit" | "batch_not_found" | "batch_too_large" | "batch_plan_required" | "batch_not_complete" | "batch_has_no_results" | "uploads_incomplete" | "duplicate_client_id" | "invalid_target_format" | "same_format_conversion" | "invalid_target_size" | "target_size_conflict" | "internal_error";
|
|
15
|
+
type TinifyErrorCode = KnownTinifyErrorCode | (string & {});
|
|
16
|
+
type QualityMode = "balanced" | "best_quality" | "lossless";
|
|
17
|
+
/**
|
|
18
|
+
* Output format for {@link TinifyClient.convert}.
|
|
19
|
+
*
|
|
20
|
+
* @beta The `/api/v1/images/convert` endpoint is rolling out server-side and
|
|
21
|
+
* may not be enabled for every account yet.
|
|
22
|
+
*/
|
|
23
|
+
type TargetFormat = "avif" | "webp" | "jpeg" | "png";
|
|
24
|
+
type ImageOperation = "compress" | "resize" | "crop" | "convert";
|
|
25
|
+
/** Values of the X-RateLimit-* response headers. `reset` is epoch seconds. */
|
|
26
|
+
interface RateLimitInfo {
|
|
27
|
+
limit: number;
|
|
28
|
+
remaining: number;
|
|
29
|
+
reset: number;
|
|
30
|
+
}
|
|
31
|
+
/** Envelope returned by every client call. */
|
|
32
|
+
interface TinifyResponse<T> {
|
|
33
|
+
data: T;
|
|
34
|
+
/** Server request id (`request_id` body field or `X-Request-Id` header). */
|
|
35
|
+
requestId: string;
|
|
36
|
+
/** Parsed X-RateLimit-* headers, or `null` when the server omitted them. */
|
|
37
|
+
rateLimit: RateLimitInfo | null;
|
|
38
|
+
}
|
|
39
|
+
/** `data` object of a successful synchronous image operation. */
|
|
40
|
+
interface ImageResultData {
|
|
41
|
+
job_id: string;
|
|
42
|
+
operation?: ImageOperation;
|
|
43
|
+
status: "succeeded";
|
|
44
|
+
/**
|
|
45
|
+
* `true` when the result is smaller than the input, `false` when the API
|
|
46
|
+
* returned the original bytes because it could not shrink them, `null`
|
|
47
|
+
* when the concept does not apply (resize/crop).
|
|
48
|
+
*/
|
|
49
|
+
optimized: boolean | null;
|
|
50
|
+
/**
|
|
51
|
+
* Whether the result met the requested byte budget. Present only when
|
|
52
|
+
* compress ran with `target_size_bytes`.
|
|
53
|
+
*/
|
|
54
|
+
target_size_achieved?: boolean;
|
|
55
|
+
quality_mode?: string;
|
|
56
|
+
original_format?: string;
|
|
57
|
+
result_format?: string;
|
|
58
|
+
original_bytes: number;
|
|
59
|
+
result_bytes: number;
|
|
60
|
+
/** Positive means the result grew. */
|
|
61
|
+
byte_change_percent?: number;
|
|
62
|
+
width: number | null;
|
|
63
|
+
height: number | null;
|
|
64
|
+
duration_ms?: number;
|
|
65
|
+
/** Expires two hours after the operation completes. */
|
|
66
|
+
download_url: string;
|
|
67
|
+
expires_at: string;
|
|
68
|
+
}
|
|
69
|
+
/** GET /api/v1/usage response body. */
|
|
70
|
+
interface Usage {
|
|
71
|
+
plan: string;
|
|
72
|
+
period_start: string;
|
|
73
|
+
period_end: string;
|
|
74
|
+
included: number;
|
|
75
|
+
reserved: number;
|
|
76
|
+
used: number;
|
|
77
|
+
remaining: number;
|
|
78
|
+
}
|
|
79
|
+
interface CompressOptions {
|
|
80
|
+
quality_mode?: QualityMode;
|
|
81
|
+
/**
|
|
82
|
+
* Ask the encoder to aim for a result at or below this many bytes.
|
|
83
|
+
*
|
|
84
|
+
* @beta Depends on a server rollout; accounts without it receive
|
|
85
|
+
* `validation_failed` or the parameter is ignored.
|
|
86
|
+
*/
|
|
87
|
+
target_size_bytes?: number;
|
|
88
|
+
}
|
|
89
|
+
interface ResizeOptions {
|
|
90
|
+
width?: number;
|
|
91
|
+
height?: number;
|
|
92
|
+
scale?: number;
|
|
93
|
+
keep_aspect_ratio?: boolean;
|
|
94
|
+
optimize?: boolean;
|
|
95
|
+
}
|
|
96
|
+
interface CropOptions {
|
|
97
|
+
x: number;
|
|
98
|
+
y: number;
|
|
99
|
+
width: number;
|
|
100
|
+
height: number;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Options for {@link TinifyClient.convert}.
|
|
104
|
+
*
|
|
105
|
+
* @beta The convert endpoint is rolling out server-side.
|
|
106
|
+
*/
|
|
107
|
+
interface ConvertOptions {
|
|
108
|
+
format: TargetFormat;
|
|
109
|
+
quality_mode?: QualityMode;
|
|
110
|
+
}
|
|
111
|
+
/** Per-call options accepted by every network method. */
|
|
112
|
+
interface RequestOptions {
|
|
113
|
+
/**
|
|
114
|
+
* Override the auto-generated Idempotency-Key (8-160 chars). The same key
|
|
115
|
+
* is reused for every retry of the call.
|
|
116
|
+
*/
|
|
117
|
+
idempotencyKey?: string;
|
|
118
|
+
/** Abort the call (including retries and waits). */
|
|
119
|
+
signal?: AbortSignal;
|
|
120
|
+
/** Multipart filename override for buffer/blob inputs. */
|
|
121
|
+
filename?: string;
|
|
122
|
+
}
|
|
123
|
+
type BatchOperation = "compress" | "resize" | "crop" | "convert";
|
|
124
|
+
type BatchStatus = "awaiting_upload" | "queued" | "processing" | "succeeded" | "partially_succeeded" | "failed" | "canceled" | "expired";
|
|
125
|
+
type BatchTerminalStatus = (typeof BATCH_TERMINAL_STATUSES)[number];
|
|
126
|
+
type BatchContentType = "image/jpeg" | "image/png" | "image/webp" | "image/avif";
|
|
127
|
+
/** One manifest entry sent to POST /api/v1/batches. */
|
|
128
|
+
interface BatchFileManifestEntry {
|
|
129
|
+
/** Your identifier for the file; must be unique within the batch. */
|
|
130
|
+
client_id: string;
|
|
131
|
+
filename: string;
|
|
132
|
+
/** Exact size of the bytes you will PUT (1..41943040). */
|
|
133
|
+
size_bytes: number;
|
|
134
|
+
content_type: BatchContentType;
|
|
135
|
+
}
|
|
136
|
+
interface CreateBatchParams {
|
|
137
|
+
operation: BatchOperation;
|
|
138
|
+
/**
|
|
139
|
+
* Operation options, mirroring the synchronous endpoints:
|
|
140
|
+
*
|
|
141
|
+
* - `convert` requires {@link ConvertOptions.format}; files already in the
|
|
142
|
+
* target format fail per job with `same_format_conversion`.
|
|
143
|
+
* - `compress` accepts `quality_mode` and `target_size_bytes`; the target
|
|
144
|
+
* size is skipped per job when it is not smaller than that job's input.
|
|
145
|
+
*/
|
|
146
|
+
options: CompressOptions | ResizeOptions | CropOptions | ConvertOptions | Record<string, unknown>;
|
|
147
|
+
files: BatchFileManifestEntry[];
|
|
148
|
+
}
|
|
149
|
+
/** Presigned upload slot returned when a batch is created. */
|
|
150
|
+
interface BatchUpload {
|
|
151
|
+
file_id: string;
|
|
152
|
+
client_id: string;
|
|
153
|
+
upload_url: string;
|
|
154
|
+
/** Send these headers verbatim on the PUT. Do NOT add Authorization. */
|
|
155
|
+
headers: Record<string, string>;
|
|
156
|
+
}
|
|
157
|
+
interface BatchUploadSession {
|
|
158
|
+
id: string;
|
|
159
|
+
status: "awaiting_upload";
|
|
160
|
+
expires_at: string;
|
|
161
|
+
uploads: BatchUpload[];
|
|
162
|
+
}
|
|
163
|
+
interface BatchFileError {
|
|
164
|
+
code: TinifyErrorCode;
|
|
165
|
+
}
|
|
166
|
+
interface BatchFile {
|
|
167
|
+
id: string;
|
|
168
|
+
client_id: string;
|
|
169
|
+
filename: string;
|
|
170
|
+
status: string;
|
|
171
|
+
original_bytes: number | null;
|
|
172
|
+
result_bytes: number | null;
|
|
173
|
+
optimized: boolean | null;
|
|
174
|
+
duration_ms: number | null;
|
|
175
|
+
error: BatchFileError | null;
|
|
176
|
+
/** Signed download URL; present only once the batch reached a result state. */
|
|
177
|
+
download_url: string | null;
|
|
178
|
+
}
|
|
179
|
+
interface Batch {
|
|
180
|
+
id: string;
|
|
181
|
+
operation: BatchOperation;
|
|
182
|
+
status: BatchStatus;
|
|
183
|
+
expires_at: string;
|
|
184
|
+
files: BatchFile[];
|
|
185
|
+
}
|
|
186
|
+
/** POST /api/v1/batches/{id}/commit response body. */
|
|
187
|
+
interface CommitBatchResult {
|
|
188
|
+
id: string;
|
|
189
|
+
status: BatchStatus;
|
|
190
|
+
}
|
|
191
|
+
interface UploadBatchFilesOptions {
|
|
192
|
+
/** Parallel presigned PUTs. Default 4. */
|
|
193
|
+
concurrency?: number;
|
|
194
|
+
signal?: AbortSignal;
|
|
195
|
+
}
|
|
196
|
+
interface WaitForBatchOptions {
|
|
197
|
+
/** First poll delay in milliseconds. Default 1000. */
|
|
198
|
+
pollIntervalMs?: number;
|
|
199
|
+
/** Poll delay ceiling in milliseconds. Default 10000. */
|
|
200
|
+
maxPollIntervalMs?: number;
|
|
201
|
+
/** Total waiting budget in milliseconds. Default 600000 (10 minutes). */
|
|
202
|
+
timeoutMs?: number;
|
|
203
|
+
signal?: AbortSignal;
|
|
204
|
+
}
|
|
205
|
+
type FetchFunction = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
206
|
+
interface TinifyClientOptions {
|
|
207
|
+
/** API key (`tnf_live_*` or `tnf_test_*`). Falls back to TINIFY_API_KEY. */
|
|
208
|
+
apiKey?: string;
|
|
209
|
+
/** API origin. Falls back to TINIFY_BASE_URL, then https://api.tinify.dev. */
|
|
210
|
+
baseUrl?: string;
|
|
211
|
+
/** Retries after the initial attempt for 429/503/network failures. Default 3. */
|
|
212
|
+
maxRetries?: number;
|
|
213
|
+
/** Per-attempt timeout in milliseconds. Default 60000. */
|
|
214
|
+
timeoutMs?: number;
|
|
215
|
+
/** Injectable fetch implementation (used for testing and custom agents). */
|
|
216
|
+
fetch?: FetchFunction;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export { type BatchUploadSession as B, type CompressOptions as C, DEFAULT_BASE_URL as D, type FetchFunction as F, type ImageResultData as I, type KnownTinifyErrorCode as K, MAX_BATCH_FILES as M, type QualityMode as Q, type RequestOptions as R, type TargetFormat as T, type Usage as U, type WaitForBatchOptions as W, type TinifyClientOptions as a, type TinifyResponse as b, type ResizeOptions as c, type CropOptions as d, type ConvertOptions as e, type CreateBatchParams as f, type UploadBatchFilesOptions as g, type CommitBatchResult as h, type Batch as i, type TinifyErrorCode as j, type BatchStatus as k, type BatchTerminalStatus as l, BATCH_TERMINAL_STATUSES as m, type BatchContentType as n, type BatchFile as o, type BatchFileError as p, type BatchFileManifestEntry as q, type BatchOperation as r, type BatchUpload as s, type ImageOperation as t, MAX_FILE_BYTES as u, type RateLimitInfo as v };
|