@poof-bg/js 1.2.0 → 1.3.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/README.md CHANGED
@@ -60,7 +60,7 @@ const result = await poof.removeBackground(file, {
60
60
  padding: '10%', // Padding around the subject when cropping
61
61
  size: 'medium', // Size preset: 'full' | 'preview' | 'medium' | 'hd'
62
62
  channels: 'rgb', // 'rgba' for transparency, 'rgb' for opaque, 'alpha' for the mask
63
- bgColor: '#ffffff', // Background color (when channels is 'rgb' or 'rgba')
63
+ bgColor: '#ffffff', // Background for opaque output: channels 'rgb' or format 'jpg' (ignored when transparent)
64
64
  });
65
65
  ```
66
66
 
@@ -116,7 +116,9 @@ fs.writeFileSync('output.png', Buffer.from(result.data));
116
116
 
117
117
  ### Video
118
118
 
119
- Videos go through the same `removeBackground()` call. Because a clip takes a while to process, the call returns a `Job` instead of bytes: wait for it with `waitForJob()` (or pass `wait: true`), then download `resultUrl`. Output is a transparent VP9 WebM by default; `format` can also be `mov` (ProRes 4444 with alpha) or `mp4` (H.264, composited on `bgColor`, default white). Audio is kept. Each started second of video costs 5 credits (10 above 30 fps), charged when the job is accepted and refunded if it fails.
119
+ Videos go through the same `removeBackground()` call. Because a clip takes a while to process, the call returns a `Job` instead of bytes: wait for it with `waitForJob()` (or pass `wait: true`), then download `resultUrl`. Output is a transparent VP9 WebM by default; `format` can also be `mov` (ProRes 4444 with alpha), `mp4` (H.264, composited on `bgColor`, default white) or `gif` (looping GIF with 1-bit transparency and no audio, capped at 1280 px on the longest side (720p for widescreen) and 50 fps, for stickers and chat; pass `size: 'preview'` for sticker-sized output). Audio is kept, except for `gif` output and `channels: 'alpha'` (matte) output, which have no audio track. An animated GIF is accepted as input too and is processed as a video; a still GIF is handled like any other image. `crop`, `padding`, `width`, `height` and `fit` are image-only options.
120
+
121
+ **Pricing:** 5 credits per second of video, rounded up to the next whole second (10 credits per second above 30 fps). Animated GIF input is always 5 credits per second, whatever its frame rate. Credits are charged when the job is accepted and refunded automatically if it fails. If your remaining credits don't cover the whole clip, the upload is rejected with a 402 `payment_required` (`PaymentRequiredError`) and nothing is charged.
120
122
 
121
123
  ```typescript
122
124
  import { Poof } from '@poof-bg/js';
@@ -142,10 +144,10 @@ Shorter: `wait: true` submits and waits in one call.
142
144
 
143
145
  ```typescript
144
146
  const done = await poof.removeBackground('./clip.mp4', {
145
- format: 'mp4', // 'webm' (transparent) | 'mov' (transparent ProRes) | 'mp4' (opaque)
147
+ format: 'mp4', // 'webm' (transparent) | 'mov' (transparent ProRes) | 'mp4' (opaque) | 'gif' (1-bit transparent)
146
148
  channels: 'rgba', // 'rgba' | 'rgb' | 'alpha' (grayscale matte video, no audio)
147
- bgColor: '#00ff00', // Background for opaque output (mp4 or channels 'rgb'); default white
148
- size: 'hd', // Longest side cap; video output never exceeds 1080p
149
+ bgColor: '#00ff00', // Background for opaque output (mp4 or channels 'rgb'); default white; ignored when transparent
150
+ size: 'hd', // Longest side cap: 640 / 1280 / 1920 (hd); 'full' keeps the source up to 4K
149
151
  wait: { pollIntervalMs: 5000, timeoutMs: 15 * 60 * 1000 },
150
152
  });
151
153
  ```
@@ -177,7 +179,9 @@ if (isJob(result)) {
177
179
  }
