@keeratita/heic-converter 0.5.2 → 0.6.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/dist/index.d.mts DELETED
@@ -1,565 +0,0 @@
1
- interface DecodedImage {
2
- width: number;
3
- height: number;
4
- /**
5
- * RGBA pixel data, interleaved, row-major, 4 bytes per pixel.
6
- *
7
- * The buffer is always a plain `ArrayBuffer` owned by the returned array
8
- * (never a view into the WASM heap), so it stays valid after
9
- * `LibheifDecoder.free()` and can be passed directly to
10
- * `new ImageData(...)` / `putImageData` — including the `ImageData`
11
- * overload that requires `Uint8ClampedArray<ArrayBuffer>` under TS >= 5.7.
12
- */
13
- data: Uint8ClampedArray;
14
- /**
15
- * Raw EXIF block copied from the source file, normalized to the JPEG APP1
16
- * payload form: `"Exif\0\0"` followed by the TIFF structure. Present when
17
- * the file carries an Exif item — including files where libheif already
18
- * applied `irot`/`imir` (the block is reported independently of
19
- * {@link DecodedImage.orientation}).
20
- *
21
- * `convertHeic` re-injects this block into JPEG (APP1) and PNG (`eXIf`)
22
- * output when `preserveExif: true`; raw-decode consumers can attach it to
23
- * their own encoder output (e.g. `sharp`'s `.withMetadata({ exif })`).
24
- * Owned by the returned object; never a WASM-heap view.
25
- */
26
- exif?: Uint8Array;
27
- /**
28
- * EXIF orientation of the **stored** pixels (1–8, EXIF tag 274 semantics;
29
- * 1 = upright). Absent or 1 means no rotation is pending.
30
- *
31
- * libheif already applies `irot`/`imir` container transforms during
32
- * decode — for those files this is 1 and the pixels are upright. A value
33
- * > 1 means the orientation comes only from the Exif item: `convertHeic`
34
- * applies it automatically (unless `applyOrientation: false`), while raw
35
- * `decode()` consumers get stored pixels and must apply it themselves.
36
- * Decoders that do not report orientation may omit this field.
37
- */
38
- orientation?: number;
39
- }
40
- /**
41
- * Decoder contract used by {@link ConvertOptions.decoder} /
42
- * {@link ConvertManyOptions.decoder} and implemented by `LibheifDecoder`.
43
- *
44
- * Lifecycle rules followed by the library (implementations may rely on them):
45
- * - `initialize()` is called before every `decode()`; implementations must
46
- * make repeated/concurrent calls cheap (e.g. memoize the load promise).
47
- * - `decode()` is awaited before the library calls `free()`; the returned
48
- * `DecodedImage` must therefore not reference decoder-owned memory that
49
- * `free()` releases (copy pixels out, as `LibheifDecoder` does).
50
- * - `free()` is called at most once per conversion. Decoders **injected** via
51
- * options are never freed by the library — the caller owns their lifetime.
52
- *
53
- * Concurrency: with `convertMany`, a single injected decoder is shared by
54
- * all concurrent conversions, so `decode()` must be safe to call concurrently
55
- * on one instance (no shared mutable state across in-flight decodes).
56
- */
57
- interface IHeicDecoder {
58
- /**
59
- * Initializes the decoder (e.g., loading WebAssembly module).
60
- */
61
- initialize(): Promise<void>;
62
- /**
63
- * Decodes HEIC binary data into raw RGBA pixel data.
64
- * @param data The HEIC file as a Uint8Array.
65
- * @param onProgress Optional progress callback that receives the progress percentage.
66
- */
67
- decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
68
- /**
69
- * Cleans up allocated resources. Idempotent: safe to call multiple times.
70
- */
71
- free(): void;
72
- }
73
- type ImageFormat = 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp' | 'avif';
74
- /**
75
- * Formats accepted by {@link ConvertOptions.to} (case-insensitive).
76
- * `'jpg'` is an alias of `'jpeg'`. `'avif'` requires an environment whose
77
- * canvas can encode AVIF (Chromium/Firefox today); elsewhere it rejects with
78
- * `format_unsupported`.
79
- */
80
- declare const SUPPORTED_FORMATS: readonly ImageFormat[];
81
- /** Default JPEG/WebP encoding quality used when `quality` is not provided. */
82
- declare const DEFAULT_QUALITY = 0.92;
83
- type HeicInput = Blob | File | ArrayBuffer | Uint8Array;
84
- /**
85
- * How {@link convertHeic} returns the converted image.
86
- * - `'blob'` — a `Blob` (the default; browser-native, works everywhere)
87
- * - `'dataUrl'` — a `data:image/...;base64,…` string (previews, `<img src>`)
88
- * - `'arrayBuffer'` — raw bytes (uploads, WebCodecs, Node-friendly transfer)
89
- */
90
- type OutputShape = 'blob' | 'dataUrl' | 'arrayBuffer';
91
- /** Resolved return type of `convertHeic`/`convertMany` for an output shape. */
92
- type ConvertResult<S extends OutputShape> = S extends 'dataUrl' ? string : S extends 'arrayBuffer' ? ArrayBuffer : Blob;
93
- /** Crop rectangle in **post-orientation display pixels** (top-left origin). */
94
- interface CropOptions {
95
- /** Left edge of the crop box. @default 0 */
96
- x?: number;
97
- /** Top edge of the crop box. @default 0 */
98
- y?: number;
99
- /** Crop width in pixels. Must be a positive integer and fit inside the image. */
100
- width: number;
101
- /** Crop height in pixels. Must be a positive integer and fit inside the image. */
102
- height: number;
103
- }
104
- /** Per-item outcome when `continueOnError: true`. */
105
- type ConvertItemResult<T = Blob> = {
106
- index: number;
107
- ok: true;
108
- result: T;
109
- } | {
110
- index: number;
111
- ok: false;
112
- error: Error;
113
- };
114
- interface ResizeOptions {
115
- /**
116
- * Maximum width in pixels. The image is downscaled to fit within this
117
- * bound while preserving the aspect ratio. Images smaller than the bound
118
- * are never upscaled.
119
- */
120
- maxWidth?: number;
121
- /**
122
- * Maximum height in pixels. The image is downscaled to fit within this
123
- * bound while preserving the aspect ratio. Images smaller than the bound
124
- * are never upscaled.
125
- */
126
- maxHeight?: number;
127
- /**
128
- * Uniform scale factor applied to both dimensions (e.g. 0.5 halves the
129
- * image). Takes precedence over `maxWidth` and `maxHeight` when set.
130
- */
131
- scale?: number;
132
- }
133
- interface ConvertOptions extends ResizeOptions {
134
- /**
135
- * Target format for the conversion. Must be one of the values in
136
- * {@link SUPPORTED_FORMATS}; an unknown value is rejected up front,
137
- * before the input is decoded.
138
- * @default 'jpeg'
139
- */
140
- to?: ImageFormat;
141
- /**
142
- * Quality of the converted image, between 0.0 and 1.0 (inclusive).
143
- * Applicable for 'jpeg', 'jpg', 'webp', and 'avif' formats — but validated
144
- * for every format: passing an out-of-range value (e.g. `90` from a 0-100
145
- * scale) throws regardless of `to`.
146
- * @default 0.92
147
- */
148
- quality?: number;
149
- /**
150
- * Optional custom decoder implementation to inject.
151
- * If not provided, a default LibheifDecoder is used.
152
- * The library never calls `free()` on an injected decoder.
153
- */
154
- decoder?: IHeicDecoder;
155
- /**
156
- * Optional progress callback that receives the progress percentage during
157
- * decoding. Values are normalized and clamped to the range 0 to 100; the
158
- * final 100% is emitted only when the conversion succeeds. A callback that
159
- * throws rejects the conversion with `progress_callback_failed`.
160
- */
161
- onProgress?: (percent: number) => void;
162
- /**
163
- * Rotate/flip the output so it matches the source's EXIF orientation
164
- * (applied as a canvas transform during rendering; `irot`/`imir` container
165
- * transforms are already applied by the decoder and never stacked on top).
166
- * Set `false` to keep the exact stored-pixel geometry. A non-boolean value
167
- * is rejected up front with `invalid_input`.
168
- * @default true
169
- */
170
- applyOrientation?: boolean;
171
- /**
172
- * Representation of the converted image. See {@link OutputShape}.
173
- * @default 'blob'
174
- */
175
- output?: OutputShape;
176
- /**
177
- * AbortSignal that cancels the conversion. Cancellation is checked at
178
- * stage boundaries (input read, decoder init, before/after decode,
179
- * before encode) and aborts `convertHeicInWorker` calls immediately by
180
- * terminating the worker; the synchronous WASM decode itself cannot be
181
- * preempted mid-call. An aborted signal rejects with code `aborted`.
182
- */
183
- signal?: AbortSignal;
184
- /**
185
- * Crop rectangle in post-orientation display pixels (the geometry the
186
- * image will be displayed in). Applied before resize: `scale`/`maxWidth`/
187
- * `maxHeight` then downscale the cropped region. Out-of-bounds crops
188
- * reject with `invalid_crop`.
189
- */
190
- crop?: CropOptions;
191
- /**
192
- * Copy the source HEIC's EXIF block into JPEG (APP1) and PNG (`eXIf`
193
- * chunk) output so converted files keep camera metadata (orientation,
194
- * GPS, timestamps). Note this **preserves private data** like GPS — set
195
- * deliberately. Ignored for `webp`/`svg` output.
196
- * @default false
197
- */
198
- preserveExif?: boolean;
199
- }
200
- interface ConvertManyOptions extends Omit<ConvertOptions, 'onProgress'> {
201
- /**
202
- * Maximum number of conversions running concurrently.
203
- * @default 4
204
- */
205
- concurrency?: number;
206
- /**
207
- * Optional progress callback that receives the item index (0-based) and
208
- * its progress percentage (normalized to 0 to 100) during decoding.
209
- */
210
- onProgress?: (index: number, percent: number) => void;
211
- /**
212
- * Optional custom decoder implementation to inject. When provided, the
213
- * same instance is shared by all concurrent conversions, so it must be
214
- * safe for concurrent `decode()` calls (see {@link IHeicDecoder}). If not
215
- * provided, a fresh default LibheifDecoder is created per item.
216
- */
217
- decoder?: IHeicDecoder;
218
- /**
219
- * Resolve with per-item results instead of rejecting the whole batch on
220
- * the first failure: the promise fulfills with `ConvertItemResult[]` in
221
- * input order, each item `{ index, ok: true, result }` or
222
- * `{ index, ok: false, error }`. All items always run to completion.
223
- * Up-front option validation failures still reject normally (a typo is a
224
- * caller bug, not an item failure).
225
- * @default false
226
- */
227
- continueOnError?: boolean;
228
- /**
229
- * Reuse one library-owned `LibheifDecoder` per concurrent runner across
230
- * items instead of creating (and WASM-initializing) a fresh instance per
231
- * item — amortizes the module load in large batches while preserving the
232
- * exclusive-use invariant (an instance is only ever held by one runner,
233
- * never decodes concurrently). Ignored when `decoder` is injected.
234
- * @default false
235
- */
236
- reuseDecoders?: boolean;
237
- }
238
-
239
- interface LibheifDecoderOptions {
240
- /**
241
- * Custom function to locate the WASM file.
242
- * Useful when serving the WASM file from a custom route or CDN.
243
- */
244
- locateFile?: (path: string, prefix: string) => string;
245
- /**
246
- * Raw WASM binary buffer. If provided, the library will use this buffer
247
- * directly instead of attempting to fetch the WASM file. Accepts an
248
- * `ArrayBuffer` or any `ArrayBufferView` (e.g. a Node.js `Buffer` from
249
- * `fs.readFileSync`).
250
- */
251
- wasmBinary?: ArrayBuffer | ArrayBufferView;
252
- /**
253
- * Advanced: extra properties merged into the Emscripten module argument
254
- * object (e.g. `instantiateWasm` for streaming compilation). Prefer
255
- * `locateFile`/`wasmBinary` for the common cases; keys provided here must
256
- * not collide with them.
257
- */
258
- moduleOverrides?: Record<string, unknown>;
259
- }
260
- declare class LibheifDecoder implements IHeicDecoder {
261
- private options?;
262
- private module;
263
- private decoderInstance;
264
- /**
265
- * Memoized module-loading promise so concurrent initialize()/decode() calls
266
- * on the same instance never instantiate (or mutate) the module twice.
267
- * Resolves null when a concurrent free() discarded the freshly created
268
- * instance (see initGeneration).
269
- */
270
- private initPromise;
271
- /**
272
- * Generation counter for init/free races: a load that finishes after a
273
- * concurrent free() must not resurrect module/decoderInstance.
274
- */
275
- private initGeneration;
276
- constructor(options?: LibheifDecoderOptions);
277
- /**
278
- * Initializes the WebAssembly module and instantiates the HEIC decoder.
279
- * Safe to call concurrently: the module is loaded at most once per instance.
280
- */
281
- initialize(): Promise<void>;
282
- /**
283
- * Decodes HEIC binary data into raw RGBA pixel data.
284
- * @param data The HEIC file contents as a Uint8Array.
285
- * @param onProgress Optional progress callback (receives a normalized
286
- * percentage clamped to 0-100).
287
- */
288
- decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
289
- /**
290
- * Cleans up the WebAssembly decoder instance and resources.
291
- * Idempotent: safe to call multiple times. After free(), the next
292
- * initialize() — or decode() directly, which re-initializes transparently
293
- * — loads a fresh module.
294
- *
295
- * free() is also safe to call while initialize() is in flight: a load that
296
- * completes after free() discards its fresh instance instead of leaking it.
297
- */
298
- free(): void;
299
- }
300
-
301
- interface WorkerConvertOptions extends Omit<ConvertOptions, 'decoder'> {
302
- /**
303
- * URL of the worker script that performs the conversion. Should be a
304
- * compile-time constant (e.g. `new URL('./worker.js', import.meta.url)`
305
- * under a bundler); the script runs with the page's privileges.
306
- */
307
- workerUrl: string | URL;
308
- /**
309
- * Maximum time in milliseconds to wait for the worker result before
310
- * rejecting with a timeout (queueing for a free worker slot counts toward
311
- * this). Defaults to 60000 (60s). Set to 0 to disable the timeout.
312
- */
313
- timeoutMs?: number;
314
- /**
315
- * Worker script type. Use `'module'` when the script uses ES module
316
- * imports (e.g. `import { convertHeic } from ...`); `'classic'`
317
- * scripts must be pre-bundled.
318
- * @default 'classic'
319
- */
320
- workerType?: 'classic' | 'module';
321
- /**
322
- * Upper bound on simultaneously live workers for this worker script.
323
- * Calls beyond the bound queue until a slot frees, which keeps bulk
324
- * conversions (`inputs.map(i => convertHeicInWorker(i, …))`) from
325
- * exhausting memory or the browser's worker limit.
326
- * Defaults to `navigator.hardwareConcurrency` clamped to 1–8.
327
- */
328
- maxConcurrentWorkers?: number;
329
- }
330
- /** Progress message a worker script posts to report decode progress. */
331
- interface WorkerProgressMessage {
332
- type: 'progress';
333
- percent: number;
334
- }
335
- /** Result message a worker script posts to settle a conversion. */
336
- interface WorkerResultMessage {
337
- type: 'result';
338
- ok: boolean;
339
- /**
340
- * The converted image exactly as `convertHeic` returned it inside the
341
- * worker: a Blob, a data-URL string (`output: 'dataUrl'`), or an
342
- * ArrayBuffer (`output: 'arrayBuffer'`). The field name `blob` is kept
343
- * for protocol compatibility.
344
- */
345
- blob?: Blob | string | ArrayBuffer;
346
- error?: string;
347
- }
348
- /**
349
- * Options for {@link convertManyInWorker}: the {@link convertHeicInWorker}
350
- * worker options plus the batch semantics of `convertMany`.
351
- */
352
- interface WorkerBatchOptions extends Omit<WorkerConvertOptions, 'onProgress'> {
353
- /**
354
- * Per-item progress callback: receives the 0-based item index and its
355
- * progress percentage (normalized 0–100). Fires only for successful items.
356
- */
357
- onProgress?: (index: number, percent: number) => void;
358
- /**
359
- * Resolve with per-item results instead of rejecting the batch on the
360
- * first failure; all items run to completion (see
361
- * `ConvertManyOptions.continueOnError`).
362
- * @default false
363
- */
364
- continueOnError?: boolean;
365
- }
366
-
367
- /**
368
- * Stable, machine-readable error codes attached to every error the library
369
- * throws (as `HeicConverterError.code`). Codes are part of the public API:
370
- * they are additive-only and never repurposed, so callers can branch on
371
- * `error.code` instead of matching on message strings.
372
- */
373
- type HeicConverterErrorCode = 'invalid_input' | 'invalid_quality' | 'invalid_resize' | 'invalid_format' | 'invalid_crop' | 'invalid_concurrency' | 'decoder_init_failed' | 'decode_failed' | 'progress_callback_failed' | 'render_encode_failed' | 'unsupported_environment' | 'format_unsupported' | 'aborted' | 'worker_unsupported' | 'worker_load_failed' | 'worker_create_failed' | 'worker_post_failed' | 'worker_failed' | 'worker_timeout' | 'batch_item_failed';
374
- /**
375
- * Error thrown by all first-party code paths. Extends `Error` so existing
376
- * `instanceof Error` / message-based handling keeps working; the `code`
377
- * (and, for batch failures, `itemIndex`/`itemTotal`/`failedCount`) fields
378
- * add a structured discriminator without changing message text.
379
- */
380
- declare class HeicConverterError extends Error {
381
- readonly code: HeicConverterErrorCode;
382
- /** 0-based index of the failing input. Only set on `batch_item_failed` errors. */
383
- readonly itemIndex?: number;
384
- /** Total number of inputs in the batch. Only set on `batch_item_failed` errors. */
385
- readonly itemTotal?: number;
386
- /** How many items failed overall. Only set on `batch_item_failed` errors. */
387
- readonly failedCount?: number;
388
- constructor(code: HeicConverterErrorCode, message: string, options?: {
389
- cause?: unknown;
390
- itemIndex?: number;
391
- itemTotal?: number;
392
- failedCount?: number;
393
- });
394
- }
395
-
396
- /**
397
- * Converts a HEIC image inside a Web Worker so the main thread stays responsive
398
- * during the (potentially slow) WASM decode. This is the public entry point; the
399
- * implementation lives in `src/worker.ts` and is fetched as a lazy chunk on the
400
- * first call, so a deployment missing that chunk rejects with
401
- * `worker_load_failed` (original failure on `cause`) rather than a raw
402
- * module-load error.
403
- *
404
- * The worker script is user-provided and must handle the following message
405
- * protocol (types are exported as {@link WorkerProgressMessage} and
406
- * {@link WorkerResultMessage}):
407
- *
408
- * ```js
409
- * // converter.worker.js — keep in sync with docs/worker.js,
410
- * // test/browser/worker.js, and this JSDoc example.
411
- * import { convertHeic } from '@keeratita/heic-converter';
412
- *
413
- * self.onmessage = async (event) => {
414
- * const { input, options } = event.data;
415
- * try {
416
- * const blob = await convertHeic(input, {
417
- * ...options,
418
- * onProgress: (percent) => self.postMessage({ type: 'progress', percent }),
419
- * });
420
- * self.postMessage({ type: 'result', ok: true, blob });
421
- * } catch (error) {
422
- * self.postMessage({ type: 'result', ok: false, error: error?.stack ?? error?.message ?? String(error) });
423
- * }
424
- * };
425
- * ```
426
- *
427
- * ```ts
428
- * const jpegBlob = await convertHeicInWorker(heicBlob, {
429
- * workerUrl: new URL('./converter.worker.js', import.meta.url),
430
- * workerType: 'module',
431
- * to: 'jpeg',
432
- * });
433
- * ```
434
- *
435
- * Only `progress` and `result` messages are understood; any other message type
436
- * is ignored (the first unknown type is reported in the timeout diagnostic).
437
- * Use `workerType: 'module'` when the script uses ES module imports (as above);
438
- * `'classic'` scripts must be pre-bundled, since static ES imports are not
439
- * supported there.
440
- *
441
- * Notes that are easy to trip over:
442
- * - `decoder` is rejected — class instances cannot cross the worker boundary,
443
- * so the worker creates its own.
444
- * - `timeoutMs` is a per-call deadline that **includes queueing** for a free
445
- * worker slot, not just the conversion itself.
446
- * - An error raised *inside* the worker comes back stringified under
447
- * `worker_failed`: the numeric `code` does not survive the boundary, so match
448
- * on the message. Option validation happens here instead, so an invalid
449
- * option keeps its own code.
450
- * - Workers are pooled per `workerUrl`, so concurrent callers to the same URL
451
- * share one bounded set rather than spawning unbounded workers.
452
- *
453
- * @param input HEIC image as a Blob, File, ArrayBuffer, or Uint8Array.
454
- * @param options Conversion options plus the worker script URL.
455
- * @returns The converted image as a Blob, data URL string, or ArrayBuffer
456
- * depending on `options.output` (default Blob).
457
- */
458
- declare function convertHeicInWorker<S extends OutputShape = 'blob'>(input: HeicInput, options: WorkerConvertOptions & {
459
- output?: S;
460
- }): Promise<ConvertResult<S>>;
461
- /**
462
- * Converts multiple HEIC images inside Web Workers, mirroring {@link convertMany}
463
- * semantics (input order, bounded concurrency, `batch_item_failed` aggregation
464
- * or `continueOnError` per-item results). Concurrency is bounded by
465
- * `maxConcurrentWorkers` (default `navigator.hardwareConcurrency` clamped to
466
- * 1–8): items queue behind the worker semaphore, so a large batch never
467
- * exhausts memory or the browser's worker limit. Each item runs in its own
468
- * worker instance via {@link convertHeicInWorker}, which means `decoder` cannot
469
- * be injected and `workerUrl` is required. See that function for the worker
470
- * script protocol and the caveats about `timeoutMs`, the worker boundary, and
471
- * `worker_load_failed`.
472
- *
473
- * ```ts
474
- * const blobs = await convertManyInWorker(heicFiles, {
475
- * workerUrl: new URL('./converter.worker.js', import.meta.url),
476
- * workerType: 'module',
477
- * to: 'webp',
478
- * continueOnError: true, // get per-item results instead of batch rejection
479
- * });
480
- * ```
481
- *
482
- * Overloads must mirror `convertManyInWorker` in `src/worker.ts`: the deferred
483
- * call below erases the union, so drift here is a public typing bug that `tsc`,
484
- * the unit tests and the bundle guard all fail to catch.
485
- *
486
- * @param inputs HEIC images as Blobs, Files, ArrayBuffers, or Uint8Arrays.
487
- * @param options Batch + worker conversion options (see {@link WorkerBatchOptions}).
488
- * @returns The converted images in input order, or per-item result entries
489
- * when `continueOnError: true`.
490
- */
491
- declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
492
- output?: S;
493
- continueOnError: true;
494
- }): Promise<ConvertItemResult<ConvertResult<S>>[]>;
495
- declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
496
- output?: S;
497
- continueOnError?: false;
498
- }): Promise<ConvertResult<S>[]>;
499
- declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
500
- output?: S;
501
- continueOnError: boolean;
502
- }): Promise<Array<ConvertResult<S> | ConvertItemResult<ConvertResult<S>>>>;
503
-
504
- /**
505
- * Releases any cached decoder resources.
506
- *
507
- * Decoders are now created and released per conversion, so there is no shared
508
- * instance to free. This function is kept for API compatibility.
509
- */
510
- declare function freeSharedDecoder(): void;
511
- /**
512
- * Converts HEIC image data to a standard web format (JPEG, PNG, WebP, AVIF,
513
- * or SVG).
514
- *
515
- * @param input HEIC image as a Blob, File, ArrayBuffer, or Uint8Array.
516
- * @param options Conversion configuration options (see {@link ConvertOptions}).
517
- * @returns The converted image as a Blob, data URL string, or ArrayBuffer
518
- * depending on `options.output` (default Blob).
519
- * @throws HeicConverterError with a machine-readable `code`:
520
- * `invalid_input` (unsupported input type or option value),
521
- * `invalid_quality`, `invalid_resize`, `invalid_crop`,
522
- * `invalid_format` (unknown `to` value), `decoder_init_failed` (WASM
523
- * module could not load), `decode_failed` (invalid/corrupt HEIC),
524
- * `unsupported_environment` (no canvas APIs — e.g. Node.js, where raw RGBA
525
- * decoding via `LibheifDecoder` is the supported path),
526
- * `format_unsupported` (environment cannot encode the format, e.g. AVIF
527
- * in Safari), `aborted` (`options.signal` aborted), or
528
- * `render_encode_failed`.
529
- */
530
- declare function convertHeic<S extends OutputShape = 'blob'>(input: HeicInput, options?: ConvertOptions & {
531
- output?: S;
532
- }): Promise<ConvertResult<S>>;
533
- /**
534
- * Converts multiple HEIC images to a standard web format.
535
- *
536
- * Conversions run with a bounded concurrency (default 4) and results are
537
- * returned in the same order as the inputs. By default, if any conversion
538
- * fails, the returned promise rejects as soon as the failure is known
539
- * (in-flight conversions are allowed to finish in the background) with a
540
- * `batch_item_failed` HeicConverterError carrying `itemIndex`, `itemTotal`,
541
- * and `failedCount` — a batch is all-or-nothing. With
542
- * `options.continueOnError: true` the promise instead fulfills with
543
- * per-item `ConvertItemResult` entries and all items run to completion
544
- * (a mid-batch abort completes not-yet-started items with `aborted`
545
- * entries instead of launching them).
546
- *
547
- * @param inputs HEIC images as Blobs, Files, ArrayBuffers, or Uint8Arrays.
548
- * @param options Batch conversion options (see {@link ConvertManyOptions}).
549
- * @returns The converted images in input order: results array by default,
550
- * or per-item result entries when `continueOnError: true`.
551
- */
552
- declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: ConvertManyOptions & {
553
- output?: S;
554
- continueOnError: true;
555
- }): Promise<ConvertItemResult<ConvertResult<S>>[]>;
556
- declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options?: ConvertManyOptions & {
557
- output?: S;
558
- continueOnError?: false;
559
- }): Promise<ConvertResult<S>[]>;
560
- declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: ConvertManyOptions & {
561
- output?: S;
562
- continueOnError: boolean;
563
- }): Promise<Array<ConvertResult<S> | ConvertItemResult<ConvertResult<S>>>>;
564
-
565
- export { type ConvertItemResult, type ConvertManyOptions, type ConvertOptions, type ConvertResult, type CropOptions, DEFAULT_QUALITY, type DecodedImage, HeicConverterError, type HeicConverterErrorCode, type HeicInput, type IHeicDecoder, type ImageFormat, LibheifDecoder, type LibheifDecoderOptions, type OutputShape, type ResizeOptions, SUPPORTED_FORMATS, type WorkerBatchOptions, type WorkerConvertOptions, type WorkerProgressMessage, type WorkerResultMessage, convertHeic, convertHeicInWorker, convertMany, convertManyInWorker, freeSharedDecoder };
@@ -1 +0,0 @@
1
- import{HeicConverterError as e,validateConvertOptions as r,Messages as t,validateContinueOnError as o,runBoundedBatch as n,clampPercent as s}from"./chunk-PTRQ7ZFB.mjs";var i="Web Worker is not supported in the current environment",a="The decoder option is not supported by convertHeicInWorker: the worker creates its own decoder (functions and class instances cannot cross the worker boundary). Use convertHeic with an injected decoder instead.",u=e=>"Worker failed"+(void 0!==e?` (could not load worker script at ${String(e)}; check the path resolves and the script is served as JavaScript, e.g. Content-Type: text/javascript)`:"");function c(r){if(void 0!==r&&(!Number.isInteger(r)||r<1))throw new e("invalid_concurrency",`maxConcurrentWorkers must be a positive integer, got: ${r}`)}function d(r){if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0))throw new e("invalid_input",`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${r}`)}function l(){const e="undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var p=new Map;function w(e,r,t){let o=p.get(e);o||(o={active:0,waiters:[]},p.set(e,o));const n={granted:!1,released:!1},s=()=>{if(!n.released)if(n.released=!0,n.granted)n.granted=!1,o.active-=1,(()=>{const r=o.waiters.shift();r?r():0===o.active&&0===o.waiters.length&&p.delete(e)})();else{const r=o.waiters.indexOf(i);-1!==r&&o.waiters.splice(r,1),0===o.active&&0===o.waiters.length&&p.delete(e)}},i=()=>{n.released||(n.granted=!0,o.active+=1,t(s))};return o.active<r?i():o.waiters.push(i),s}function m(r){return new e("progress_callback_failed",t.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r})}var g={reserveWorkerSlot:w,workerSlots:p,defaultMaxWorkers:l};function v(o,n){return new Promise((l,p)=>{if("undefined"==typeof Worker)return void p(new e("worker_unsupported",i));if(void 0!==n.decoder)return void p(new e("invalid_input",a));try{r(n),c(n?.maxConcurrentWorkers),d(n?.timeoutMs)}catch(e){return void p(e)}if(n.signal?.aborted)return void p(new e("aborted",t.Aborted));const g={progressMessages:0};let v,k,h,y=!1;const b=()=>{y||(y=!0,void 0!==k&&clearTimeout(k),n.signal?.removeEventListener("abort",W),v&&(v.removeEventListener("message",E),v.removeEventListener("messageerror",x),v.removeEventListener("error",T),v.terminate()),h?.())},W=()=>{b(),p(new e("aborted",t.Aborted))};n.signal?.addEventListener("abort",W,{once:!0});const M=n.timeoutMs??6e4,$=Date.now();let _;M>0&&(k=setTimeout(()=>{b(),p(new e("worker_timeout",((e,r)=>{if(void 0===r.startedAt)return`Web Worker conversion timed out after ${e}ms before a worker slot was granted — the deadline was spent waiting behind other conversions (timeoutMs includes queue wait). Raise maxConcurrentWorkers or timeoutMs, or set timeoutMs to 0 to disable the timeout.`;const t=[`${r.progressMessages} progress message(s) received`];return void 0!==r.queueWaitMs&&r.queueWaitMs>0&&t.unshift(`started after ${r.queueWaitMs}ms queued`),void 0!==r.lastPercent&&t.push(`last percent ${r.lastPercent}`),void 0!==r.unknownType&&t.push(`last unknown message type '${r.unknownType}' (worker may not implement the progress/result protocol)`),void 0!==r.workerUrl&&t.push(`worker ${String(r.workerUrl)}`),`Web Worker conversion timed out after ${e}ms (${t.join("; ")}). Increase timeoutMs for large images, set timeoutMs to 0 to disable the timeout, and verify the worker script implements the { type: "progress" | "result" } protocol.`})(M,{progressMessages:g.progressMessages,lastPercent:g.lastPercent,unknownType:g.unknownType,workerUrl:n.workerUrl,startedAt:_,queueWaitMs:void 0===_?void 0:_-$})))},M));const E=r=>{const t=r.data;if("progress"===t?.type){g.progressMessages+=1;const e=s(t.percent);if(g.lastPercent=e,e>=100)return;try{n.onProgress?.(e)}catch(e){b(),p(m(e))}return}if("result"===t?.type)if(b(),t.ok&&void 0!==t.blob){try{n.onProgress?.(100)}catch(e){return void p(m(e))}l(t.blob)}else p(new e("worker_failed",t.error??"Worker conversion failed"));else"string"==typeof t?.type&&(g.unknownType=t.type)},T=r=>{b();const t=r.filename?` (${r.filename}:${r.lineno})`:"";p(new e("worker_failed",`${r.message||u(n.workerUrl)}${t}`))},x=r=>{b();const t=r.data;p(new e("worker_failed",t instanceof Error?t.message:void 0!==t?String(t):u(n.workerUrl),{cause:t}))},{workerUrl:P,onProgress:C,timeoutMs:S,workerType:L,maxConcurrentWorkers:U,signal:A,...q}=n,I=`${String(P)}|${n.workerType??"classic"}`,O=f(n.maxConcurrentWorkers);h=w(I,O,r=>{if(h=r,!y){_=Date.now();try{v=new Worker(P,"module"===n.workerType?{type:"module"}:void 0)}catch(r){return b(),void p(new e("worker_create_failed",(t=r instanceof Error?r.message:String(r),`Failed to create Web Worker: ${t}`),{cause:r}))}v.addEventListener("message",E),v.addEventListener("messageerror",x),v.addEventListener("error",T);try{v.postMessage({input:o,options:q})}catch(r){b(),p(new e("worker_post_failed",(e=>`Failed to post message to Web Worker: ${e}`)(r instanceof Error?r.message:String(r)),{cause:r}))}}var t})})}function f(e){return"number"==typeof e&&Number.isInteger(e)?Math.max(1,e):l()}async function k(s,u){if(!Array.isArray(s))throw new e("invalid_input",t.InputsMustBeArray);if("undefined"==typeof Worker)throw new e("worker_unsupported",i);if(void 0!==u.decoder)throw new e("invalid_input",a);r(u),o(u?.continueOnError),c(u?.maxConcurrentWorkers),d(u?.timeoutMs);const{onProgress:l,continueOnError:p,...w}=u??{};return n(s,f(u?.maxConcurrentWorkers),(e,r)=>v(e,{...w,...void 0!==l?{onProgress:e=>l(r,e)}:{}}),{continueOnError:!0===u?.continueOnError,signal:u?.signal})}export{g as __semaphoreTestHooks,v as convertHeicInWorker,k as convertManyInWorker};
@@ -1 +0,0 @@
1
- var e=require("./chunk-FKEXCXR4.js"),r="Web Worker is not supported in the current environment",t="The decoder option is not supported by convertHeicInWorker: the worker creates its own decoder (functions and class instances cannot cross the worker boundary). Use convertHeic with an injected decoder instead.",o=e=>"Worker failed"+(void 0!==e?` (could not load worker script at ${String(e)}; check the path resolves and the script is served as JavaScript, e.g. Content-Type: text/javascript)`:"");function n(r){if(void 0!==r&&(!Number.isInteger(r)||r<1))throw new e.HeicConverterError("invalid_concurrency",`maxConcurrentWorkers must be a positive integer, got: ${r}`)}function s(r){if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<0))throw new e.HeicConverterError("invalid_input",`timeoutMs must be a finite number >= 0 (0 disables the timeout), got: ${r}`)}function i(){const e="undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(1,Math.min(e,8))}var a=new Map;function c(e,r,t){let o=a.get(e);o||(o={active:0,waiters:[]},a.set(e,o));const n={granted:!1,released:!1},s=()=>{if(!n.released)if(n.released=!0,n.granted)n.granted=!1,o.active-=1,(()=>{const r=o.waiters.shift();r?r():0===o.active&&0===o.waiters.length&&a.delete(e)})();else{const r=o.waiters.indexOf(i);-1!==r&&o.waiters.splice(r,1),0===o.active&&0===o.waiters.length&&a.delete(e)}},i=()=>{n.released||(n.granted=!0,o.active+=1,t(s))};return o.active<r?i():o.waiters.push(i),s}function u(r){return new e.HeicConverterError("progress_callback_failed",e.Messages.ProgressCallbackThrew(r instanceof Error?r.message:String(r)),{cause:r})}var d={reserveWorkerSlot:c,workerSlots:a,defaultMaxWorkers:i};function v(i,a){return new Promise((d,v)=>{if("undefined"==typeof Worker)return void v(new e.HeicConverterError("worker_unsupported",r));if(void 0!==a.decoder)return void v(new e.HeicConverterError("invalid_input",t));try{e.validateConvertOptions(a),n(a?.maxConcurrentWorkers),s(a?.timeoutMs)}catch(e){return void v(e)}if(a.signal?.aborted)return void v(new e.HeicConverterError("aborted",e.Messages.Aborted));const p={progressMessages:0};let w,g,m,f=!1;const k=()=>{f||(f=!0,void 0!==g&&clearTimeout(g),a.signal?.removeEventListener("abort",h),w&&(w.removeEventListener("message",C),w.removeEventListener("messageerror",W),w.removeEventListener("error",M),w.terminate()),m?.())},h=()=>{k(),v(new e.HeicConverterError("aborted",e.Messages.Aborted))};a.signal?.addEventListener("abort",h,{once:!0});const y=a.timeoutMs??6e4,b=Date.now();let E;y>0&&(g=setTimeout(()=>{k(),v(new e.HeicConverterError("worker_timeout",((e,r)=>{if(void 0===r.startedAt)return`Web Worker conversion timed out after ${e}ms before a worker slot was granted — the deadline was spent waiting behind other conversions (timeoutMs includes queue wait). Raise maxConcurrentWorkers or timeoutMs, or set timeoutMs to 0 to disable the timeout.`;const t=[`${r.progressMessages} progress message(s) received`];return void 0!==r.queueWaitMs&&r.queueWaitMs>0&&t.unshift(`started after ${r.queueWaitMs}ms queued`),void 0!==r.lastPercent&&t.push(`last percent ${r.lastPercent}`),void 0!==r.unknownType&&t.push(`last unknown message type '${r.unknownType}' (worker may not implement the progress/result protocol)`),void 0!==r.workerUrl&&t.push(`worker ${String(r.workerUrl)}`),`Web Worker conversion timed out after ${e}ms (${t.join("; ")}). Increase timeoutMs for large images, set timeoutMs to 0 to disable the timeout, and verify the worker script implements the { type: "progress" | "result" } protocol.`})(y,{progressMessages:p.progressMessages,lastPercent:p.lastPercent,unknownType:p.unknownType,workerUrl:a.workerUrl,startedAt:E,queueWaitMs:void 0===E?void 0:E-b})))},y));const C=r=>{const t=r.data;if("progress"===t?.type){p.progressMessages+=1;const r=e.clampPercent(t.percent);if(p.lastPercent=r,r>=100)return;try{a.onProgress?.(r)}catch(e){k(),v(u(e))}return}if("result"===t?.type)if(k(),t.ok&&void 0!==t.blob){try{a.onProgress?.(100)}catch(e){return void v(u(e))}d(t.blob)}else v(new e.HeicConverterError("worker_failed",t.error??"Worker conversion failed"));else"string"==typeof t?.type&&(p.unknownType=t.type)},M=r=>{k();const t=r.filename?` (${r.filename}:${r.lineno})`:"";v(new e.HeicConverterError("worker_failed",`${r.message||o(a.workerUrl)}${t}`))},W=r=>{k();const t=r.data;v(new e.HeicConverterError("worker_failed",t instanceof Error?t.message:void 0!==t?String(t):o(a.workerUrl),{cause:t}))},{workerUrl:H,onProgress:$,timeoutMs:_,workerType:x,maxConcurrentWorkers:T,signal:P,...S}=a,L=`${String(H)}|${a.workerType??"classic"}`,O=l(a.maxConcurrentWorkers);m=c(L,O,r=>{if(m=r,!f){E=Date.now();try{w=new Worker(H,"module"===a.workerType?{type:"module"}:void 0)}catch(r){return k(),void v(new e.HeicConverterError("worker_create_failed",(t=r instanceof Error?r.message:String(r),`Failed to create Web Worker: ${t}`),{cause:r}))}w.addEventListener("message",C),w.addEventListener("messageerror",W),w.addEventListener("error",M);try{w.postMessage({input:i,options:S})}catch(r){k(),v(new e.HeicConverterError("worker_post_failed",(e=>`Failed to post message to Web Worker: ${e}`)(r instanceof Error?r.message:String(r)),{cause:r}))}}var t})})}function l(e){return"number"==typeof e&&Number.isInteger(e)?Math.max(1,e):i()}exports.__semaphoreTestHooks=d,exports.convertHeicInWorker=v,exports.convertManyInWorker=async function(o,i){if(!Array.isArray(o))throw new e.HeicConverterError("invalid_input",e.Messages.InputsMustBeArray);if("undefined"==typeof Worker)throw new e.HeicConverterError("worker_unsupported",r);if(void 0!==i.decoder)throw new e.HeicConverterError("invalid_input",t);e.validateConvertOptions(i),e.validateContinueOnError(i?.continueOnError),n(i?.maxConcurrentWorkers),s(i?.timeoutMs);const{onProgress:a,continueOnError:c,...u}=i??{};return e.runBoundedBatch(o,l(i?.maxConcurrentWorkers),(e,r)=>v(e,{...u,...void 0!==a?{onProgress:e=>a(r,e)}:{}}),{continueOnError:!0===i?.continueOnError,signal:i?.signal})};