178
180
  ```
179
181
 
180
- A failed job makes `waitForJob()` throw a `PoofError` with code `job_failed`; the credits are refunded automatically. Jobs are limited to 5 minutes of video.
182
+ A failed job makes `waitForJob()` throw a `PoofError` with code `job_failed`; the credits are refunded automatically.
183
+
184
+ Limits: up to 5 minutes of video, 100 MB per upload, 500 MB when submitted by `{ url }`.
181
185
 
182
186
  ### Account Information
183
187
 
@@ -220,11 +224,12 @@ try {
220
224
  if (error instanceof AuthenticationError) {
221
225
  console.error('Invalid API key');
222
226
  } else if (error instanceof PaymentRequiredError) {
223
- console.error('Insufficient credits');
227
+ console.error('Insufficient credits (for video: not enough left for the whole clip)');
224
228
  } else if (error instanceof RateLimitError) {
225
229
  console.error('Rate limit exceeded, retry later');
226
230
  } else if (error instanceof ValidationError) {
227
- console.error('Invalid input:', error.details);
231
+ console.error('Invalid input:', error.details); // e.g. { field: 'crop' }
232
+ console.error('Docs:', error.docUrl);
228
233
  } else if (error instanceof PoofError && error.code === 'job_failed') {
229
234
  console.error('Video job failed, credits refunded:', error.message);
230
235
  } else if (error instanceof PoofError) {
@@ -258,7 +263,7 @@ const poof = new Poof({
258
263
  | File path (string) | ❌ | ✅ |
259
264
  | `{ url: string }` (public https URL) | ✅ | ✅ |
260
265
 
261
- Images: PNG, JPEG, WebP, GIF (first frame), up to 20 MB. Videos: MP4, MOV, WebM, MKV, up to 100 MB uploaded or 500 MB by URL, up to 5 minutes.
266
+ Images: PNG, JPEG, WebP or a still (single-frame) GIF, up to 20 MB. Videos: MP4, MOV, WebM, M4V, MKV, animated GIF (two or more frames), up to 100 MB uploaded or 500 MB by URL, up to 5 minutes.
262
267
 
263
268
  ## TypeScript
264
269
 
package/dist/index.cjs CHANGED
@@ -8,8 +8,10 @@ var PoofError = class _PoofError extends Error {
8
8
  status;
9
9
  /** Unique request ID for support */
10
10
  requestId;
11
- /** Additional details */
11
+ /** Additional details: an object for validation errors (e.g. { field: 'crop' }), or a string */
12
12
  details;
13
+ /** Link to the documentation page for this error code */
14
+ docUrl;
13
15
  constructor(message, code, options) {
14
16
  super(message);
15
17
  this.name = "PoofError";
@@ -17,6 +19,7 @@ var PoofError = class _PoofError extends Error {
17
19
  this.status = options?.status;
18
20
  this.requestId = options?.requestId;
19
21
  this.details = options?.details;
22
+ this.docUrl = options?.docUrl;
20
23
  if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
21
24
  Error.captureStackTrace(this, this.constructor);
22
25
  }
@@ -27,7 +30,8 @@ var PoofError = class _PoofError extends Error {
27
30
  return new ErrorClass(response.message, response.code, {
28
31
  status,
29
32
  requestId: response.request_id,
30
- details: response.details
33
+ details: response.details,
34
+ docUrl: response.doc_url
31
35
  });
32
36
  }
33
37
  };
@@ -76,6 +80,8 @@ var ERROR_MAP = {
76
80
  missing_image: ValidationError,
77
81
  image_too_large: ValidationError,
78
82
  invalid_image: ValidationError,
83
+ processing_failed: ServerError,
84
+ not_found: PoofError,
79
85
  video_too_large: ValidationError,
80
86
  video_too_long: ValidationError,
81
87
  invalid_video: ValidationError,
@@ -251,7 +257,8 @@ var Poof = class {
251
257
  if (options.channels) formData.append("channels", options.channels);
252
258
  if (options.bgColor) formData.append("bg_color", options.bgColor);
253
259
  if (options.size) formData.append("size", options.size);
254
- if (options.crop !== void 0) formData.append("crop", String(options.crop));
260
+ if (options.crop === true) formData.append("crop", "true");
261
+ else if (typeof options.crop === "string" && options.crop) formData.append("crop", options.crop);
255
262
  if (options.padding) formData.append("padding", options.padding);
256
263
  if (options.width !== void 0) formData.append("width", String(options.width));
257
264
  if (options.height !== void 0) formData.append("height", String(options.height));
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/client.ts"],"names":[],"mappings":";;;AAKO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA;AAAA,EAE1B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,OAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,IAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,SAAS,OAAA,EAAS,MAAA;AACvB,IAAA,IAAA,CAAK,YAAY,OAAA,EAAS,SAAA;AAC1B,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AAGxB,IAAA,IAAI,mBAAA,IAAuB,KAAA,IAAS,OAAO,KAAA,CAAM,sBAAsB,UAAA,EAAY;AACjF,MAAA,KAAA,CAAM,iBAAA,CAAkB,IAAA,EAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IAChD;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A;AAAA,IACZ,QAAA,EAAU,IAAI,QAAA,IAAY,CAAA;AAAA,IAC1B,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,WAAA,EAAa,IAAI,YAAA,IAAgB,IAAA;AAAA,IACjC,iBAAiB,GAAA,CAAI,gBAAA;AAAA,IACrB,KAAK,GAAA,CAAI,GAAA;AAAA,IACT,OAAO,GAAA,CAAI,KAAA;AAAA,IACX,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,UAAU,GAAA,CAAI,QAAA;AAAA,IACd,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,KAAA,EAAO,IAAI,KAAA,IAAS,IAAA;AAAA,IACpB,KAAA,EAAO,IAAI,KAAA,IAAS;AAAA,GACtB;AACF","file":"index.cjs","sourcesContent":["import type { ErrorCode, ApiErrorResponse } from './types.js';\n\n/**\n * Base error class for all Poof SDK errors\n */\nexport class PoofError extends Error {\n /** Machine-readable error code */\n readonly code: string;\n /** HTTP status code */\n readonly status?: number;\n /** Unique request ID for support */\n readonly requestId?: string;\n /** Additional details */\n readonly details?: string;\n\n constructor(\n message: string,\n code: string,\n options?: { status?: number; requestId?: string; details?: string }\n ) {\n super(message);\n this.name = 'PoofError';\n this.code = code;\n this.status = options?.status;\n this.requestId = options?.requestId;\n this.details = options?.details;\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /** Create error from API response */\n static fromResponse(response: ApiErrorResponse, status: number): PoofError {\n const ErrorClass = ERROR_MAP[response.code] || PoofError;\n return new ErrorClass(response.message, response.code, {\n status,\n requestId: response.request_id,\n details: response.details,\n });\n }\n}\n\n/**\n * Thrown when the API key is invalid or missing\n */\nexport class AuthenticationError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown when the account doesn't have permission\n */\nexport class PermissionError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'PermissionError';\n }\n}\n\n/**\n * Thrown when the account has insufficient credits\n */\nexport class PaymentRequiredError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'PaymentRequiredError';\n }\n}\n\n/**\n * Thrown when rate limit is exceeded\n */\nexport class RateLimitError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Thrown when request parameters are invalid\n */\nexport class ValidationError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Thrown when a server error occurs\n */\nexport class ServerError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'ServerError';\n }\n}\n\n/** Map error codes to error classes */\nconst ERROR_MAP: Record<ErrorCode, typeof PoofError> = {\n authentication_error: AuthenticationError,\n permission_denied: PermissionError,\n payment_required: PaymentRequiredError,\n rate_limit_exceeded: RateLimitError,\n validation_error: ValidationError,\n missing_image: ValidationError,\n image_too_large: ValidationError,\n invalid_image: ValidationError,\n video_too_large: ValidationError,\n video_too_long: ValidationError,\n invalid_video: ValidationError,\n job_not_found: ValidationError,\n job_failed: PoofError,\n upstream_error: ServerError,\n internal_server_error: ServerError,\n};\n","import type { ImageInput, MediaInput, UrlInput } from './types.js';\n\n/** Check if running in Node.js environment */\nexport const isNode = typeof process !== 'undefined' && process.versions?.node;\n\n/** Detect MIME type from buffer */\nfunction detectMimeType(buffer: Uint8Array): string {\n // Check magic bytes\n if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {\n return 'image/png';\n }\n if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {\n return 'image/jpeg';\n }\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) {\n // RIFF header, check for WEBP\n if (buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {\n return 'image/webp';\n }\n }\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\n return 'image/gif';\n }\n // ISO base media file (MP4, MOV): 'ftyp' at offset 4\n if (buffer[4] === 0x66 && buffer[5] === 0x74 && buffer[6] === 0x79 && buffer[7] === 0x70) {\n // 'qt ' brand is QuickTime\n if (buffer[8] === 0x71 && buffer[9] === 0x74) {\n return 'video/quicktime';\n }\n return 'video/mp4';\n }\n // EBML header (WebM, Matroska)\n if (buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3) {\n return 'video/webm';\n }\n // Default to octet-stream\n return 'application/octet-stream';\n}\n\n/** Get file extension from MIME type */\nfunction getExtension(mimeType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'video/webm': 'webm',\n };\n return map[mimeType] || 'bin';\n}\n\n/** Convert various input types to a Blob suitable for FormData */\nexport async function toBlob(input: ImageInput): Promise<Blob> {\n // Already a Blob or File\n if (input instanceof Blob) {\n return input;\n }\n\n // ArrayBuffer\n if (input instanceof ArrayBuffer) {\n const uint8 = new Uint8Array(input);\n const mimeType = detectMimeType(uint8);\n return new Blob([input], { type: mimeType });\n }\n\n // Uint8Array or Node.js Buffer. Copy into a fresh ArrayBuffer-backed view:\n // a view over a SharedArrayBuffer (or a Buffer pool slice) is not a valid BlobPart.\n if (input instanceof Uint8Array || (isNode && Buffer.isBuffer(input))) {\n const bytes = Uint8Array.from(input);\n const mimeType = detectMimeType(bytes);\n return new Blob([bytes], { type: mimeType });\n }\n\n // String - treat as file path (Node.js only)\n if (typeof input === 'string') {\n if (!isNode) {\n throw new Error('File paths are only supported in Node.js. Use a Blob or File in the browser.');\n }\n \n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n \n const buffer = await fs.readFile(input);\n const uint8 = new Uint8Array(buffer);\n const mimeType = detectMimeType(uint8);\n const ext = path.extname(input).toLowerCase().slice(1);\n \n // Use file extension for mime type if available\n const mimeFromExt: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n mkv: 'video/x-matroska',\n };\n \n const finalMimeType = mimeFromExt[ext] || mimeType;\n return new Blob([buffer], { type: finalMimeType });\n }\n\n throw new Error(`Unsupported input type: ${typeof input}`);\n}\n\n/** Get filename for FormData */\nexport function getFilename(input: ImageInput, mimeType: string): string {\n // File has a name\n if (typeof File !== 'undefined' && input instanceof File) {\n return input.name;\n }\n\n // String path\n if (typeof input === 'string' && isNode) {\n // Extract filename from path\n const parts = input.split(/[/\\\\]/);\n return parts[parts.length - 1] || defaultFilename(mimeType);\n }\n\n // Generate name from mime type\n return defaultFilename(mimeType);\n}\n\nfunction defaultFilename(mimeType: string): string {\n const stem = mimeType.startsWith('video/') ? 'video' : 'image';\n return `${stem}.${getExtension(mimeType)}`;\n}\n\n/** Is the input a `{ url }` object rather than file contents? */\nexport function isUrlInput(input: MediaInput): input is UrlInput {\n return typeof input === 'object' && input !== null && 'url' in input && typeof (input as UrlInput).url === 'string';\n}\n\n/** Resolve after `ms` milliseconds */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import type {\n PoofOptions,\n MediaInput,\n RemoveBackgroundOptions,\n RemoveBackgroundResult,\n Job,\n JobStatus,\n WaitForJobOptions,\n AccountInfo,\n ApiErrorResponse,\n} from './types.js';\nimport { PoofError } from './errors.js';\nimport { toBlob, getFilename, isUrlInput, sleep } from './utils.js';\n\nconst DEFAULT_BASE_URL = 'https://api.poof.bg/v1';\nconst DEFAULT_TIMEOUT = 60000;\nconst DEFAULT_POLL_INTERVAL_MS = 3000;\nconst DEFAULT_JOB_TIMEOUT_MS = 600000;\n\n/**\n * Poof API client for background removal\n *\n * @example\n * ```typescript\n * import { Poof } from '@poof-bg/js';\n *\n * const poof = new Poof({ apiKey: 'your-api-key' });\n * const result = await poof.removeBackground(imageFile);\n * ```\n */\nexport class Poof {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(options: PoofOptions) {\n if (!options.apiKey) {\n throw new Error('API key is required');\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl?.replace(/\\/$/, '') || DEFAULT_BASE_URL;\n this.timeout = options.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Remove the background from an image or a video.\n *\n * Images are processed synchronously and come back as bytes. Videos are\n * processed as a job: the call returns a queued {@link Job}; poll it with\n * {@link getJob} / {@link waitForJob}, or pass `wait: true` to get the\n * completed job (with `resultUrl`) directly. Use {@link isJob} to tell the\n * two apart.\n *\n * @param input - File, Blob, Buffer, ArrayBuffer, Uint8Array, file path (Node.js), or `{ url }`\n * @param options - Processing options\n * @returns Processed image data and metadata, or a video Job\n *\n * @example\n * ```typescript\n * // Image\n * const result = await poof.removeBackground(file);\n * const imageBlob = new Blob([result.data], { type: result.metadata.contentType });\n *\n * // With options\n * const result = await poof.removeBackground(file, { format: 'webp', crop: true, size: 'medium' });\n *\n * // Exact 500x500 output, subject cropped and centred, never stretched\n * const result = await poof.removeBackground(file, { crop: true, width: 500, height: 500 });\n *\n * // Video: submit, then wait for the result\n * const job = await poof.removeBackground('./clip.mp4', { format: 'webm' });\n * const done = await poof.waitForJob(job);\n * console.log(done.resultUrl);\n *\n * // Video from a public URL, waiting inline\n * const done = await poof.removeBackground({ url: 'https://example.com/clip.mp4' }, { wait: true });\n * ```\n */\n async removeBackground(\n input: MediaInput,\n options: RemoveBackgroundOptions = {}\n ): Promise<RemoveBackgroundResult | Job> {\n const formData = new FormData();\n\n if (isUrlInput(input)) {\n formData.append('url', input.url);\n } else {\n const blob = await toBlob(input);\n const filename = getFilename(input, blob.type);\n formData.append('file', blob, filename);\n }\n\n // Add optional parameters\n if (options.format) formData.append('format', options.format);\n if (options.channels) formData.append('channels', options.channels);\n if (options.bgColor) formData.append('bg_color', options.bgColor);\n if (options.size) formData.append('size', options.size);\n if (options.crop !== undefined) formData.append('crop', String(options.crop));\n if (options.padding) formData.append('padding', options.padding);\n if (options.width !== undefined) formData.append('width', String(options.width));\n if (options.height !== undefined) formData.append('height', String(options.height));\n if (options.fit) formData.append('fit', options.fit);\n\n const response = await this.fetch(`${this.baseUrl}/remove`, {\n method: 'POST',\n body: formData,\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n // Videos are accepted as a job\n if (response.status === 202) {\n const job = toJob(await response.json());\n if (options.wait) {\n return this.waitForJob(job, options.wait === true ? {} : options.wait);\n }\n return job;\n }\n\n const data = await response.arrayBuffer();\n\n const matteConfidence = response.headers.get('X-Matte-Confidence');\n const matteAmbiguousRatio = response.headers.get('X-Matte-Ambiguous-Ratio');\n\n return {\n data,\n metadata: {\n requestId: response.headers.get('X-Request-ID') || '',\n processingTimeMs: parseInt(response.headers.get('X-Processing-Time-Ms') || '0', 10),\n width: parseInt(response.headers.get('X-Image-Width') || '0', 10),\n height: parseInt(response.headers.get('X-Image-Height') || '0', 10),\n contentType: response.headers.get('Content-Type') || 'image/png',\n matteConfidence: matteConfidence !== null ? parseFloat(matteConfidence) : undefined,\n matteAmbiguousRatio: matteAmbiguousRatio !== null ? parseFloat(matteAmbiguousRatio) : undefined,\n },\n };\n }\n\n /**\n * Get the current state of a video job. Polling is free and does not count\n * against your rate limit.\n *\n * @param jobId - The job ID returned by removeBackground()\n *\n * @example\n * ```typescript\n * const job = await poof.getJob('job_8f3a1c2e9b7d4a10');\n * console.log(job.status, job.progress);\n * ```\n */\n async getJob(jobId: string): Promise<Job> {\n const response = await this.fetch(`${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return toJob(await response.json());\n }\n\n /**\n * Poll a video job until it is completed.\n *\n * @param job - A Job or a job ID\n * @param options - Poll interval, timeout and progress callback\n * @returns The completed job; `resultUrl` is a direct download link valid for 24 hours\n * @throws PoofError with code `job_failed` if the job fails (credits are refunded),\n * or code `timeout` if `timeoutMs` elapses first\n *\n * @example\n * ```typescript\n * const done = await poof.waitForJob(job, {\n * onProgress: (j) => console.log(`${Math.round(j.progress * 100)}%`),\n * });\n * const video = await fetch(done.resultUrl!);\n * ```\n */\n async waitForJob(job: Job | string, options: WaitForJobOptions = {}): Promise<Job> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS;\n const deadline = Date.now() + timeoutMs;\n\n let current: Job = typeof job === 'string' ? await this.getJob(job) : job;\n options.onProgress?.(current);\n\n while (!isTerminal(current.status)) {\n if (Date.now() >= deadline) {\n throw new PoofError(\n `Timed out after ${timeoutMs}ms waiting for job ${current.id}`,\n 'timeout',\n { status: 408 }\n );\n }\n await sleep(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));\n current = await this.getJob(current.id);\n options.onProgress?.(current);\n }\n\n if (current.status === 'failed') {\n throw new PoofError(\n current.error?.message || `Job ${current.id} failed`,\n 'job_failed',\n { details: current.error?.code }\n );\n }\n\n return current;\n }\n\n /**\n * Get account information\n *\n * @returns Account info including plan and credit usage\n *\n * @example\n * ```typescript\n * const account = await poof.me();\n * console.log(`Plan: ${account.plan}`);\n * console.log(`Credits: ${account.usedCredits}/${account.maxCredits}`);\n * ```\n */\n async me(): Promise<AccountInfo> {\n const response = await this.fetch(`${this.baseUrl}/me`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return response.json();\n }\n\n /** Make a fetch request with auth and timeout */\n private async fetch(url: string, init: RequestInit): Promise<Response> {\n const headers = new Headers(init.headers);\n headers.set('x-api-key', this.apiKey);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n return response;\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new PoofError('Request timeout', 'timeout', { status: 408 });\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /** Handle error response */\n private async handleError(response: Response): Promise<never> {\n let errorData: ApiErrorResponse;\n\n try {\n errorData = await response.json();\n } catch {\n throw new PoofError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'unknown_error',\n { status: response.status }\n );\n }\n\n throw PoofError.fromResponse(errorData, response.status);\n }\n}\n\n/**\n * Type guard: did removeBackground() return a video Job rather than image bytes?\n *\n * @example\n * ```typescript\n * const result = await poof.removeBackground(input);\n * if (isJob(result)) {\n * const done = await poof.waitForJob(result);\n * } else {\n * fs.writeFileSync('output.png', Buffer.from(result.data));\n * }\n * ```\n */\nexport function isJob(value: RemoveBackgroundResult | Job): value is Job {\n return typeof value === 'object' && value !== null && 'status' in value && typeof (value as Job).id === 'string';\n}\n\nfunction isTerminal(status: JobStatus): boolean {\n return status === 'completed' || status === 'failed';\n}\n\n/** The job object as the API returns it (snake_case) */\ninterface RawJob {\n id: string;\n status: JobStatus;\n progress: number;\n created_at: string;\n started_at: string | null;\n completed_at: string | null;\n duration_seconds: number;\n fps: number;\n width: number;\n height: number;\n frames: number;\n credits: number;\n format: Job['format'];\n channels: Job['channels'];\n status_url: string;\n result_url: string | null;\n expires_at: string | null;\n error: Job['error'];\n stats: Job['stats'];\n}\n\nfunction toJob(raw: RawJob): Job {\n return {\n id: raw.id,\n status: raw.status,\n progress: raw.progress ?? 0,\n createdAt: raw.created_at,\n startedAt: raw.started_at ?? null,\n completedAt: raw.completed_at ?? null,\n durationSeconds: raw.duration_seconds,\n fps: raw.fps,\n width: raw.width,\n height: raw.height,\n frames: raw.frames,\n credits: raw.credits,\n format: raw.format,\n channels: raw.channels,\n statusUrl: raw.status_url,\n resultUrl: raw.result_url ?? null,\n expiresAt: raw.expires_at ?? null,\n error: raw.error ?? null,\n stats: raw.stats ?? null,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/client.ts"],"names":[],"mappings":";;;AAaO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA;AAAA,EAE1B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,IAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,SAAS,OAAA,EAAS,MAAA;AACvB,IAAA,IAAA,CAAK,YAAY,OAAA,EAAS,SAAA;AAC1B,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AACxB,IAAA,IAAA,CAAK,SAAS,OAAA,EAAS,MAAA;AAGvB,IAAA,IAAI,mBAAA,IAAuB,KAAA,IAAS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AAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,QAAA,IAAY,KAAA,IAAS,OAAQ,KAAA,CAAc,EAAA,KAAO,QAAA;AAC1G;AAEA,SAAS,WAAW,MAAA,EAA4B;AAC9C,EAAA,OAAO,MAAA,KAAW,eAAe,MAAA,KAAW,QAAA;AAC9C;AAyBA,SAAS,MAAM,GAAA,EAAkB;AAC/B,EAAA,OAAO;AAAA,IACL,IAAI,GAAA,CAAI,EAAA;AAAA,IACR,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,QAAA,EAAU,IAAI,QAAA,IAAY,CAAA;AAAA,IAC1B,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,WAAA,EAAa,IAAI,YAAA,IAAgB,IAAA;AAAA,IACjC,iBAAiB,GAAA,CAAI,gBAAA;AAAA,IACrB,KAAK,GAAA,CAAI,GAAA;AAAA,IACT,OAAO,GAAA,CAAI,KAAA;AAAA,IACX,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,UAAU,GAAA,CAAI,QAAA;AAAA,IACd,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,KAAA,EAAO,IAAI,KAAA,IAAS,IAAA;AAAA,IACpB,KAAA,EAAO,IAAI,KAAA,IAAS;AAAA,GACtB;AACF","file":"index.cjs","sourcesContent":["import type { ErrorCode, ApiErrorResponse, ErrorDetails } from './types.js';\n\n/** Options accepted by every Poof error class */\nexport interface PoofErrorOptions {\n status?: number;\n requestId?: string;\n details?: ErrorDetails;\n docUrl?: string;\n}\n\n/**\n * Base error class for all Poof SDK errors\n */\nexport class PoofError extends Error {\n /** Machine-readable error code */\n readonly code: string;\n /** HTTP status code */\n readonly status?: number;\n /** Unique request ID for support */\n readonly requestId?: string;\n /** Additional details: an object for validation errors (e.g. { field: 'crop' }), or a string */\n readonly details?: ErrorDetails;\n /** Link to the documentation page for this error code */\n readonly docUrl?: string;\n\n constructor(\n message: string,\n code: string,\n options?: PoofErrorOptions\n ) {\n super(message);\n this.name = 'PoofError';\n this.code = code;\n this.status = options?.status;\n this.requestId = options?.requestId;\n this.details = options?.details;\n this.docUrl = options?.docUrl;\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /** Create error from API response */\n static fromResponse(response: ApiErrorResponse, status: number): PoofError {\n const ErrorClass = ERROR_MAP[response.code] || PoofError;\n return new ErrorClass(response.message, response.code, {\n status,\n requestId: response.request_id,\n details: response.details,\n docUrl: response.doc_url,\n });\n }\n}\n\n/**\n * Thrown when the API key is invalid or missing\n */\nexport class AuthenticationError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown when the account doesn't have permission\n */\nexport class PermissionError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'PermissionError';\n }\n}\n\n/**\n * Thrown when the account has insufficient credits\n */\nexport class PaymentRequiredError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'PaymentRequiredError';\n }\n}\n\n/**\n * Thrown when rate limit is exceeded\n */\nexport class RateLimitError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Thrown when request parameters are invalid\n */\nexport class ValidationError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Thrown when a server error occurs\n */\nexport class ServerError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'ServerError';\n }\n}\n\n/** Map error codes to error classes */\nconst ERROR_MAP: Record<ErrorCode, typeof PoofError> = {\n authentication_error: AuthenticationError,\n permission_denied: PermissionError,\n payment_required: PaymentRequiredError,\n rate_limit_exceeded: RateLimitError,\n validation_error: ValidationError,\n missing_image: ValidationError,\n image_too_large: ValidationError,\n invalid_image: ValidationError,\n processing_failed: ServerError,\n not_found: PoofError,\n video_too_large: ValidationError,\n video_too_long: ValidationError,\n invalid_video: ValidationError,\n job_not_found: ValidationError,\n job_failed: PoofError,\n upstream_error: ServerError,\n internal_server_error: ServerError,\n};\n","import type { ImageInput, MediaInput, UrlInput } from './types.js';\n\n/** Check if running in Node.js environment */\nexport const isNode = typeof process !== 'undefined' && process.versions?.node;\n\n/** Detect MIME type from buffer */\nfunction detectMimeType(buffer: Uint8Array): string {\n // Check magic bytes\n if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {\n return 'image/png';\n }\n if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {\n return 'image/jpeg';\n }\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) {\n // RIFF header, check for WEBP\n if (buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {\n return 'image/webp';\n }\n }\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\n return 'image/gif';\n }\n // ISO base media file (MP4, MOV): 'ftyp' at offset 4\n if (buffer[4] === 0x66 && buffer[5] === 0x74 && buffer[6] === 0x79 && buffer[7] === 0x70) {\n // 'qt ' brand is QuickTime\n if (buffer[8] === 0x71 && buffer[9] === 0x74) {\n return 'video/quicktime';\n }\n return 'video/mp4';\n }\n // EBML header (WebM, Matroska)\n if (buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3) {\n return 'video/webm';\n }\n // Default to octet-stream\n return 'application/octet-stream';\n}\n\n/** Get file extension from MIME type */\nfunction getExtension(mimeType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'video/webm': 'webm',\n };\n return map[mimeType] || 'bin';\n}\n\n/** Convert various input types to a Blob suitable for FormData */\nexport async function toBlob(input: ImageInput): Promise<Blob> {\n // Already a Blob or File\n if (input instanceof Blob) {\n return input;\n }\n\n // ArrayBuffer\n if (input instanceof ArrayBuffer) {\n const uint8 = new Uint8Array(input);\n const mimeType = detectMimeType(uint8);\n return new Blob([input], { type: mimeType });\n }\n\n // Uint8Array or Node.js Buffer. Copy into a fresh ArrayBuffer-backed view:\n // a view over a SharedArrayBuffer (or a Buffer pool slice) is not a valid BlobPart.\n if (input instanceof Uint8Array || (isNode && Buffer.isBuffer(input))) {\n const bytes = Uint8Array.from(input);\n const mimeType = detectMimeType(bytes);\n return new Blob([bytes], { type: mimeType });\n }\n\n // String - treat as file path (Node.js only)\n if (typeof input === 'string') {\n if (!isNode) {\n throw new Error('File paths are only supported in Node.js. Use a Blob or File in the browser.');\n }\n \n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n \n const buffer = await fs.readFile(input);\n const uint8 = new Uint8Array(buffer);\n const mimeType = detectMimeType(uint8);\n const ext = path.extname(input).toLowerCase().slice(1);\n \n // Use file extension for mime type if available\n const mimeFromExt: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n mkv: 'video/x-matroska',\n };\n \n const finalMimeType = mimeFromExt[ext] || mimeType;\n return new Blob([buffer], { type: finalMimeType });\n }\n\n throw new Error(`Unsupported input type: ${typeof input}`);\n}\n\n/** Get filename for FormData */\nexport function getFilename(input: ImageInput, mimeType: string): string {\n // File has a name\n if (typeof File !== 'undefined' && input instanceof File) {\n return input.name;\n }\n\n // String path\n if (typeof input === 'string' && isNode) {\n // Extract filename from path\n const parts = input.split(/[/\\\\]/);\n return parts[parts.length - 1] || defaultFilename(mimeType);\n }\n\n // Generate name from mime type\n return defaultFilename(mimeType);\n}\n\nfunction defaultFilename(mimeType: string): string {\n const stem = mimeType.startsWith('video/') ? 'video' : 'image';\n return `${stem}.${getExtension(mimeType)}`;\n}\n\n/** Is the input a `{ url }` object rather than file contents? */\nexport function isUrlInput(input: MediaInput): input is UrlInput {\n return typeof input === 'object' && input !== null && 'url' in input && typeof (input as UrlInput).url === 'string';\n}\n\n/** Resolve after `ms` milliseconds */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import type {\n PoofOptions,\n MediaInput,\n RemoveBackgroundOptions,\n RemoveBackgroundResult,\n Job,\n JobStatus,\n WaitForJobOptions,\n AccountInfo,\n ApiErrorResponse,\n} from './types.js';\nimport { PoofError } from './errors.js';\nimport { toBlob, getFilename, isUrlInput, sleep } from './utils.js';\n\nconst DEFAULT_BASE_URL = 'https://api.poof.bg/v1';\nconst DEFAULT_TIMEOUT = 60000;\nconst DEFAULT_POLL_INTERVAL_MS = 3000;\nconst DEFAULT_JOB_TIMEOUT_MS = 600000;\n\n/**\n * Poof API client for background removal\n *\n * @example\n * ```typescript\n * import { Poof } from '@poof-bg/js';\n *\n * const poof = new Poof({ apiKey: 'your-api-key' });\n * const result = await poof.removeBackground(imageFile);\n * ```\n */\nexport class Poof {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(options: PoofOptions) {\n if (!options.apiKey) {\n throw new Error('API key is required');\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl?.replace(/\\/$/, '') || DEFAULT_BASE_URL;\n this.timeout = options.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Remove the background from an image or a video.\n *\n * Images are processed synchronously and come back as bytes. Videos are\n * processed as a job: the call returns a queued {@link Job}; poll it with\n * {@link getJob} / {@link waitForJob}, or pass `wait: true` to get the\n * completed job (with `resultUrl`) directly. Use {@link isJob} to tell the\n * two apart.\n *\n * @param input - File, Blob, Buffer, ArrayBuffer, Uint8Array, file path (Node.js), or `{ url }`\n * @param options - Processing options\n * @returns Processed image data and metadata, or a video Job\n *\n * @example\n * ```typescript\n * // Image\n * const result = await poof.removeBackground(file);\n * const imageBlob = new Blob([result.data], { type: result.metadata.contentType });\n *\n * // With options\n * const result = await poof.removeBackground(file, { format: 'webp', crop: true, size: 'medium' });\n *\n * // Exact 500x500 output, subject cropped and centred, never stretched\n * const result = await poof.removeBackground(file, { crop: true, width: 500, height: 500 });\n *\n * // Video: submit, then wait for the result\n * const job = await poof.removeBackground('./clip.mp4', { format: 'webm' });\n * const done = await poof.waitForJob(job);\n * console.log(done.resultUrl);\n *\n * // Video from a public URL, waiting inline\n * const done = await poof.removeBackground({ url: 'https://example.com/clip.mp4' }, { wait: true });\n * ```\n */\n async removeBackground(\n input: MediaInput,\n options: RemoveBackgroundOptions = {}\n ): Promise<RemoveBackgroundResult | Job> {\n const formData = new FormData();\n\n if (isUrlInput(input)) {\n formData.append('url', input.url);\n } else {\n const blob = await toBlob(input);\n const filename = getFilename(input, blob.type);\n formData.append('file', blob, filename);\n }\n\n // Add optional parameters\n if (options.format) formData.append('format', options.format);\n if (options.channels) formData.append('channels', options.channels);\n if (options.bgColor) formData.append('bg_color', options.bgColor);\n if (options.size) formData.append('size', options.size);\n // crop defaults to false and is image-only: only send it when enabled, so\n // `crop: false` on a video is not rejected with a validation_error.\n if (options.crop === true) formData.append('crop', 'true');\n else if (typeof options.crop === 'string' && options.crop) formData.append('crop', options.crop);\n if (options.padding) formData.append('padding', options.padding);\n if (options.width !== undefined) formData.append('width', String(options.width));\n if (options.height !== undefined) formData.append('height', String(options.height));\n if (options.fit) formData.append('fit', options.fit);\n\n const response = await this.fetch(`${this.baseUrl}/remove`, {\n method: 'POST',\n body: formData,\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n // Videos are accepted as a job\n if (response.status === 202) {\n const job = toJob(await response.json());\n if (options.wait) {\n return this.waitForJob(job, options.wait === true ? {} : options.wait);\n }\n return job;\n }\n\n const data = await response.arrayBuffer();\n\n const matteConfidence = response.headers.get('X-Matte-Confidence');\n const matteAmbiguousRatio = response.headers.get('X-Matte-Ambiguous-Ratio');\n\n return {\n data,\n metadata: {\n requestId: response.headers.get('X-Request-ID') || '',\n processingTimeMs: parseInt(response.headers.get('X-Processing-Time-Ms') || '0', 10),\n width: parseInt(response.headers.get('X-Image-Width') || '0', 10),\n height: parseInt(response.headers.get('X-Image-Height') || '0', 10),\n contentType: response.headers.get('Content-Type') || 'image/png',\n matteConfidence: matteConfidence !== null ? parseFloat(matteConfidence) : undefined,\n matteAmbiguousRatio: matteAmbiguousRatio !== null ? parseFloat(matteAmbiguousRatio) : undefined,\n },\n };\n }\n\n /**\n * Get the current state of a video job. Polling is free and does not count\n * against your rate limit.\n *\n * @param jobId - The job ID returned by removeBackground()\n *\n * @example\n * ```typescript\n * const job = await poof.getJob('job_8f3a1c2e9b7d4a10');\n * console.log(job.status, job.progress);\n * ```\n */\n async getJob(jobId: string): Promise<Job> {\n const response = await this.fetch(`${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return toJob(await response.json());\n }\n\n /**\n * Poll a video job until it is completed.\n *\n * @param job - A Job or a job ID\n * @param options - Poll interval, timeout and progress callback\n * @returns The completed job; `resultUrl` is a direct download link valid for 24 hours\n * @throws PoofError with code `job_failed` if the job fails (credits are refunded),\n * or code `timeout` if `timeoutMs` elapses first\n *\n * @example\n * ```typescript\n * const done = await poof.waitForJob(job, {\n * onProgress: (j) => console.log(`${Math.round(j.progress * 100)}%`),\n * });\n * const video = await fetch(done.resultUrl!);\n * ```\n */\n async waitForJob(job: Job | string, options: WaitForJobOptions = {}): Promise<Job> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS;\n const deadline = Date.now() + timeoutMs;\n\n let current: Job = typeof job === 'string' ? await this.getJob(job) : job;\n options.onProgress?.(current);\n\n while (!isTerminal(current.status)) {\n if (Date.now() >= deadline) {\n throw new PoofError(\n `Timed out after ${timeoutMs}ms waiting for job ${current.id}`,\n 'timeout',\n { status: 408 }\n );\n }\n await sleep(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));\n current = await this.getJob(current.id);\n options.onProgress?.(current);\n }\n\n if (current.status === 'failed') {\n throw new PoofError(\n current.error?.message || `Job ${current.id} failed`,\n 'job_failed',\n { details: current.error?.code }\n );\n }\n\n return current;\n }\n\n /**\n * Get account information\n *\n * @returns Account info including plan and credit usage\n *\n * @example\n * ```typescript\n * const account = await poof.me();\n * console.log(`Plan: ${account.plan}`);\n * console.log(`Credits: ${account.usedCredits}/${account.maxCredits}`);\n * ```\n */\n async me(): Promise<AccountInfo> {\n const response = await this.fetch(`${this.baseUrl}/me`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return response.json();\n }\n\n /** Make a fetch request with auth and timeout */\n private async fetch(url: string, init: RequestInit): Promise<Response> {\n const headers = new Headers(init.headers);\n headers.set('x-api-key', this.apiKey);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n return response;\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new PoofError('Request timeout', 'timeout', { status: 408 });\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /** Handle error response */\n private async handleError(response: Response): Promise<never> {\n let errorData: ApiErrorResponse;\n\n try {\n errorData = await response.json();\n } catch {\n throw new PoofError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'unknown_error',\n { status: response.status }\n );\n }\n\n throw PoofError.fromResponse(errorData, response.status);\n }\n}\n\n/**\n * Type guard: did removeBackground() return a video Job rather than image bytes?\n *\n * @example\n * ```typescript\n * const result = await poof.removeBackground(input);\n * if (isJob(result)) {\n * const done = await poof.waitForJob(result);\n * } else {\n * fs.writeFileSync('output.png', Buffer.from(result.data));\n * }\n * ```\n */\nexport function isJob(value: RemoveBackgroundResult | Job): value is Job {\n return typeof value === 'object' && value !== null && 'status' in value && typeof (value as Job).id === 'string';\n}\n\nfunction isTerminal(status: JobStatus): boolean {\n return status === 'completed' || status === 'failed';\n}\n\n/** The job object as the API returns it (snake_case) */\ninterface RawJob {\n id: string;\n status: JobStatus;\n progress: number;\n created_at: string;\n started_at: string | null;\n completed_at: string | null;\n duration_seconds: number;\n fps: number;\n width: number;\n height: number;\n frames: number;\n credits: number;\n format: Job['format'];\n channels: Job['channels'];\n status_url: string;\n result_url: string | null;\n expires_at: string | null;\n error: Job['error'];\n stats: Job['stats'];\n}\n\nfunction toJob(raw: RawJob): Job {\n return {\n id: raw.id,\n status: raw.status,\n progress: raw.progress ?? 0,\n createdAt: raw.created_at,\n startedAt: raw.started_at ?? null,\n completedAt: raw.completed_at ?? null,\n durationSeconds: raw.duration_seconds,\n fps: raw.fps,\n width: raw.width,\n height: raw.height,\n frames: raw.frames,\n credits: raw.credits,\n format: raw.format,\n channels: raw.channels,\n statusUrl: raw.status_url,\n resultUrl: raw.result_url ?? null,\n expiresAt: raw.expires_at ?? null,\n error: raw.error ?? null,\n stats: raw.stats ?? null,\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -12,11 +12,19 @@ interface PoofOptions {
12
12
  }
13
13
  /** Output image format */
14
14
  type ImageFormat = 'png' | 'jpg' | 'webp';
15
- /** Output video format: VP9 WebM (alpha or opaque), ProRes MOV (alpha or opaque) or H.264 MP4 (opaque) */
16
- type VideoFormat = 'webm' | 'mov' | 'mp4';
15
+ /**
16
+ * Output video format: VP9 WebM (alpha or opaque), ProRes MOV (alpha or opaque),
17
+ * H.264 MP4 (opaque) or looping animated GIF (1-bit transparency, no audio,
18
+ * capped at 1280 px on the longest side / 720p for widescreen, and 50 fps)
19
+ */
20
+ type VideoFormat = 'webm' | 'mov' | 'mp4' | 'gif';
17
21
  /** Output color channels */
18
22
  type Channels = 'rgba' | 'rgb' | 'alpha';
19
- /** Output image size preset */
23
+ /**
24
+ * Output size preset. Images: megapixel cap. Videos: longest side capped at
25
+ * 640 (preview), 1280 (medium) or 1920 (hd); 'full' keeps the source
26
+ * resolution up to 4096 px (4K).
27
+ */
20
28
  type ImageSize = 'full' | 'preview' | 'medium' | 'hd';
21
29
  /**
22
30
  * How the image is fitted into a fixed width/height (never stretched):
@@ -36,15 +44,19 @@ interface WaitForJobOptions {
36
44
  }
37
45
  /** Options for background removal */
38
46
  interface RemoveBackgroundOptions {
39
- /** Output format: png, jpg or webp for images (default: png); webm, mov or mp4 for videos (default: webm) */
47
+ /** Output format: png, jpg or webp for images (default: png); webm, mov, mp4 or gif for videos (default: webm) */
40
48
  format?: ImageFormat | VideoFormat;
41
49
  /** Color channels - rgba for transparency, rgb for opaque, alpha for the grayscale mask only (default: rgba) */
42
50
  channels?: Channels;
43
- /** Background color (hex, rgb, or color name). Applies when channels is 'rgb' or 'rgba' */
51
+ /**
52
+ * Background color (hex, rgb, or color name; default white). Used for opaque
53
+ * output: channels 'rgb', format 'jpg' and format 'mp4'. Ignored for
54
+ * transparent output
55
+ */
44
56
  bgColor?: string;
45
57
  /** Output size preset (default: full) */
46
58
  size?: ImageSize;
47
- /** Crop to subject bounds: true/false or an aspect ratio like '1:1', '4:3', '16:9' (default: false) */
59
+ /** Images only. Crop to subject bounds: true or an aspect ratio like '1:1', '4:3', '16:9' (default: false; not sent unless enabled) */
48
60
  crop?: boolean | string;
49
61
  /** Padding around the subject when crop is enabled, as a fraction ('0.1') or percentage ('10%') */
50
62
  padding?: string;
@@ -126,7 +138,10 @@ interface Job {
126
138
  height: number;
127
139
  /** Number of frames in the source video */
128
140
  frames: number;
129
- /** Credits charged for this job (5 per second of video, 10 above 30 fps); refunded if it fails */
141
+ /**
142
+ * Credits charged for this job: 5 per started second of video (10 above
143
+ * 30 fps; animated GIF input is always 5 per second). Refunded if it fails
144
+ */
130
145
  credits: number;
131
146
  /** Requested output format */
132
147
  format: VideoFormat;
@@ -157,14 +172,19 @@ interface AccountInfo {
157
172
  autoRechargeThreshold: number | null;
158
173
  }
159
174
  /** Error codes returned by the API */
160
- type ErrorCode = 'authentication_error' | 'permission_denied' | 'payment_required' | 'rate_limit_exceeded' | 'validation_error' | 'missing_image' | 'image_too_large' | 'invalid_image' | 'video_too_large' | 'video_too_long' | 'invalid_video' | 'job_not_found' | 'job_failed' | 'upstream_error' | 'internal_server_error';
175
+ type ErrorCode = 'authentication_error' | 'permission_denied' | 'payment_required' | 'rate_limit_exceeded' | 'validation_error' | 'missing_image' | 'image_too_large' | 'invalid_image' | 'processing_failed' | 'not_found' | 'video_too_large' | 'video_too_long' | 'invalid_video' | 'job_not_found' | 'job_failed' | 'upstream_error' | 'internal_server_error';
161
176
  /** API error response structure */
162
177
  interface ApiErrorResponse {
163
178
  code: ErrorCode;
164
179
  message: string;
165
- details?: string;
180
+ /** Extra context; for validation_error an object such as { field: 'crop' } */
181
+ details?: ErrorDetails;
166
182
  request_id: string;
183
+ /** Link to the documentation page for this error code */
184
+ doc_url?: string;
167
185
  }
186
+ /** Optional extra context on an API error: an object for validation errors, or a string */
187
+ type ErrorDetails = Record<string, unknown> | string;
168
188
  /** Valid input types for image and video processing: file contents, or a file path in Node.js */
169
189
  type ImageInput = File | Blob | ArrayBuffer | Buffer | Uint8Array | string;
170
190
  /** A publicly reachable https URL that Poof downloads instead of an upload (images up to 20 MB, videos up to 500 MB) */
@@ -289,6 +309,13 @@ declare class Poof {
289
309
  */
290
310
  declare function isJob(value: RemoveBackgroundResult | Job): value is Job;
291
311
 
312
+ /** Options accepted by every Poof error class */
313
+ interface PoofErrorOptions {
314
+ status?: number;
315
+ requestId?: string;
316
+ details?: ErrorDetails;
317
+ docUrl?: string;
318
+ }
292
319
  /**
293
320
  * Base error class for all Poof SDK errors
294
321
  */
@@ -299,13 +326,11 @@ declare class PoofError extends Error {
299
326
  readonly status?: number;
300
327
  /** Unique request ID for support */
301
328
  readonly requestId?: string;
302
- /** Additional details */
303
- readonly details?: string;
304
- constructor(message: string, code: string, options?: {
305
- status?: number;
306
- requestId?: string;
307
- details?: string;
308
- });
329
+ /** Additional details: an object for validation errors (e.g. { field: 'crop' }), or a string */
330
+ readonly details?: ErrorDetails;
331
+ /** Link to the documentation page for this error code */
332
+ readonly docUrl?: string;
333
+ constructor(message: string, code: string, options?: PoofErrorOptions);
309
334
  /** Create error from API response */
310
335
  static fromResponse(response: ApiErrorResponse, status: number): PoofError;
311
336
  }
@@ -313,61 +338,37 @@ declare class PoofError extends Error {
313
338
  * Thrown when the API key is invalid or missing
314
339
  */
315
340
  declare class AuthenticationError extends PoofError {
316
- constructor(message: string, code: string, options?: {
317
- status?: number;
318
- requestId?: string;
319
- details?: string;
320
- });
341
+ constructor(message: string, code: string, options?: PoofErrorOptions);
321
342
  }
322
343
  /**
323
344
  * Thrown when the account doesn't have permission
324
345
  */
325
346
  declare class PermissionError extends PoofError {
326
- constructor(message: string, code: string, options?: {
327
- status?: number;
328
- requestId?: string;
329
- details?: string;
330
- });
347
+ constructor(message: string, code: string, options?: PoofErrorOptions);
331
348
  }
332
349
  /**
333
350
  * Thrown when the account has insufficient credits
334
351
  */
335
352
  declare class PaymentRequiredError extends PoofError {
336
- constructor(message: string, code: string, options?: {
337
- status?: number;
338
- requestId?: string;
339
- details?: string;
340
- });
353
+ constructor(message: string, code: string, options?: PoofErrorOptions);
341
354
  }
342
355
  /**
343
356
  * Thrown when rate limit is exceeded
344
357
  */
345
358
  declare class RateLimitError extends PoofError {
346
- constructor(message: string, code: string, options?: {
347
- status?: number;
348
- requestId?: string;
349
- details?: string;
350
- });
359
+ constructor(message: string, code: string, options?: PoofErrorOptions);
351
360
  }
352
361
  /**
353
362
  * Thrown when request parameters are invalid
354
363
  */
355
364
  declare class ValidationError extends PoofError {
356
- constructor(message: string, code: string, options?: {
357
- status?: number;
358
- requestId?: string;
359
- details?: string;
360
- });
365
+ constructor(message: string, code: string, options?: PoofErrorOptions);
361
366
  }
362
367
  /**
363
368
  * Thrown when a server error occurs
364
369
  */
365
370
  declare class ServerError extends PoofError {
366
- constructor(message: string, code: string, options?: {
367
- status?: number;
368
- requestId?: string;
369
- details?: string;
370
- });
371
+ constructor(message: string, code: string, options?: PoofErrorOptions);
371
372
  }
372
373
 
373
- export { type AccountInfo, type ApiErrorResponse, AuthenticationError, type Channels, type ErrorCode, type FitMode, type ImageFormat, type ImageInput, type ImageSize, type Job, type JobError, type JobStatus, type MediaInput, PaymentRequiredError, PermissionError, Poof, PoofError, type PoofOptions, type ProcessingMetadata, RateLimitError, type RemoveBackgroundOptions, type RemoveBackgroundResult, ServerError, type UrlInput, ValidationError, type VideoFormat, type WaitForJobOptions, isJob };
374
+ export { type AccountInfo, type ApiErrorResponse, AuthenticationError, type Channels, type ErrorCode, type ErrorDetails, type FitMode, type ImageFormat, type ImageInput, type ImageSize, type Job, type JobError, type JobStatus, type MediaInput, PaymentRequiredError, PermissionError, Poof, PoofError, type PoofErrorOptions, type PoofOptions, type ProcessingMetadata, RateLimitError, type RemoveBackgroundOptions, type RemoveBackgroundResult, ServerError, type UrlInput, ValidationError, type VideoFormat, type WaitForJobOptions, isJob };
package/dist/index.d.ts CHANGED
@@ -12,11 +12,19 @@ interface PoofOptions {
12
12
  }
13
13
  /** Output image format */
14
14
  type ImageFormat = 'png' | 'jpg' | 'webp';
15
- /** Output video format: VP9 WebM (alpha or opaque), ProRes MOV (alpha or opaque) or H.264 MP4 (opaque) */
16
- type VideoFormat = 'webm' | 'mov' | 'mp4';
15
+ /**
16
+ * Output video format: VP9 WebM (alpha or opaque), ProRes MOV (alpha or opaque),
17
+ * H.264 MP4 (opaque) or looping animated GIF (1-bit transparency, no audio,
18
+ * capped at 1280 px on the longest side / 720p for widescreen, and 50 fps)
19
+ */
20
+ type VideoFormat = 'webm' | 'mov' | 'mp4' | 'gif';
17
21
  /** Output color channels */
18
22
  type Channels = 'rgba' | 'rgb' | 'alpha';
19
- /** Output image size preset */
23
+ /**
24
+ * Output size preset. Images: megapixel cap. Videos: longest side capped at
25
+ * 640 (preview), 1280 (medium) or 1920 (hd); 'full' keeps the source
26
+ * resolution up to 4096 px (4K).
27
+ */
20
28
  type ImageSize = 'full' | 'preview' | 'medium' | 'hd';
21
29
  /**
22
30
  * How the image is fitted into a fixed width/height (never stretched):
@@ -36,15 +44,19 @@ interface WaitForJobOptions {
36
44
  }
37
45
  /** Options for background removal */
38
46
  interface RemoveBackgroundOptions {
39
- /** Output format: png, jpg or webp for images (default: png); webm, mov or mp4 for videos (default: webm) */
47
+ /** Output format: png, jpg or webp for images (default: png); webm, mov, mp4 or gif for videos (default: webm) */
40
48
  format?: ImageFormat | VideoFormat;
41
49
  /** Color channels - rgba for transparency, rgb for opaque, alpha for the grayscale mask only (default: rgba) */
42
50
  channels?: Channels;
43
- /** Background color (hex, rgb, or color name). Applies when channels is 'rgb' or 'rgba' */
51
+ /**
52
+ * Background color (hex, rgb, or color name; default white). Used for opaque
53
+ * output: channels 'rgb', format 'jpg' and format 'mp4'. Ignored for
54
+ * transparent output
55
+ */
44
56
  bgColor?: string;
45
57
  /** Output size preset (default: full) */
46
58
  size?: ImageSize;
47
- /** Crop to subject bounds: true/false or an aspect ratio like '1:1', '4:3', '16:9' (default: false) */
59
+ /** Images only. Crop to subject bounds: true or an aspect ratio like '1:1', '4:3', '16:9' (default: false; not sent unless enabled) */
48
60
  crop?: boolean | string;
49
61
  /** Padding around the subject when crop is enabled, as a fraction ('0.1') or percentage ('10%') */
50
62
  padding?: string;
@@ -126,7 +138,10 @@ interface Job {
126
138
  height: number;
127
139
  /** Number of frames in the source video */
128
140
  frames: number;
129
- /** Credits charged for this job (5 per second of video, 10 above 30 fps); refunded if it fails */
141
+ /**
142
+ * Credits charged for this job: 5 per started second of video (10 above
143
+ * 30 fps; animated GIF input is always 5 per second). Refunded if it fails
144
+ */
130
145
  credits: number;
131
146
  /** Requested output format */
132
147
  format: VideoFormat;
@@ -157,14 +172,19 @@ interface AccountInfo {
157
172
  autoRechargeThreshold: number | null;
158
173
  }
159
174
  /** Error codes returned by the API */
160
- type ErrorCode = 'authentication_error' | 'permission_denied' | 'payment_required' | 'rate_limit_exceeded' | 'validation_error' | 'missing_image' | 'image_too_large' | 'invalid_image' | 'video_too_large' | 'video_too_long' | 'invalid_video' | 'job_not_found' | 'job_failed' | 'upstream_error' | 'internal_server_error';
175
+ type ErrorCode = 'authentication_error' | 'permission_denied' | 'payment_required' | 'rate_limit_exceeded' | 'validation_error' | 'missing_image' | 'image_too_large' | 'invalid_image' | 'processing_failed' | 'not_found' | 'video_too_large' | 'video_too_long' | 'invalid_video' | 'job_not_found' | 'job_failed' | 'upstream_error' | 'internal_server_error';
161
176
  /** API error response structure */
162
177
  interface ApiErrorResponse {
163
178
  code: ErrorCode;
164
179
  message: string;
165
- details?: string;
180
+ /** Extra context; for validation_error an object such as { field: 'crop' } */
181
+ details?: ErrorDetails;
166
182
  request_id: string;
183
+ /** Link to the documentation page for this error code */
184
+ doc_url?: string;
167
185
  }
186
+ /** Optional extra context on an API error: an object for validation errors, or a string */
187
+ type ErrorDetails = Record<string, unknown> | string;
168
188
  /** Valid input types for image and video processing: file contents, or a file path in Node.js */
169
189
  type ImageInput = File | Blob | ArrayBuffer | Buffer | Uint8Array | string;
170
190
  /** A publicly reachable https URL that Poof downloads instead of an upload (images up to 20 MB, videos up to 500 MB) */
@@ -289,6 +309,13 @@ declare class Poof {
289
309
  */
290
310
  declare function isJob(value: RemoveBackgroundResult | Job): value is Job;
291
311
 
312
+ /** Options accepted by every Poof error class */
313
+ interface PoofErrorOptions {
314
+ status?: number;
315
+ requestId?: string;
316
+ details?: ErrorDetails;
317
+ docUrl?: string;
318
+ }
292
319
  /**
293
320
  * Base error class for all Poof SDK errors
294
321
  */
@@ -299,13 +326,11 @@ declare class PoofError extends Error {
299
326
  readonly status?: number;
300
327
  /** Unique request ID for support */
301
328
  readonly requestId?: string;
302
- /** Additional details */
303
- readonly details?: string;
304
- constructor(message: string, code: string, options?: {
305
- status?: number;
306
- requestId?: string;
307
- details?: string;
308
- });
329
+ /** Additional details: an object for validation errors (e.g. { field: 'crop' }), or a string */
330
+ readonly details?: ErrorDetails;
331
+ /** Link to the documentation page for this error code */
332
+ readonly docUrl?: string;
333
+ constructor(message: string, code: string, options?: PoofErrorOptions);
309
334
  /** Create error from API response */
310
335
  static fromResponse(response: ApiErrorResponse, status: number): PoofError;
311
336
  }
@@ -313,61 +338,37 @@ declare class PoofError extends Error {
313
338
  * Thrown when the API key is invalid or missing
314
339
  */
315
340
  declare class AuthenticationError extends PoofError {
316
- constructor(message: string, code: string, options?: {
317
- status?: number;
318
- requestId?: string;
319
- details?: string;
320
- });
341
+ constructor(message: string, code: string, options?: PoofErrorOptions);
321
342
  }
322
343
  /**
323
344
  * Thrown when the account doesn't have permission
324
345
  */
325
346
  declare class PermissionError extends PoofError {
326
- constructor(message: string, code: string, options?: {
327
- status?: number;
328
- requestId?: string;
329
- details?: string;
330
- });
347
+ constructor(message: string, code: string, options?: PoofErrorOptions);
331
348
  }
332
349
  /**
333
350
  * Thrown when the account has insufficient credits
334
351
  */
335
352
  declare class PaymentRequiredError extends PoofError {
336
- constructor(message: string, code: string, options?: {
337
- status?: number;
338
- requestId?: string;
339
- details?: string;
340
- });
353
+ constructor(message: string, code: string, options?: PoofErrorOptions);
341
354
  }
342
355
  /**
343
356
  * Thrown when rate limit is exceeded
344
357
  */
345
358
  declare class RateLimitError extends PoofError {
346
- constructor(message: string, code: string, options?: {
347
- status?: number;
348
- requestId?: string;
349
- details?: string;
350
- });
359
+ constructor(message: string, code: string, options?: PoofErrorOptions);
351
360
  }
352
361
  /**
353
362
  * Thrown when request parameters are invalid
354
363
  */
355
364
  declare class ValidationError extends PoofError {
356
- constructor(message: string, code: string, options?: {
357
- status?: number;
358
- requestId?: string;
359
- details?: string;
360
- });
365
+ constructor(message: string, code: string, options?: PoofErrorOptions);
361
366
  }
362
367
  /**
363
368
  * Thrown when a server error occurs
364
369
  */
365
370
  declare class ServerError extends PoofError {
366
- constructor(message: string, code: string, options?: {
367
- status?: number;
368
- requestId?: string;
369
- details?: string;
370
- });
371
+ constructor(message: string, code: string, options?: PoofErrorOptions);
371
372
  }
372
373
 
373
- export { type AccountInfo, type ApiErrorResponse, AuthenticationError, type Channels, type ErrorCode, type FitMode, type ImageFormat, type ImageInput, type ImageSize, type Job, type JobError, type JobStatus, type MediaInput, PaymentRequiredError, PermissionError, Poof, PoofError, type PoofOptions, type ProcessingMetadata, RateLimitError, type RemoveBackgroundOptions, type RemoveBackgroundResult, ServerError, type UrlInput, ValidationError, type VideoFormat, type WaitForJobOptions, isJob };
374
+ export { type AccountInfo, type ApiErrorResponse, AuthenticationError, type Channels, type ErrorCode, type ErrorDetails, type FitMode, type ImageFormat, type ImageInput, type ImageSize, type Job, type JobError, type JobStatus, type MediaInput, PaymentRequiredError, PermissionError, Poof, PoofError, type PoofErrorOptions, type PoofOptions, type ProcessingMetadata, RateLimitError, type RemoveBackgroundOptions, type RemoveBackgroundResult, ServerError, type UrlInput, ValidationError, type VideoFormat, type WaitForJobOptions, isJob };
package/dist/index.js CHANGED
@@ -6,8 +6,10 @@ var PoofError = class _PoofError extends Error {
6
6
  status;
7
7
  /** Unique request ID for support */
8
8
  requestId;
9
- /** Additional details */
9
+ /** Additional details: an object for validation errors (e.g. { field: 'crop' }), or a string */
10
10
  details;
11
+ /** Link to the documentation page for this error code */
12
+ docUrl;
11
13
  constructor(message, code, options) {
12
14
  super(message);
13
15
  this.name = "PoofError";
@@ -15,6 +17,7 @@ var PoofError = class _PoofError extends Error {
15
17
  this.status = options?.status;
16
18
  this.requestId = options?.requestId;
17
19
  this.details = options?.details;
20
+ this.docUrl = options?.docUrl;
18
21
  if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
19
22
  Error.captureStackTrace(this, this.constructor);
20
23
  }
@@ -25,7 +28,8 @@ var PoofError = class _PoofError extends Error {
25
28
  return new ErrorClass(response.message, response.code, {
26
29
  status,
27
30
  requestId: response.request_id,
28
- details: response.details
31
+ details: response.details,
32
+ docUrl: response.doc_url
29
33
  });
30
34
  }
31
35
  };
@@ -74,6 +78,8 @@ var ERROR_MAP = {
74
78
  missing_image: ValidationError,
75
79
  image_too_large: ValidationError,
76
80
  invalid_image: ValidationError,
81
+ processing_failed: ServerError,
82
+ not_found: PoofError,
77
83
  video_too_large: ValidationError,
78
84
  video_too_long: ValidationError,
79
85
  invalid_video: ValidationError,
@@ -249,7 +255,8 @@ var Poof = class {
249
255
  if (options.channels) formData.append("channels", options.channels);
250
256
  if (options.bgColor) formData.append("bg_color", options.bgColor);
251
257
  if (options.size) formData.append("size", options.size);
252
- if (options.crop !== void 0) formData.append("crop", String(options.crop));
258
+ if (options.crop === true) formData.append("crop", "true");
259
+ else if (typeof options.crop === "string" && options.crop) formData.append("crop", options.crop);
253
260
  if (options.padding) formData.append("padding", options.padding);
254
261
  if (options.width !== void 0) formData.append("width", String(options.width));
255
262
  if (options.height !== void 0) formData.append("height", String(options.height));
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/client.ts"],"names":[],"mappings":";AAKO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA;AAAA,EAE1B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,SAAA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":"index.js","sourcesContent":["import type { ErrorCode, ApiErrorResponse } from './types.js';\n\n/**\n * Base error class for all Poof SDK errors\n */\nexport class PoofError extends Error {\n /** Machine-readable error code */\n readonly code: string;\n /** HTTP status code */\n readonly status?: number;\n /** Unique request ID for support */\n readonly requestId?: string;\n /** Additional details */\n readonly details?: string;\n\n constructor(\n message: string,\n code: string,\n options?: { status?: number; requestId?: string; details?: string }\n ) {\n super(message);\n this.name = 'PoofError';\n this.code = code;\n this.status = options?.status;\n this.requestId = options?.requestId;\n this.details = options?.details;\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /** Create error from API response */\n static fromResponse(response: ApiErrorResponse, status: number): PoofError {\n const ErrorClass = ERROR_MAP[response.code] || PoofError;\n return new ErrorClass(response.message, response.code, {\n status,\n requestId: response.request_id,\n details: response.details,\n });\n }\n}\n\n/**\n * Thrown when the API key is invalid or missing\n */\nexport class AuthenticationError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown when the account doesn't have permission\n */\nexport class PermissionError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'PermissionError';\n }\n}\n\n/**\n * Thrown when the account has insufficient credits\n */\nexport class PaymentRequiredError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'PaymentRequiredError';\n }\n}\n\n/**\n * Thrown when rate limit is exceeded\n */\nexport class RateLimitError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Thrown when request parameters are invalid\n */\nexport class ValidationError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Thrown when a server error occurs\n */\nexport class ServerError extends PoofError {\n constructor(message: string, code: string, options?: { status?: number; requestId?: string; details?: string }) {\n super(message, code, options);\n this.name = 'ServerError';\n }\n}\n\n/** Map error codes to error classes */\nconst ERROR_MAP: Record<ErrorCode, typeof PoofError> = {\n authentication_error: AuthenticationError,\n permission_denied: PermissionError,\n payment_required: PaymentRequiredError,\n rate_limit_exceeded: RateLimitError,\n validation_error: ValidationError,\n missing_image: ValidationError,\n image_too_large: ValidationError,\n invalid_image: ValidationError,\n video_too_large: ValidationError,\n video_too_long: ValidationError,\n invalid_video: ValidationError,\n job_not_found: ValidationError,\n job_failed: PoofError,\n upstream_error: ServerError,\n internal_server_error: ServerError,\n};\n","import type { ImageInput, MediaInput, UrlInput } from './types.js';\n\n/** Check if running in Node.js environment */\nexport const isNode = typeof process !== 'undefined' && process.versions?.node;\n\n/** Detect MIME type from buffer */\nfunction detectMimeType(buffer: Uint8Array): string {\n // Check magic bytes\n if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {\n return 'image/png';\n }\n if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {\n return 'image/jpeg';\n }\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) {\n // RIFF header, check for WEBP\n if (buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {\n return 'image/webp';\n }\n }\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\n return 'image/gif';\n }\n // ISO base media file (MP4, MOV): 'ftyp' at offset 4\n if (buffer[4] === 0x66 && buffer[5] === 0x74 && buffer[6] === 0x79 && buffer[7] === 0x70) {\n // 'qt ' brand is QuickTime\n if (buffer[8] === 0x71 && buffer[9] === 0x74) {\n return 'video/quicktime';\n }\n return 'video/mp4';\n }\n // EBML header (WebM, Matroska)\n if (buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3) {\n return 'video/webm';\n }\n // Default to octet-stream\n return 'application/octet-stream';\n}\n\n/** Get file extension from MIME type */\nfunction getExtension(mimeType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'video/webm': 'webm',\n };\n return map[mimeType] || 'bin';\n}\n\n/** Convert various input types to a Blob suitable for FormData */\nexport async function toBlob(input: ImageInput): Promise<Blob> {\n // Already a Blob or File\n if (input instanceof Blob) {\n return input;\n }\n\n // ArrayBuffer\n if (input instanceof ArrayBuffer) {\n const uint8 = new Uint8Array(input);\n const mimeType = detectMimeType(uint8);\n return new Blob([input], { type: mimeType });\n }\n\n // Uint8Array or Node.js Buffer. Copy into a fresh ArrayBuffer-backed view:\n // a view over a SharedArrayBuffer (or a Buffer pool slice) is not a valid BlobPart.\n if (input instanceof Uint8Array || (isNode && Buffer.isBuffer(input))) {\n const bytes = Uint8Array.from(input);\n const mimeType = detectMimeType(bytes);\n return new Blob([bytes], { type: mimeType });\n }\n\n // String - treat as file path (Node.js only)\n if (typeof input === 'string') {\n if (!isNode) {\n throw new Error('File paths are only supported in Node.js. Use a Blob or File in the browser.');\n }\n \n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n \n const buffer = await fs.readFile(input);\n const uint8 = new Uint8Array(buffer);\n const mimeType = detectMimeType(uint8);\n const ext = path.extname(input).toLowerCase().slice(1);\n \n // Use file extension for mime type if available\n const mimeFromExt: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n mkv: 'video/x-matroska',\n };\n \n const finalMimeType = mimeFromExt[ext] || mimeType;\n return new Blob([buffer], { type: finalMimeType });\n }\n\n throw new Error(`Unsupported input type: ${typeof input}`);\n}\n\n/** Get filename for FormData */\nexport function getFilename(input: ImageInput, mimeType: string): string {\n // File has a name\n if (typeof File !== 'undefined' && input instanceof File) {\n return input.name;\n }\n\n // String path\n if (typeof input === 'string' && isNode) {\n // Extract filename from path\n const parts = input.split(/[/\\\\]/);\n return parts[parts.length - 1] || defaultFilename(mimeType);\n }\n\n // Generate name from mime type\n return defaultFilename(mimeType);\n}\n\nfunction defaultFilename(mimeType: string): string {\n const stem = mimeType.startsWith('video/') ? 'video' : 'image';\n return `${stem}.${getExtension(mimeType)}`;\n}\n\n/** Is the input a `{ url }` object rather than file contents? */\nexport function isUrlInput(input: MediaInput): input is UrlInput {\n return typeof input === 'object' && input !== null && 'url' in input && typeof (input as UrlInput).url === 'string';\n}\n\n/** Resolve after `ms` milliseconds */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import type {\n PoofOptions,\n MediaInput,\n RemoveBackgroundOptions,\n RemoveBackgroundResult,\n Job,\n JobStatus,\n WaitForJobOptions,\n AccountInfo,\n ApiErrorResponse,\n} from './types.js';\nimport { PoofError } from './errors.js';\nimport { toBlob, getFilename, isUrlInput, sleep } from './utils.js';\n\nconst DEFAULT_BASE_URL = 'https://api.poof.bg/v1';\nconst DEFAULT_TIMEOUT = 60000;\nconst DEFAULT_POLL_INTERVAL_MS = 3000;\nconst DEFAULT_JOB_TIMEOUT_MS = 600000;\n\n/**\n * Poof API client for background removal\n *\n * @example\n * ```typescript\n * import { Poof } from '@poof-bg/js';\n *\n * const poof = new Poof({ apiKey: 'your-api-key' });\n * const result = await poof.removeBackground(imageFile);\n * ```\n */\nexport class Poof {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(options: PoofOptions) {\n if (!options.apiKey) {\n throw new Error('API key is required');\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl?.replace(/\\/$/, '') || DEFAULT_BASE_URL;\n this.timeout = options.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Remove the background from an image or a video.\n *\n * Images are processed synchronously and come back as bytes. Videos are\n * processed as a job: the call returns a queued {@link Job}; poll it with\n * {@link getJob} / {@link waitForJob}, or pass `wait: true` to get the\n * completed job (with `resultUrl`) directly. Use {@link isJob} to tell the\n * two apart.\n *\n * @param input - File, Blob, Buffer, ArrayBuffer, Uint8Array, file path (Node.js), or `{ url }`\n * @param options - Processing options\n * @returns Processed image data and metadata, or a video Job\n *\n * @example\n * ```typescript\n * // Image\n * const result = await poof.removeBackground(file);\n * const imageBlob = new Blob([result.data], { type: result.metadata.contentType });\n *\n * // With options\n * const result = await poof.removeBackground(file, { format: 'webp', crop: true, size: 'medium' });\n *\n * // Exact 500x500 output, subject cropped and centred, never stretched\n * const result = await poof.removeBackground(file, { crop: true, width: 500, height: 500 });\n *\n * // Video: submit, then wait for the result\n * const job = await poof.removeBackground('./clip.mp4', { format: 'webm' });\n * const done = await poof.waitForJob(job);\n * console.log(done.resultUrl);\n *\n * // Video from a public URL, waiting inline\n * const done = await poof.removeBackground({ url: 'https://example.com/clip.mp4' }, { wait: true });\n * ```\n */\n async removeBackground(\n input: MediaInput,\n options: RemoveBackgroundOptions = {}\n ): Promise<RemoveBackgroundResult | Job> {\n const formData = new FormData();\n\n if (isUrlInput(input)) {\n formData.append('url', input.url);\n } else {\n const blob = await toBlob(input);\n const filename = getFilename(input, blob.type);\n formData.append('file', blob, filename);\n }\n\n // Add optional parameters\n if (options.format) formData.append('format', options.format);\n if (options.channels) formData.append('channels', options.channels);\n if (options.bgColor) formData.append('bg_color', options.bgColor);\n if (options.size) formData.append('size', options.size);\n if (options.crop !== undefined) formData.append('crop', String(options.crop));\n if (options.padding) formData.append('padding', options.padding);\n if (options.width !== undefined) formData.append('width', String(options.width));\n if (options.height !== undefined) formData.append('height', String(options.height));\n if (options.fit) formData.append('fit', options.fit);\n\n const response = await this.fetch(`${this.baseUrl}/remove`, {\n method: 'POST',\n body: formData,\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n // Videos are accepted as a job\n if (response.status === 202) {\n const job = toJob(await response.json());\n if (options.wait) {\n return this.waitForJob(job, options.wait === true ? {} : options.wait);\n }\n return job;\n }\n\n const data = await response.arrayBuffer();\n\n const matteConfidence = response.headers.get('X-Matte-Confidence');\n const matteAmbiguousRatio = response.headers.get('X-Matte-Ambiguous-Ratio');\n\n return {\n data,\n metadata: {\n requestId: response.headers.get('X-Request-ID') || '',\n processingTimeMs: parseInt(response.headers.get('X-Processing-Time-Ms') || '0', 10),\n width: parseInt(response.headers.get('X-Image-Width') || '0', 10),\n height: parseInt(response.headers.get('X-Image-Height') || '0', 10),\n contentType: response.headers.get('Content-Type') || 'image/png',\n matteConfidence: matteConfidence !== null ? parseFloat(matteConfidence) : undefined,\n matteAmbiguousRatio: matteAmbiguousRatio !== null ? parseFloat(matteAmbiguousRatio) : undefined,\n },\n };\n }\n\n /**\n * Get the current state of a video job. Polling is free and does not count\n * against your rate limit.\n *\n * @param jobId - The job ID returned by removeBackground()\n *\n * @example\n * ```typescript\n * const job = await poof.getJob('job_8f3a1c2e9b7d4a10');\n * console.log(job.status, job.progress);\n * ```\n */\n async getJob(jobId: string): Promise<Job> {\n const response = await this.fetch(`${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return toJob(await response.json());\n }\n\n /**\n * Poll a video job until it is completed.\n *\n * @param job - A Job or a job ID\n * @param options - Poll interval, timeout and progress callback\n * @returns The completed job; `resultUrl` is a direct download link valid for 24 hours\n * @throws PoofError with code `job_failed` if the job fails (credits are refunded),\n * or code `timeout` if `timeoutMs` elapses first\n *\n * @example\n * ```typescript\n * const done = await poof.waitForJob(job, {\n * onProgress: (j) => console.log(`${Math.round(j.progress * 100)}%`),\n * });\n * const video = await fetch(done.resultUrl!);\n * ```\n */\n async waitForJob(job: Job | string, options: WaitForJobOptions = {}): Promise<Job> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS;\n const deadline = Date.now() + timeoutMs;\n\n let current: Job = typeof job === 'string' ? await this.getJob(job) : job;\n options.onProgress?.(current);\n\n while (!isTerminal(current.status)) {\n if (Date.now() >= deadline) {\n throw new PoofError(\n `Timed out after ${timeoutMs}ms waiting for job ${current.id}`,\n 'timeout',\n { status: 408 }\n );\n }\n await sleep(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));\n current = await this.getJob(current.id);\n options.onProgress?.(current);\n }\n\n if (current.status === 'failed') {\n throw new PoofError(\n current.error?.message || `Job ${current.id} failed`,\n 'job_failed',\n { details: current.error?.code }\n );\n }\n\n return current;\n }\n\n /**\n * Get account information\n *\n * @returns Account info including plan and credit usage\n *\n * @example\n * ```typescript\n * const account = await poof.me();\n * console.log(`Plan: ${account.plan}`);\n * console.log(`Credits: ${account.usedCredits}/${account.maxCredits}`);\n * ```\n */\n async me(): Promise<AccountInfo> {\n const response = await this.fetch(`${this.baseUrl}/me`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return response.json();\n }\n\n /** Make a fetch request with auth and timeout */\n private async fetch(url: string, init: RequestInit): Promise<Response> {\n const headers = new Headers(init.headers);\n headers.set('x-api-key', this.apiKey);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n return response;\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new PoofError('Request timeout', 'timeout', { status: 408 });\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /** Handle error response */\n private async handleError(response: Response): Promise<never> {\n let errorData: ApiErrorResponse;\n\n try {\n errorData = await response.json();\n } catch {\n throw new PoofError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'unknown_error',\n { status: response.status }\n );\n }\n\n throw PoofError.fromResponse(errorData, response.status);\n }\n}\n\n/**\n * Type guard: did removeBackground() return a video Job rather than image bytes?\n *\n * @example\n * ```typescript\n * const result = await poof.removeBackground(input);\n * if (isJob(result)) {\n * const done = await poof.waitForJob(result);\n * } else {\n * fs.writeFileSync('output.png', Buffer.from(result.data));\n * }\n * ```\n */\nexport function isJob(value: RemoveBackgroundResult | Job): value is Job {\n return typeof value === 'object' && value !== null && 'status' in value && typeof (value as Job).id === 'string';\n}\n\nfunction isTerminal(status: JobStatus): boolean {\n return status === 'completed' || status === 'failed';\n}\n\n/** The job object as the API returns it (snake_case) */\ninterface RawJob {\n id: string;\n status: JobStatus;\n progress: number;\n created_at: string;\n started_at: string | null;\n completed_at: string | null;\n duration_seconds: number;\n fps: number;\n width: number;\n height: number;\n frames: number;\n credits: number;\n format: Job['format'];\n channels: Job['channels'];\n status_url: string;\n result_url: string | null;\n expires_at: string | null;\n error: Job['error'];\n stats: Job['stats'];\n}\n\nfunction toJob(raw: RawJob): Job {\n return {\n id: raw.id,\n status: raw.status,\n progress: raw.progress ?? 0,\n createdAt: raw.created_at,\n startedAt: raw.started_at ?? null,\n completedAt: raw.completed_at ?? null,\n durationSeconds: raw.duration_seconds,\n fps: raw.fps,\n width: raw.width,\n height: raw.height,\n frames: raw.frames,\n credits: raw.credits,\n format: raw.format,\n channels: raw.channels,\n statusUrl: raw.status_url,\n resultUrl: raw.result_url ?? null,\n expiresAt: raw.expires_at ?? null,\n error: raw.error ?? null,\n stats: raw.stats ?? null,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/client.ts"],"names":[],"mappings":";AAaO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA;AAAA,EAE1B,IAA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,CAAI,OAAA;AAAA,IACb,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,UAAU,GAAA,CAAI,QAAA;AAAA,IACd,WAAW,GAAA,CAAI,UAAA;AAAA,IACf,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,SAAA,EAAW,IAAI,UAAA,IAAc,IAAA;AAAA,IAC7B,KAAA,EAAO,IAAI,KAAA,IAAS,IAAA;AAAA,IACpB,KAAA,EAAO,IAAI,KAAA,IAAS;AAAA,GACtB;AACF","file":"index.js","sourcesContent":["import type { ErrorCode, ApiErrorResponse, ErrorDetails } from './types.js';\n\n/** Options accepted by every Poof error class */\nexport interface PoofErrorOptions {\n status?: number;\n requestId?: string;\n details?: ErrorDetails;\n docUrl?: string;\n}\n\n/**\n * Base error class for all Poof SDK errors\n */\nexport class PoofError extends Error {\n /** Machine-readable error code */\n readonly code: string;\n /** HTTP status code */\n readonly status?: number;\n /** Unique request ID for support */\n readonly requestId?: string;\n /** Additional details: an object for validation errors (e.g. { field: 'crop' }), or a string */\n readonly details?: ErrorDetails;\n /** Link to the documentation page for this error code */\n readonly docUrl?: string;\n\n constructor(\n message: string,\n code: string,\n options?: PoofErrorOptions\n ) {\n super(message);\n this.name = 'PoofError';\n this.code = code;\n this.status = options?.status;\n this.requestId = options?.requestId;\n this.details = options?.details;\n this.docUrl = options?.docUrl;\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /** Create error from API response */\n static fromResponse(response: ApiErrorResponse, status: number): PoofError {\n const ErrorClass = ERROR_MAP[response.code] || PoofError;\n return new ErrorClass(response.message, response.code, {\n status,\n requestId: response.request_id,\n details: response.details,\n docUrl: response.doc_url,\n });\n }\n}\n\n/**\n * Thrown when the API key is invalid or missing\n */\nexport class AuthenticationError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown when the account doesn't have permission\n */\nexport class PermissionError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'PermissionError';\n }\n}\n\n/**\n * Thrown when the account has insufficient credits\n */\nexport class PaymentRequiredError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'PaymentRequiredError';\n }\n}\n\n/**\n * Thrown when rate limit is exceeded\n */\nexport class RateLimitError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Thrown when request parameters are invalid\n */\nexport class ValidationError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Thrown when a server error occurs\n */\nexport class ServerError extends PoofError {\n constructor(message: string, code: string, options?: PoofErrorOptions) {\n super(message, code, options);\n this.name = 'ServerError';\n }\n}\n\n/** Map error codes to error classes */\nconst ERROR_MAP: Record<ErrorCode, typeof PoofError> = {\n authentication_error: AuthenticationError,\n permission_denied: PermissionError,\n payment_required: PaymentRequiredError,\n rate_limit_exceeded: RateLimitError,\n validation_error: ValidationError,\n missing_image: ValidationError,\n image_too_large: ValidationError,\n invalid_image: ValidationError,\n processing_failed: ServerError,\n not_found: PoofError,\n video_too_large: ValidationError,\n video_too_long: ValidationError,\n invalid_video: ValidationError,\n job_not_found: ValidationError,\n job_failed: PoofError,\n upstream_error: ServerError,\n internal_server_error: ServerError,\n};\n","import type { ImageInput, MediaInput, UrlInput } from './types.js';\n\n/** Check if running in Node.js environment */\nexport const isNode = typeof process !== 'undefined' && process.versions?.node;\n\n/** Detect MIME type from buffer */\nfunction detectMimeType(buffer: Uint8Array): string {\n // Check magic bytes\n if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {\n return 'image/png';\n }\n if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {\n return 'image/jpeg';\n }\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) {\n // RIFF header, check for WEBP\n if (buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {\n return 'image/webp';\n }\n }\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\n return 'image/gif';\n }\n // ISO base media file (MP4, MOV): 'ftyp' at offset 4\n if (buffer[4] === 0x66 && buffer[5] === 0x74 && buffer[6] === 0x79 && buffer[7] === 0x70) {\n // 'qt ' brand is QuickTime\n if (buffer[8] === 0x71 && buffer[9] === 0x74) {\n return 'video/quicktime';\n }\n return 'video/mp4';\n }\n // EBML header (WebM, Matroska)\n if (buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3) {\n return 'video/webm';\n }\n // Default to octet-stream\n return 'application/octet-stream';\n}\n\n/** Get file extension from MIME type */\nfunction getExtension(mimeType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'video/webm': 'webm',\n };\n return map[mimeType] || 'bin';\n}\n\n/** Convert various input types to a Blob suitable for FormData */\nexport async function toBlob(input: ImageInput): Promise<Blob> {\n // Already a Blob or File\n if (input instanceof Blob) {\n return input;\n }\n\n // ArrayBuffer\n if (input instanceof ArrayBuffer) {\n const uint8 = new Uint8Array(input);\n const mimeType = detectMimeType(uint8);\n return new Blob([input], { type: mimeType });\n }\n\n // Uint8Array or Node.js Buffer. Copy into a fresh ArrayBuffer-backed view:\n // a view over a SharedArrayBuffer (or a Buffer pool slice) is not a valid BlobPart.\n if (input instanceof Uint8Array || (isNode && Buffer.isBuffer(input))) {\n const bytes = Uint8Array.from(input);\n const mimeType = detectMimeType(bytes);\n return new Blob([bytes], { type: mimeType });\n }\n\n // String - treat as file path (Node.js only)\n if (typeof input === 'string') {\n if (!isNode) {\n throw new Error('File paths are only supported in Node.js. Use a Blob or File in the browser.');\n }\n \n const fs = await import('node:fs/promises');\n const path = await import('node:path');\n \n const buffer = await fs.readFile(input);\n const uint8 = new Uint8Array(buffer);\n const mimeType = detectMimeType(uint8);\n const ext = path.extname(input).toLowerCase().slice(1);\n \n // Use file extension for mime type if available\n const mimeFromExt: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n mov: 'video/quicktime',\n webm: 'video/webm',\n mkv: 'video/x-matroska',\n };\n \n const finalMimeType = mimeFromExt[ext] || mimeType;\n return new Blob([buffer], { type: finalMimeType });\n }\n\n throw new Error(`Unsupported input type: ${typeof input}`);\n}\n\n/** Get filename for FormData */\nexport function getFilename(input: ImageInput, mimeType: string): string {\n // File has a name\n if (typeof File !== 'undefined' && input instanceof File) {\n return input.name;\n }\n\n // String path\n if (typeof input === 'string' && isNode) {\n // Extract filename from path\n const parts = input.split(/[/\\\\]/);\n return parts[parts.length - 1] || defaultFilename(mimeType);\n }\n\n // Generate name from mime type\n return defaultFilename(mimeType);\n}\n\nfunction defaultFilename(mimeType: string): string {\n const stem = mimeType.startsWith('video/') ? 'video' : 'image';\n return `${stem}.${getExtension(mimeType)}`;\n}\n\n/** Is the input a `{ url }` object rather than file contents? */\nexport function isUrlInput(input: MediaInput): input is UrlInput {\n return typeof input === 'object' && input !== null && 'url' in input && typeof (input as UrlInput).url === 'string';\n}\n\n/** Resolve after `ms` milliseconds */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import type {\n PoofOptions,\n MediaInput,\n RemoveBackgroundOptions,\n RemoveBackgroundResult,\n Job,\n JobStatus,\n WaitForJobOptions,\n AccountInfo,\n ApiErrorResponse,\n} from './types.js';\nimport { PoofError } from './errors.js';\nimport { toBlob, getFilename, isUrlInput, sleep } from './utils.js';\n\nconst DEFAULT_BASE_URL = 'https://api.poof.bg/v1';\nconst DEFAULT_TIMEOUT = 60000;\nconst DEFAULT_POLL_INTERVAL_MS = 3000;\nconst DEFAULT_JOB_TIMEOUT_MS = 600000;\n\n/**\n * Poof API client for background removal\n *\n * @example\n * ```typescript\n * import { Poof } from '@poof-bg/js';\n *\n * const poof = new Poof({ apiKey: 'your-api-key' });\n * const result = await poof.removeBackground(imageFile);\n * ```\n */\nexport class Poof {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n\n constructor(options: PoofOptions) {\n if (!options.apiKey) {\n throw new Error('API key is required');\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl?.replace(/\\/$/, '') || DEFAULT_BASE_URL;\n this.timeout = options.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Remove the background from an image or a video.\n *\n * Images are processed synchronously and come back as bytes. Videos are\n * processed as a job: the call returns a queued {@link Job}; poll it with\n * {@link getJob} / {@link waitForJob}, or pass `wait: true` to get the\n * completed job (with `resultUrl`) directly. Use {@link isJob} to tell the\n * two apart.\n *\n * @param input - File, Blob, Buffer, ArrayBuffer, Uint8Array, file path (Node.js), or `{ url }`\n * @param options - Processing options\n * @returns Processed image data and metadata, or a video Job\n *\n * @example\n * ```typescript\n * // Image\n * const result = await poof.removeBackground(file);\n * const imageBlob = new Blob([result.data], { type: result.metadata.contentType });\n *\n * // With options\n * const result = await poof.removeBackground(file, { format: 'webp', crop: true, size: 'medium' });\n *\n * // Exact 500x500 output, subject cropped and centred, never stretched\n * const result = await poof.removeBackground(file, { crop: true, width: 500, height: 500 });\n *\n * // Video: submit, then wait for the result\n * const job = await poof.removeBackground('./clip.mp4', { format: 'webm' });\n * const done = await poof.waitForJob(job);\n * console.log(done.resultUrl);\n *\n * // Video from a public URL, waiting inline\n * const done = await poof.removeBackground({ url: 'https://example.com/clip.mp4' }, { wait: true });\n * ```\n */\n async removeBackground(\n input: MediaInput,\n options: RemoveBackgroundOptions = {}\n ): Promise<RemoveBackgroundResult | Job> {\n const formData = new FormData();\n\n if (isUrlInput(input)) {\n formData.append('url', input.url);\n } else {\n const blob = await toBlob(input);\n const filename = getFilename(input, blob.type);\n formData.append('file', blob, filename);\n }\n\n // Add optional parameters\n if (options.format) formData.append('format', options.format);\n if (options.channels) formData.append('channels', options.channels);\n if (options.bgColor) formData.append('bg_color', options.bgColor);\n if (options.size) formData.append('size', options.size);\n // crop defaults to false and is image-only: only send it when enabled, so\n // `crop: false` on a video is not rejected with a validation_error.\n if (options.crop === true) formData.append('crop', 'true');\n else if (typeof options.crop === 'string' && options.crop) formData.append('crop', options.crop);\n if (options.padding) formData.append('padding', options.padding);\n if (options.width !== undefined) formData.append('width', String(options.width));\n if (options.height !== undefined) formData.append('height', String(options.height));\n if (options.fit) formData.append('fit', options.fit);\n\n const response = await this.fetch(`${this.baseUrl}/remove`, {\n method: 'POST',\n body: formData,\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n // Videos are accepted as a job\n if (response.status === 202) {\n const job = toJob(await response.json());\n if (options.wait) {\n return this.waitForJob(job, options.wait === true ? {} : options.wait);\n }\n return job;\n }\n\n const data = await response.arrayBuffer();\n\n const matteConfidence = response.headers.get('X-Matte-Confidence');\n const matteAmbiguousRatio = response.headers.get('X-Matte-Ambiguous-Ratio');\n\n return {\n data,\n metadata: {\n requestId: response.headers.get('X-Request-ID') || '',\n processingTimeMs: parseInt(response.headers.get('X-Processing-Time-Ms') || '0', 10),\n width: parseInt(response.headers.get('X-Image-Width') || '0', 10),\n height: parseInt(response.headers.get('X-Image-Height') || '0', 10),\n contentType: response.headers.get('Content-Type') || 'image/png',\n matteConfidence: matteConfidence !== null ? parseFloat(matteConfidence) : undefined,\n matteAmbiguousRatio: matteAmbiguousRatio !== null ? parseFloat(matteAmbiguousRatio) : undefined,\n },\n };\n }\n\n /**\n * Get the current state of a video job. Polling is free and does not count\n * against your rate limit.\n *\n * @param jobId - The job ID returned by removeBackground()\n *\n * @example\n * ```typescript\n * const job = await poof.getJob('job_8f3a1c2e9b7d4a10');\n * console.log(job.status, job.progress);\n * ```\n */\n async getJob(jobId: string): Promise<Job> {\n const response = await this.fetch(`${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return toJob(await response.json());\n }\n\n /**\n * Poll a video job until it is completed.\n *\n * @param job - A Job or a job ID\n * @param options - Poll interval, timeout and progress callback\n * @returns The completed job; `resultUrl` is a direct download link valid for 24 hours\n * @throws PoofError with code `job_failed` if the job fails (credits are refunded),\n * or code `timeout` if `timeoutMs` elapses first\n *\n * @example\n * ```typescript\n * const done = await poof.waitForJob(job, {\n * onProgress: (j) => console.log(`${Math.round(j.progress * 100)}%`),\n * });\n * const video = await fetch(done.resultUrl!);\n * ```\n */\n async waitForJob(job: Job | string, options: WaitForJobOptions = {}): Promise<Job> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS;\n const deadline = Date.now() + timeoutMs;\n\n let current: Job = typeof job === 'string' ? await this.getJob(job) : job;\n options.onProgress?.(current);\n\n while (!isTerminal(current.status)) {\n if (Date.now() >= deadline) {\n throw new PoofError(\n `Timed out after ${timeoutMs}ms waiting for job ${current.id}`,\n 'timeout',\n { status: 408 }\n );\n }\n await sleep(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));\n current = await this.getJob(current.id);\n options.onProgress?.(current);\n }\n\n if (current.status === 'failed') {\n throw new PoofError(\n current.error?.message || `Job ${current.id} failed`,\n 'job_failed',\n { details: current.error?.code }\n );\n }\n\n return current;\n }\n\n /**\n * Get account information\n *\n * @returns Account info including plan and credit usage\n *\n * @example\n * ```typescript\n * const account = await poof.me();\n * console.log(`Plan: ${account.plan}`);\n * console.log(`Credits: ${account.usedCredits}/${account.maxCredits}`);\n * ```\n */\n async me(): Promise<AccountInfo> {\n const response = await this.fetch(`${this.baseUrl}/me`, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n await this.handleError(response);\n }\n\n return response.json();\n }\n\n /** Make a fetch request with auth and timeout */\n private async fetch(url: string, init: RequestInit): Promise<Response> {\n const headers = new Headers(init.headers);\n headers.set('x-api-key', this.apiKey);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n return response;\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new PoofError('Request timeout', 'timeout', { status: 408 });\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /** Handle error response */\n private async handleError(response: Response): Promise<never> {\n let errorData: ApiErrorResponse;\n\n try {\n errorData = await response.json();\n } catch {\n throw new PoofError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'unknown_error',\n { status: response.status }\n );\n }\n\n throw PoofError.fromResponse(errorData, response.status);\n }\n}\n\n/**\n * Type guard: did removeBackground() return a video Job rather than image bytes?\n *\n * @example\n * ```typescript\n * const result = await poof.removeBackground(input);\n * if (isJob(result)) {\n * const done = await poof.waitForJob(result);\n * } else {\n * fs.writeFileSync('output.png', Buffer.from(result.data));\n * }\n * ```\n */\nexport function isJob(value: RemoveBackgroundResult | Job): value is Job {\n return typeof value === 'object' && value !== null && 'status' in value && typeof (value as Job).id === 'string';\n}\n\nfunction isTerminal(status: JobStatus): boolean {\n return status === 'completed' || status === 'failed';\n}\n\n/** The job object as the API returns it (snake_case) */\ninterface RawJob {\n id: string;\n status: JobStatus;\n progress: number;\n created_at: string;\n started_at: string | null;\n completed_at: string | null;\n duration_seconds: number;\n fps: number;\n width: number;\n height: number;\n frames: number;\n credits: number;\n format: Job['format'];\n channels: Job['channels'];\n status_url: string;\n result_url: string | null;\n expires_at: string | null;\n error: Job['error'];\n stats: Job['stats'];\n}\n\nfunction toJob(raw: RawJob): Job {\n return {\n id: raw.id,\n status: raw.status,\n progress: raw.progress ?? 0,\n createdAt: raw.created_at,\n startedAt: raw.started_at ?? null,\n completedAt: raw.completed_at ?? null,\n durationSeconds: raw.duration_seconds,\n fps: raw.fps,\n width: raw.width,\n height: raw.height,\n frames: raw.frames,\n credits: raw.credits,\n format: raw.format,\n channels: raw.channels,\n statusUrl: raw.status_url,\n resultUrl: raw.result_url ?? null,\n expiresAt: raw.expires_at ?? null,\n error: raw.error ?? null,\n stats: raw.stats ?? null,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@poof-bg/js",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Official Poof SDK for image and video background removal",
5
5
  "author": "Poof <support@poof.bg>",
6
6
  "license": "MIT",