@keeratita/heic-converter 0.5.1 โ 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -20
- package/dist/batch.d.ts +27 -0
- package/dist/chunk-AROQBV5T.mjs +1 -0
- package/dist/chunk-BTAX2PFV.mjs +1 -0
- package/dist/chunk-N2LCVW2Q.js +1 -0
- package/dist/chunk-TND3VERK.js +1 -0
- package/dist/errors.d.ts +28 -0
- package/dist/heic-decoder.wasm +0 -0
- package/dist/heic-decoder.wasm.br +0 -0
- package/dist/heic-decoder.wasm.gz +0 -0
- package/dist/index.d.ts +42 -423
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/messages/core.d.ts +60 -0
- package/dist/messages/worker.d.ts +33 -0
- package/dist/native-IGARV2W7.mjs +1 -0
- package/dist/native-JFFONPCS.js +1 -0
- package/dist/progress.d.ts +39 -0
- package/dist/render/canvas.d.ts +71 -0
- package/dist/render/exif.d.ts +37 -0
- package/dist/types.d.ts +257 -0
- package/dist/validate.d.ts +59 -0
- package/dist/wasm/fault.d.ts +3 -0
- package/dist/wasm/index.d.ts +1 -0
- package/dist/wasm/native.d.ts +46 -0
- package/dist/wasm/wrapper.d.ts +62 -0
- package/dist/worker-DISSAV3W.js +1 -0
- package/dist/worker-VA6WQF25.mjs +1 -0
- package/dist/worker.d.ts +128 -0
- package/package.json +7 -6
- package/dist/chunk-FKEXCXR4.js +0 -1
- package/dist/chunk-PTRQ7ZFB.mjs +0 -1
- package/dist/index.d.mts +0 -565
- package/dist/worker-FNMN2SJV.mjs +0 -1
- package/dist/worker-Z3UQ6WL7.js +0 -1
package/README.md
CHANGED
|
@@ -18,7 +18,8 @@ Designed specifically for environments with strict **Content Security Policy (CS
|
|
|
18
18
|
- ๐งญ **EXIF-Orientation Aware**: Images stored rotated with an EXIF orientation flag come out upright, matching what viewers display. Opt out with `applyOrientation: false`.
|
|
19
19
|
- ๐ **Metadata Preservation**: `preserveExif: true` keeps the source EXIF block in JPEG (APP1) and PNG (`eXIf`) output; raw-decode consumers get the block via `DecodedImage.exif`.
|
|
20
20
|
- ๐ **Batch Conversion**: Convert many images at once with bounded concurrency via `convertMany` โ with per-item results (`continueOnError`) and pooled decoders (`reuseDecoders`) for large batches.
|
|
21
|
-
- ๐งต **Web Worker Helpers**: Offload single conversions (`convertHeicInWorker`) or whole batches (`convertManyInWorker`) to Web Workers to keep the UI thread responsive.
|
|
21
|
+
- ๐งต **Web Worker Helpers**: Offload single conversions (`convertHeicInWorker`) or whole batches (`convertManyInWorker`) to Web Workers to keep the UI thread responsive โ live workers are reused across batch items, not booted per file.
|
|
22
|
+
- ๐ **Native Decode Opt-in**: `nativeDecode: true` decodes with the platform's HEIC stack (`createImageBitmap` on Safari/iOS, Edge, Windows) instead of the bundled WASM decoder, skipping its ~300 KB payload; hosts without native HEIC support fall back to libheif automatically.
|
|
22
23
|
- ๐ **Output Shapes & Cancellation**: Return Blobs, base64 data URLs, or ArrayBuffers (`output`), and cancel in-flight work with an `AbortSignal` (`signal`) โ worker conversions terminate immediately.
|
|
23
24
|
|
|
24
25
|
---
|
|
@@ -146,6 +147,7 @@ const jpegBlob = await convertHeic(heicBlob, {
|
|
|
146
147
|
| `heic-decoder.wasm` (+ `.gz` / `.br`) | the decoder binary |
|
|
147
148
|
| `worker-*.mjs` / `worker-*.js` | `convertHeicInWorker` / `convertManyInWorker` |
|
|
148
149
|
| `exif-*.mjs` / `exif-*.js` | `preserveExif: true` |
|
|
150
|
+
| `native-*.mjs` / `native-*.js` | `nativeDecode: true` |
|
|
149
151
|
|
|
150
152
|
- Chunk names are **content-hashed and hard-referenced by the entry**, so a partial upload โ or a `dist/` mixed across releases โ 404s instead of degrading quietly. Deploy the whole directory per release.
|
|
151
153
|
- Serve chunks as `text/javascript`. A wrong MIME type surfaces as `worker_load_failed` from the worker APIs, and as `preserveExif` silently dropping metadata (it warns once).
|
|
@@ -172,9 +174,11 @@ Fetching a `.gz`/`.br` variant URL directly will not work โ see the compressio
|
|
|
172
174
|
|
|
173
175
|
#### Reducing the download size
|
|
174
176
|
|
|
175
|
-
The WASM binary (~
|
|
177
|
+
The WASM binary (~795 KB, ~290 KB gzipped) dominates the payload; everything else is small and lazy. The Emscripten glue is a separate chunk fetched only on the first decode, and the Web Worker implementation, the opt-in EXIF injectors, and the opt-in native-decode strategy are separate chunks fetched only when you first call `convertHeicInWorker`/`convertManyInWorker` or pass `preserveExif: true` / `nativeDecode: true`. What every consumer pays for up front is a few kilobytes of gzipped JavaScript โ `test/unit/bundle.test.ts` fails the build if one of those boundaries moves or the eager budget grows, so the numbers live in the tests rather than here.
|
|
176
178
|
|
|
177
|
-
|
|
179
|
+
On HEIC-capable hosts (Safari/iOS, Edge, Windows) `nativeDecode: true` skips the WASM binary entirely โ the platform decodes. Pages that instantiate decoders repeatedly (or re-instantiate after `free()`) can instead compile the WASM once and share it via `moduleOverrides.instantiateWasm` โ see the recipe in [API.md](API.md#libheifdecoderoptions).
|
|
180
|
+
|
|
181
|
+
`npm run build` also emits pre-compressed copies โ `dist/heic-decoder.wasm.gz` (~290 KB) and `dist/heic-decoder.wasm.br` (~232 KB) โ and verifies each one decompresses back to the binary, so a corrupt sidecar cannot reach a CDN. Most static hosts and CDNs (GitHub Pages, Netlify, Vercel, Cloudflare) already compress `application/wasm` automatically when the browser sends `Accept-Encoding`; verify with:
|
|
178
182
|
|
|
179
183
|
```bash
|
|
180
184
|
curl -sI -H 'Accept-Encoding: br' https://your-site/heic-decoder.wasm | grep -i content-encoding
|
|
@@ -385,8 +389,8 @@ Batch semantics worth knowing:
|
|
|
385
389
|
|
|
386
390
|
- The promise rejects with the **first failure in time** (not the lowest index). All items are still allowed to finish; decoders of in-flight items are released when they settle.
|
|
387
391
|
- The rejection is a `batch_item_failed` error carrying structured fields: `itemIndex` (0-based index of the first failing item), `itemTotal`, `failedCount` (total items that failed), and `cause` (the underlying error). The message names the failing item and, when several items failed, summarizes the count and the other errors.
|
|
388
|
-
- `onProgress`
|
|
389
|
-
- `concurrency` must be a
|
|
392
|
+
- `onProgress` fires `(index, percent)` as items run. Sub-100 percentages are live and may also arrive for items that ultimately fail; the `100` event fires only for items that succeed.
|
|
393
|
+
- `concurrency` must be an integer between 1 and 64 (each runner boots a full WASM decoder, so runaway values are rejected, not clamped); the default is `4`.
|
|
390
394
|
|
|
391
395
|
**Keeping going after failures** โ with `continueOnError: true` the batch never rejects for item failures. Every item runs, and you get a result entry per item in input order:
|
|
392
396
|
|
|
@@ -423,23 +427,27 @@ Run the conversion inside a Web Worker so the main thread stays responsive. Crea
|
|
|
423
427
|
import { convertHeic } from '@keeratita/heic-converter';
|
|
424
428
|
|
|
425
429
|
self.onmessage = async (event) => {
|
|
426
|
-
const { input, options } = event.data;
|
|
430
|
+
const { id, input, options } = event.data;
|
|
427
431
|
try {
|
|
428
432
|
const blob = await convertHeic(input, {
|
|
429
433
|
...options,
|
|
430
|
-
onProgress: (percent) => self.postMessage({ type: 'progress', percent }),
|
|
434
|
+
onProgress: (percent) => self.postMessage({ id, type: 'progress', percent }),
|
|
431
435
|
});
|
|
432
436
|
// With output: 'arrayBuffer' the payload is zero-copy via a transfer list.
|
|
433
437
|
self.postMessage(
|
|
434
|
-
{ type: 'result', ok: true, blob },
|
|
438
|
+
{ id, type: 'result', ok: true, blob },
|
|
435
439
|
blob instanceof ArrayBuffer ? [blob] : []
|
|
436
440
|
);
|
|
437
441
|
} catch (error) {
|
|
438
|
-
self.postMessage({ type: 'result', ok: false, error: error?.stack ?? error?.message ?? String(error) });
|
|
442
|
+
self.postMessage({ id, type: 'result', ok: false, error: error?.stack ?? error?.message ?? String(error) });
|
|
439
443
|
}
|
|
440
444
|
};
|
|
441
445
|
```
|
|
442
446
|
|
|
447
|
+
**Protocol:** every request carries an `id` and every reply must echo it โ workers are pooled, so a reply that does not match the current request is ignored and cannot settle the wrong item. Full protocol in [API.md](API.md#web-worker-protocol).
|
|
448
|
+
|
|
449
|
+
**Worker reuse:** the transport keeps live workers across batch items โ one that answered a clean `ok: true` is parked and adopted by the next request instead of being booted again (workers that timed out, aborted, or errored are terminated). Your script must therefore stay request-oriented: keep `onmessage` installed and do **not** call `self.close()` after posting a result, or the next queued conversion waits out its `timeoutMs`. The script above already complies.
|
|
450
|
+
|
|
443
451
|
Then convert from the main thread:
|
|
444
452
|
|
|
445
453
|
```typescript
|
|
@@ -461,7 +469,7 @@ const jpegBlob = await convertHeicInWorker(heicBlob, {
|
|
|
461
469
|
> - `workerUrl` should be a compile-time constant; the script runs with the page's privileges.
|
|
462
470
|
> - Only `progress` and `result` messages are understood; any other message type is ignored โ but ignored messages are counted and surfaced in timeout diagnostics (see below).
|
|
463
471
|
> - `decoder` cannot cross the worker boundary: passing it rejects immediately with an `invalid_input` error (it is also absent from `WorkerConvertOptions` at compile time). `onProgress` and `workerUrl` are stripped from the posted message; progress is forwarded through `{ type: 'progress', percent }` messages instead.
|
|
464
|
-
> - Concurrent calls are bounded per worker script: calls beyond `maxConcurrentWorkers` queue and start as slots free. Must be
|
|
472
|
+
> - Concurrent calls are bounded per worker script: calls beyond `maxConcurrentWorkers` queue and start as slots free. Must be an integer between 1 and 64 (`invalid_concurrency` otherwise). Default: `navigator.hardwareConcurrency` clamped to 1โ8 (4 when unavailable).
|
|
465
473
|
> - `timeoutMs` (default `60000`) bounds how long the promise waits for a result; must be a finite number โฅ 0, `0` disables. The deadline starts when the call is made, so time spent queued behind `maxConcurrentWorkers` counts toward it โ raise `timeoutMs` or `maxConcurrentWorkers` for very large batches. A timeout rejects with a `worker_timeout` error whose message includes diagnostics โ how many progress messages arrived, the last percent, and any unrecognized message type (the usual sign the worker script doesn't implement the protocol).
|
|
466
474
|
> - This helper is **browser-only**: it rejects in Node.js, where there is no global `Worker`.
|
|
467
475
|
|
|
@@ -506,11 +514,13 @@ Two additions to that header are easy to miss:
|
|
|
506
514
|
|
|
507
515
|
## ๐ API Reference
|
|
508
516
|
|
|
517
|
+
The sections below are the working reference. The exhaustive version โ full signatures, per-API guarantees, the worker message protocol, and the complete error catalogue โ lives in **[API.md](API.md)**.
|
|
518
|
+
|
|
509
519
|
### `convertHeic(input, options?)`
|
|
510
520
|
|
|
511
521
|
Converts a HEIC image file to a standard web format.
|
|
512
522
|
|
|
513
|
-
- **`input`**: `Blob
|
|
523
|
+
- **`input`**: `Blob` (including `File`), `ArrayBuffer`, or any `ArrayBufferView` (`Uint8Array`, `DataView`, โฆ)
|
|
514
524
|
- **`options`**: (optional) `ConvertOptions`
|
|
515
525
|
- `to`: `'jpeg' | 'jpg' | 'png' | 'webp' | 'avif' | 'svg'` (Default: `'jpeg'`; `avif` rejects with `format_unsupported` where the canvas cannot encode it)
|
|
516
526
|
- `quality`: `number` (0.0 to 1.0, applicable to JPEG, WebP, and AVIF. Default: `0.92`)
|
|
@@ -524,41 +534,42 @@ Converts a HEIC image file to a standard web format.
|
|
|
524
534
|
- `preserveExif`: `boolean` (Re-inject the source EXIF block into JPEG (APP1) / PNG (`eXIf`) output. Metadata may contain GPS โ opt-in. Default: `false`. Fail-safe: unparsable encoder output, a malformed block, or an oversized payload returns the image without metadata rather than failing โ as does a missing `dist/exif-*.mjs` chunk, which logs a one-time warning so a deployment problem is distinguishable from a file that simply had no Exif item)
|
|
525
535
|
- `output`: `'blob' | 'dataUrl' | 'arrayBuffer'` (Result representation. Default: `'blob'`; see [Usage section 10](#10-output-shapes-blob-data-url-arraybuffer))
|
|
526
536
|
- `signal`: `AbortSignal` (Cancel pending work; rejects with `aborted`. Default: none)
|
|
537
|
+
- `nativeDecode`: `boolean` (Decode via the platform's native HEIC stack โ `createImageBitmap` on Safari/iOS, Edge, Windows โ skipping the WASM payload; falls back to libheif transparently where unavailable. Ignored with an injected `decoder`, `preserveExif: true`, or `applyOrientation: false`. Default: `false`)
|
|
527
538
|
- **Returns**: `Promise<Blob>` โ or `Promise<string>` / `Promise<ArrayBuffer>` with the typed `output` overloads
|
|
528
539
|
|
|
529
540
|
### `convertMany(inputs, options?)`
|
|
530
541
|
|
|
531
542
|
Converts multiple HEIC images with bounded concurrency. Results are returned in input order; rejects with the first failure in time โ a `batch_item_failed` error whose `message` names the failing item and whose fields describe the batch (`itemIndex` 0-based, `itemTotal`, `failedCount`, `cause`). With `continueOnError` the promise fulfills with per-item results instead.
|
|
532
543
|
|
|
533
|
-
- **`inputs`**: `Array<Blob
|
|
544
|
+
- **`inputs`**: `Array<Blob (incl. File) | ArrayBuffer | ArrayBufferView>`
|
|
534
545
|
- **`options`**: (optional) `ConvertManyOptions` โ same as `ConvertOptions`, except `onProgress` uses the batch signature below; plus:
|
|
535
|
-
- `concurrency`: `number` (Maximum concurrent conversions. Default: `4`)
|
|
536
|
-
- `onProgress`: `(index: number, percent: number) => void` (Per-item progress callback;
|
|
546
|
+
- `concurrency`: `number` (Maximum concurrent conversions; integer 1โ64. Default: `4`)
|
|
547
|
+
- `onProgress`: `(index: number, percent: number) => void` (Per-item progress callback; sub-100 may fire for failing items, `100` only on success)
|
|
537
548
|
- `decoder`: `IHeicDecoder` (Optional. When provided, the same instance is shared by all concurrent conversions and must be safe for concurrent `decode()` calls; the library never frees an injected decoder; `reuseDecoders` is ignored)
|
|
538
549
|
- `continueOnError`: `boolean` (Return per-item `{ index, ok, result | error }` entries instead of rejecting on the first failure. Default: `false`)
|
|
539
|
-
- `reuseDecoders`: `boolean` (Hand each batch runner one pooled `LibheifDecoder` reused across items โ amortizes WASM init for large batches while keeping exclusive use. Default: `false`)
|
|
550
|
+
- `reuseDecoders`: `boolean` (Hand each batch runner one pooled `LibheifDecoder` reused across items โ amortizes WASM init for large batches while keeping exclusive use. Ignored when `decoder` is set or `nativeDecode: true`. Default: `false`)
|
|
540
551
|
- **Returns**: `Promise<Blob[]>` โ or `Promise<string[]>` / `Promise<ArrayBuffer[]>` with the typed `output` overloads; `Promise<ConvertItemResult[]>` with `continueOnError` (also typed by `output`)
|
|
541
552
|
|
|
542
553
|
### `convertHeicInWorker(input, options)`
|
|
543
554
|
|
|
544
555
|
Converts a HEIC image inside a Web Worker. The worker script must implement the message protocol shown in [Usage section 13](#13-web-worker-conversion). Browser-only; rejects in Node.js.
|
|
545
556
|
|
|
546
|
-
- **`input`**: `Blob
|
|
557
|
+
- **`input`**: `Blob` (including `File`), `ArrayBuffer`, or any `ArrayBufferView` (`Uint8Array`, `DataView`, โฆ)
|
|
547
558
|
- **`options`**: `WorkerConvertOptions` โ same as `ConvertOptions` but without `decoder` (cannot be structured-cloned; passing one rejects with `invalid_input`), plus:
|
|
548
559
|
- `workerUrl`: `string | URL` (URL of the worker script; should be a compile-time constant)
|
|
549
560
|
- `workerType`: `'classic' | 'module'` (Worker script type. Default: `'classic'`; use `'module'` for scripts with ES imports)
|
|
550
561
|
- `timeoutMs`: `number` (Maximum wait for the result in milliseconds, including time spent queued. Finite, โฅ 0; `0` disables. Default: `60000`)
|
|
551
|
-
- `maxConcurrentWorkers`: `number` (
|
|
562
|
+
- `maxConcurrentWorkers`: `number` (Integer 1โ64. Concurrent workers per `workerUrl` + type; extra calls queue. Default: `navigator.hardwareConcurrency` clamped to 1โ8)
|
|
552
563
|
- **Returns**: `Promise<Blob>` โ or `Promise<string>` / `Promise<ArrayBuffer>` with the typed `output` overloads. Aborting via `signal` terminates the worker immediately.
|
|
553
564
|
|
|
554
565
|
### `convertManyInWorker(inputs, options)`
|
|
555
566
|
|
|
556
567
|
Converts multiple HEIC images, each inside a Web Worker, with `convertMany` semantics (input order, `batch_item_failed` aggregation, `continueOnError` per-item results). Browser-only; rejects in Node.js.
|
|
557
568
|
|
|
558
|
-
- **`inputs`**: `Array<Blob
|
|
569
|
+
- **`inputs`**: `Array<Blob (incl. File) | ArrayBuffer | ArrayBufferView>`
|
|
559
570
|
- **`options`**: `WorkerBatchOptions` โ same as `convertHeicInWorker`'s `WorkerConvertOptions` (including `output`, `crop`, `preserveExif`, `signal`), except `onProgress` uses the batch signature below; plus:
|
|
560
571
|
- `onProgress`: `(index: number, percent: number) => void` (Per-item progress callback)
|
|
561
|
-
- `maxConcurrentWorkers`: `number` (
|
|
572
|
+
- `maxConcurrentWorkers`: `number` (Integer 1โ64. Real concurrency โ each in-flight item occupies one semaphore slot. Default: `navigator.hardwareConcurrency` clamped to 1โ8)
|
|
562
573
|
- `continueOnError`: `boolean` (Per-item `{ index, ok, result | error }` entries instead of rejecting on the first failure. Default: `false`)
|
|
563
574
|
- **Returns**: `Promise<Blob[]>` โ typed overloads mirror `convertMany` (`output` / `continueOnError` combinations)
|
|
564
575
|
|
|
@@ -586,7 +597,7 @@ All errors thrown by this library are `HeicConverterError` instances (`extends E
|
|
|
586
597
|
| `invalid_resize` | all conversion APIs | `scale`/`maxWidth`/`maxHeight` not positive finite numbers, or target size exceeds 16384 px |
|
|
587
598
|
| `invalid_format` | all conversion APIs | Unknown `to` value |
|
|
588
599
|
| `invalid_crop` | all conversion APIs | `crop` with non-integer/non-positive dimensions, negative offsets, or a rectangle beyond the image's display size |
|
|
589
|
-
| `invalid_concurrency` | all conversion APIs | `concurrency` (batch) or `maxConcurrentWorkers` (worker APIs) not
|
|
600
|
+
| `invalid_concurrency` | all conversion APIs | `concurrency` (batch) or `maxConcurrentWorkers` (worker APIs) is not an integer between 1 and 64 |
|
|
590
601
|
| `decoder_init_failed` | `convertHeic`, `convertMany` | WASM module could not be loaded (missing asset, CSP block) |
|
|
591
602
|
| `decode_failed` | `convertHeic`, `convertMany` | Invalid/corrupt HEIC bytes |
|
|
592
603
|
| `unsupported_environment` | `convertHeic`, `convertMany` | No canvas APIs (e.g. Node.js); the worker APIs reject with `worker_unsupported` there instead. Decode raw RGBA via `LibheifDecoder` |
|
package/dist/batch.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ConvertItemResult } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Shared bounded-concurrency batch runner backing both `convertMany` and
|
|
4
|
+
* `convertManyInWorker`. Semantics (documented on the public APIs):
|
|
5
|
+
*
|
|
6
|
+
* - Items are processed in input order by at most `concurrency` runners.
|
|
7
|
+
* - Default mode rejects with `batch_item_failed` as soon as the first
|
|
8
|
+
* failure is known; in-flight items settle in the background. The error
|
|
9
|
+
* names the first failing item and carries `itemIndex`/`itemTotal`/
|
|
10
|
+
* `failedCount`, plus up to two extra distinct failure messages.
|
|
11
|
+
* - `continueOnError` mode never rejects for item failures and never stops
|
|
12
|
+
* launching items: it fulfills with per-item results in input order.
|
|
13
|
+
* - Up-front failures thrown by `convertItem` synchronously (none today)
|
|
14
|
+
* propagate untouched.
|
|
15
|
+
*/
|
|
16
|
+
export declare function runBoundedBatch<T>(inputs: readonly unknown[], concurrency: number, convertItem: (input: unknown, index: number) => Promise<T>, options: {
|
|
17
|
+
continueOnError: true;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}): Promise<ConvertItemResult<T>[]>;
|
|
20
|
+
export declare function runBoundedBatch<T>(inputs: readonly unknown[], concurrency: number, convertItem: (input: unknown, index: number) => Promise<T>, options?: {
|
|
21
|
+
continueOnError?: false;
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}): Promise<T[]>;
|
|
24
|
+
export declare function runBoundedBatch<T>(inputs: readonly unknown[], concurrency: number, convertItem: (input: unknown, index: number) => Promise<T>, options: {
|
|
25
|
+
continueOnError: boolean;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
}): Promise<Array<T | ConvertItemResult<T>>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{code;itemIndex;itemTotal;failedCount;constructor(e,t,i){super(t,{cause:i?.cause}),this.name="HeicConverterError",this.code=e,void 0!==i?.itemIndex&&(this.itemIndex=i.itemIndex),void 0!==i?.itemTotal&&(this.itemTotal=i.itemTotal),void 0!==i?.failedCount&&(this.failedCount=i.failedCount)}};export{e as HeicConverterError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{HeicConverterError as e}from"./chunk-AROQBV5T.mjs";var t={QualityInvalid:e=>`Quality must be a number between 0.0 and 1.0, got: ${e}`,BooleanOptionInvalid:(e,t)=>`${e} must be a boolean, got: ${t}`,UnsupportedInputType:e=>`Unsupported input type. Expected Blob (incl. File), ArrayBuffer, or ArrayBufferView. Got: ${e}`,DecoderInitFailed:e=>`Failed to initialize HEIC decoder: ${e} โ verify heic-decoder.wasm is served (dist/heic-decoder.wasm; see the README "Serving and Locating WASM" section / locateFile option) and that your CSP allows 'wasm-unsafe-eval'`,WorkerChunkLoadFailed:e=>`Failed to load the Web Worker implementation chunk (dist/worker-*.mjs): ${e} โ deploy every file in dist/ together, or use convertHeic to convert in the current thread`,NativeChunkLoadWarning:e=>`@keeratita/heic-converter: the native-decode chunk could not be loaded (${e}) โ converting with the bundled decoder; serve every file in dist/ together, with dist/native-*.mjs as JavaScript`,RenderEncodeFailed:(e,t)=>`Failed to render and encode image as ${e}: ${t}`,ConcurrencyInvalid:(e,t)=>`Concurrency must be an integer between 1 and ${t}, got: ${e}`,InputsMustBeArray:"Inputs must be an array of HEIC images",OutputShapeInvalid:e=>`output must be one of 'blob', 'dataUrl', 'arrayBuffer', got: ${e}`,SignalInvalid:e=>`signal must be an AbortSignal, got: ${e}`,Aborted:"Conversion aborted (AbortSignal was aborted)",ConvertManyItemFailed:(e,t,n)=>`Conversion of item ${e} of ${t} failed: ${n}`,BatchItemProducedNoResult:(e,t)=>`Conversion of item ${e} of ${t} failed: item produced no result`,BatchEndedWithoutSettling:e=>`Batch ended without settling any of its ${e} items`,ConvertManyExtraFailures:(e,t)=>` (${e} of ${t} items failed in total)`,ConvertManyOtherErrors:e=>`; other errors: ${e.join(" | ")}`,ExifChunkLoadWarning:"@keeratita/heic-converter: the EXIF injector chunk could not be loaded โ converted without metadata; serve every file in dist/ together, with dist/exif-*.mjs as JavaScript.",ScaleInvalid:e=>`Scale must be a positive finite number, got: ${e}`,MaxWidthInvalid:e=>`maxWidth must be a positive finite number, got: ${e}`,MaxHeightInvalid:e=>`maxHeight must be a positive finite number, got: ${e}`,TargetSizeTooLarge:(e,t,n)=>`Target image size ${e}x${t} exceeds the maximum supported dimension of ${n}px`,BlobToBase64FailedWithCause:e=>`Failed to convert Blob to base64 string: ${e}`,CanvasToBlobFailed:e=>`Failed to convert canvas to blob (type: ${e})`,CanvasUnsupported:"Canvas is not supported in the current environment. In a browser this requires OffscreenCanvas or HTMLCanvasElement. In Node.js there is no canvas: decode raw RGBA with LibheifDecoder and encode externally (see the Node.js section of the README).",InvalidDimensions:(e,t)=>`Invalid image dimensions: ${e}x${t}. Width and height must be positive integers.`,DataLengthMismatch:(e,t,n,i)=>`Image data length mismatch. Expected ${e} bytes for ${t}x${n}, got ${i}`,ContextUnavailable:"Failed to acquire 2D rendering context from canvas",UnsupportedFormat:e=>`Unsupported output format: ${e}`,FormatUnsupported:e=>`The current environment cannot encode '${e}' โ canvas encoding produced no '${e}' image (e.g. AVIF encoding is not supported in this browser). Try 'jpeg', 'png', or 'webp' instead.`,CropInvalid:(e,t)=>`crop.${e} must be ${"width"===e||"height"===e?"a positive integer":"a non-negative integer"}, got: ${t}`,CropOutOfBounds:(e,t,n,i,o,r)=>`crop ${n}x${i} at (${e}, ${t}) exceeds the ${o}x${r} image (crop coordinates are in post-orientation display pixels)`,GlueApiMissing:e=>`The bundled decoder glue is missing required APIs (${e}) โ deploy every file in dist/ from the same release; heic-decoder.wasm and its glue chunk must come from one build.`,DecoderFreedDuringDecode:"Decoder was freed before decoding completed; call initialize() again.",DecodeInputAllocFailed:e=>`Failed to allocate ${e} bytes in the WASM heap for decode input`,DecodeFailed:e=>`HEIC decoding failed (no result returned; input: ${e} bytes โ is the file truncated or empty?)`,DecodeFailedWithDetail:(e,t)=>`HEIC decoding failed: ${e} (input: ${t} bytes)`,DecodeFaulted:e=>`Decoder faulted on a ${e}-byte image (out of memory, or a corrupted WebAssembly instance); retry โ a faulted pooled decoder is discarded, not reused`,ProgressCallbackThrew:e=>`onProgress callback threw during decode: ${e}`};function n(e){const t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function i(n){return new e("progress_callback_failed",t.ProgressCallbackThrew(n instanceof Error?n.message:String(n)),{cause:n})}function o(e){return"function"==typeof e?e:void 0}function r(e){const t=o(e);return t?function(e){let t,o=!1;return{report:i=>{if(o)return;const r=n(i);if(!(r>=100))try{e(r)}catch(e){t=t??e}},complete:()=>{if(!o){if(o=!0,void 0!==t)throw i(t);try{e(100)}catch(e){throw i(e)}}},pendingError:()=>void 0===t?void 0:i(t)}}(t):void 0}var a=["jpeg","jpg","png","svg","webp","avif"],d=.92,s=64;function l(n){m(n?.to??"jpeg"),void 0!==n?.quality&&function(n){if("number"!=typeof n||!Number.isFinite(n)||n<0||n>1)throw new e("invalid_quality",t.QualityInvalid(n))}(n.quality),h("applyOrientation",n?.applyOrientation),function(n){if(void 0!==n&&"blob"!==n&&"dataUrl"!==n&&"arrayBuffer"!==n)throw new e("invalid_input",t.OutputShapeInvalid(n))}(n?.output),function(n){if(void 0!==n&&("object"!=typeof n||null===n||"function"!=typeof n.addEventListener))throw new e("invalid_input",t.SignalInvalid(n))}(n?.signal),v(n?.crop),h("preserveExif",n?.preserveExif),h("nativeDecode",n?.nativeDecode),p(n)}function c(e){h("continueOnError",e?.continueOnError),h("reuseDecoders",e?.reuseDecoders)}function u(n){if(!Number.isInteger(n)||n<1||n>64)throw new e("invalid_concurrency",t.ConcurrencyInvalid(n,64))}function h(n,i){if(void 0!==i&&"boolean"!=typeof i)throw new e("invalid_input",t.BooleanOptionInvalid(n,i))}function f(n){if(n?.aborted)throw new e("aborted",t.Aborted)}function m(n){const i=String(n).toLowerCase();if(!a.includes(i))throw new e("invalid_format",t.UnsupportedFormat(String(n)))}function p(n){if(!n)return;const{maxWidth:i,maxHeight:o,scale:r}=n;if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)||r<=0))throw new e("invalid_resize",t.ScaleInvalid(r));if(void 0!==i&&("number"!=typeof i||!Number.isFinite(i)||i<=0))throw new e("invalid_resize",t.MaxWidthInvalid(i));if(void 0!==o&&("number"!=typeof o||!Number.isFinite(o)||o<=0))throw new e("invalid_resize",t.MaxHeightInvalid(o))}function v(n){if(!n)return;const{x:i=0,y:o=0,width:r,height:a}=n;if(!Number.isInteger(r)||r<=0)throw new e("invalid_crop",t.CropInvalid("width",r));if(!Number.isInteger(a)||a<=0)throw new e("invalid_crop",t.CropInvalid("height",a));if(!Number.isInteger(i)||i<0)throw new e("invalid_crop",t.CropInvalid("x",i));if(!Number.isInteger(o)||o<0)throw new e("invalid_crop",t.CropInvalid("y",o))}async function g(n,i,o,r){const a=!0===r?.continueOnError,d=r?.signal,s=new Array(n.length);let l=0,c=!1,u=0,h=null,f=-1,m=0;const p=[];let v;const g=new Promise(e=>{v=e}),b=()=>v?.();d&&!a&&d.addEventListener("abort",b,{once:!0});const w=function(e,t){return Math.min(e,t)}(i,n.length),y=Array.from({length:w},()=>(async()=>{for(;!c&&!d?.aborted||a;){const i=l;if(l+=1,i>=n.length)return;if(a&&d?.aborted){const o=new e("aborted",t.Aborted);for(let e=i;e<n.length;e++)s[e]={index:e,ok:!1,error:o};return void(l=n.length)}try{const e=await o(n[i],i);s[i]={index:i,ok:!0,result:e},u+=1}catch(e){if(m+=1,a){s[i]={index:i,ok:!1,error:e instanceof Error?e:new Error(String(e))};continue}c?p.length<2&&p.push(e instanceof Error?e.message:String(e)):(c=!0,h=e,f=i,v?.())}}})());try{if(a)return await Promise.all(y),s;if(await Promise.race([Promise.all(y),g]),u===n.length)return s.map(i=>{if(!i||!i.ok)throw new e("batch_item_failed",t.BatchItemProducedNoResult((i?.index??0)+1,n.length));return i.result});if(d?.aborted)throw new e("aborted",t.Aborted);if(c){const i=h instanceof Error?h.message:String(h);let o=t.ConvertManyItemFailed(f+1,n.length,i);throw m>1&&(o+=t.ConvertManyExtraFailures(m,n.length),p.length>0&&(o+=t.ConvertManyOtherErrors(p))),new e("batch_item_failed",o,{cause:h,itemIndex:f,itemTotal:n.length,failedCount:m})}throw new e("batch_item_failed",t.BatchEndedWithoutSettling(n.length))}finally{d?.removeEventListener("abort",b)}}export{d as DEFAULT_QUALITY,s as MAX_BATCH_CONCURRENCY,t as Messages,a as SUPPORTED_FORMATS,n as clampPercent,i as progressCallbackError,o as progressCallbackFor,r as progressGateFor,g as runBoundedBatch,f as throwIfAborted,c as validateBatchOptions,u as validateConcurrency,l as validateConvertOptions,v as validateCrop,m as validateFormat,p as validateResize};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{code;itemIndex;itemTotal;failedCount;constructor(e,t,i){super(t,{cause:i?.cause}),this.name="HeicConverterError",this.code=e,void 0!==i?.itemIndex&&(this.itemIndex=i.itemIndex),void 0!==i?.itemTotal&&(this.itemTotal=i.itemTotal),void 0!==i?.failedCount&&(this.failedCount=i.failedCount)}};exports.HeicConverterError=e;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=require("./chunk-N2LCVW2Q.js"),r={QualityInvalid:e=>`Quality must be a number between 0.0 and 1.0, got: ${e}`,BooleanOptionInvalid:(e,r)=>`${e} must be a boolean, got: ${r}`,UnsupportedInputType:e=>`Unsupported input type. Expected Blob (incl. File), ArrayBuffer, or ArrayBufferView. Got: ${e}`,DecoderInitFailed:e=>`Failed to initialize HEIC decoder: ${e} โ verify heic-decoder.wasm is served (dist/heic-decoder.wasm; see the README "Serving and Locating WASM" section / locateFile option) and that your CSP allows 'wasm-unsafe-eval'`,WorkerChunkLoadFailed:e=>`Failed to load the Web Worker implementation chunk (dist/worker-*.mjs): ${e} โ deploy every file in dist/ together, or use convertHeic to convert in the current thread`,NativeChunkLoadWarning:e=>`@keeratita/heic-converter: the native-decode chunk could not be loaded (${e}) โ converting with the bundled decoder; serve every file in dist/ together, with dist/native-*.mjs as JavaScript`,RenderEncodeFailed:(e,r)=>`Failed to render and encode image as ${e}: ${r}`,ConcurrencyInvalid:(e,r)=>`Concurrency must be an integer between 1 and ${r}, got: ${e}`,InputsMustBeArray:"Inputs must be an array of HEIC images",OutputShapeInvalid:e=>`output must be one of 'blob', 'dataUrl', 'arrayBuffer', got: ${e}`,SignalInvalid:e=>`signal must be an AbortSignal, got: ${e}`,Aborted:"Conversion aborted (AbortSignal was aborted)",ConvertManyItemFailed:(e,r,t)=>`Conversion of item ${e} of ${r} failed: ${t}`,BatchItemProducedNoResult:(e,r)=>`Conversion of item ${e} of ${r} failed: item produced no result`,BatchEndedWithoutSettling:e=>`Batch ended without settling any of its ${e} items`,ConvertManyExtraFailures:(e,r)=>` (${e} of ${r} items failed in total)`,ConvertManyOtherErrors:e=>`; other errors: ${e.join(" | ")}`,ExifChunkLoadWarning:"@keeratita/heic-converter: the EXIF injector chunk could not be loaded โ converted without metadata; serve every file in dist/ together, with dist/exif-*.mjs as JavaScript.",ScaleInvalid:e=>`Scale must be a positive finite number, got: ${e}`,MaxWidthInvalid:e=>`maxWidth must be a positive finite number, got: ${e}`,MaxHeightInvalid:e=>`maxHeight must be a positive finite number, got: ${e}`,TargetSizeTooLarge:(e,r,t)=>`Target image size ${e}x${r} exceeds the maximum supported dimension of ${t}px`,BlobToBase64FailedWithCause:e=>`Failed to convert Blob to base64 string: ${e}`,CanvasToBlobFailed:e=>`Failed to convert canvas to blob (type: ${e})`,CanvasUnsupported:"Canvas is not supported in the current environment. In a browser this requires OffscreenCanvas or HTMLCanvasElement. In Node.js there is no canvas: decode raw RGBA with LibheifDecoder and encode externally (see the Node.js section of the README).",InvalidDimensions:(e,r)=>`Invalid image dimensions: ${e}x${r}. Width and height must be positive integers.`,DataLengthMismatch:(e,r,t,n)=>`Image data length mismatch. Expected ${e} bytes for ${r}x${t}, got ${n}`,ContextUnavailable:"Failed to acquire 2D rendering context from canvas",UnsupportedFormat:e=>`Unsupported output format: ${e}`,FormatUnsupported:e=>`The current environment cannot encode '${e}' โ canvas encoding produced no '${e}' image (e.g. AVIF encoding is not supported in this browser). Try 'jpeg', 'png', or 'webp' instead.`,CropInvalid:(e,r)=>`crop.${e} must be ${"width"===e||"height"===e?"a positive integer":"a non-negative integer"}, got: ${r}`,CropOutOfBounds:(e,r,t,n,o,i)=>`crop ${t}x${n} at (${e}, ${r}) exceeds the ${o}x${i} image (crop coordinates are in post-orientation display pixels)`,GlueApiMissing:e=>`The bundled decoder glue is missing required APIs (${e}) โ deploy every file in dist/ from the same release; heic-decoder.wasm and its glue chunk must come from one build.`,DecoderFreedDuringDecode:"Decoder was freed before decoding completed; call initialize() again.",DecodeInputAllocFailed:e=>`Failed to allocate ${e} bytes in the WASM heap for decode input`,DecodeFailed:e=>`HEIC decoding failed (no result returned; input: ${e} bytes โ is the file truncated or empty?)`,DecodeFailedWithDetail:(e,r)=>`HEIC decoding failed: ${e} (input: ${r} bytes)`,DecodeFaulted:e=>`Decoder faulted on a ${e}-byte image (out of memory, or a corrupted WebAssembly instance); retry โ a faulted pooled decoder is discarded, not reused`,ProgressCallbackThrew:e=>`onProgress callback threw during decode: ${e}`};function t(e){const r=Number(e);return Number.isFinite(r)?Math.min(100,Math.max(0,r)):0}function n(t){return new e.HeicConverterError("progress_callback_failed",r.ProgressCallbackThrew(t instanceof Error?t.message:String(t)),{cause:t})}function o(e){return"function"==typeof e?e:void 0}var i=["jpeg","jpg","png","svg","webp","avif"];function a(t,n){if(void 0!==n&&"boolean"!=typeof n)throw new e.HeicConverterError("invalid_input",r.BooleanOptionInvalid(t,n))}function d(t){const n=String(t).toLowerCase();if(!i.includes(n))throw new e.HeicConverterError("invalid_format",r.UnsupportedFormat(String(t)))}function s(t){if(!t)return;const{maxWidth:n,maxHeight:o,scale:i}=t;if(void 0!==i&&("number"!=typeof i||!Number.isFinite(i)||i<=0))throw new e.HeicConverterError("invalid_resize",r.ScaleInvalid(i));if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)||n<=0))throw new e.HeicConverterError("invalid_resize",r.MaxWidthInvalid(n));if(void 0!==o&&("number"!=typeof o||!Number.isFinite(o)||o<=0))throw new e.HeicConverterError("invalid_resize",r.MaxHeightInvalid(o))}function c(t){if(!t)return;const{x:n=0,y:o=0,width:i,height:a}=t;if(!Number.isInteger(i)||i<=0)throw new e.HeicConverterError("invalid_crop",r.CropInvalid("width",i));if(!Number.isInteger(a)||a<=0)throw new e.HeicConverterError("invalid_crop",r.CropInvalid("height",a));if(!Number.isInteger(n)||n<0)throw new e.HeicConverterError("invalid_crop",r.CropInvalid("x",n));if(!Number.isInteger(o)||o<0)throw new e.HeicConverterError("invalid_crop",r.CropInvalid("y",o))}exports.DEFAULT_QUALITY=.92,exports.MAX_BATCH_CONCURRENCY=64,exports.Messages=r,exports.SUPPORTED_FORMATS=i,exports.clampPercent=t,exports.progressCallbackError=n,exports.progressCallbackFor=o,exports.progressGateFor=function(e){const r=o(e);return r?function(e){let r,o=!1;return{report:n=>{if(o)return;const i=t(n);if(!(i>=100))try{e(i)}catch(e){r=r??e}},complete:()=>{if(!o){if(o=!0,void 0!==r)throw n(r);try{e(100)}catch(e){throw n(e)}}},pendingError:()=>void 0===r?void 0:n(r)}}(r):void 0},exports.runBoundedBatch=async function(t,n,o,i){const a=!0===i?.continueOnError,d=i?.signal,s=new Array(t.length);let c=0,l=!1,u=0,v=null,h=-1,p=0;const f=[];let g;const m=new Promise(e=>{g=e}),b=()=>g?.();d&&!a&&d.addEventListener("abort",b,{once:!0});const w=function(e,r){return Math.min(e,r)}(n,t.length),y=Array.from({length:w},()=>(async()=>{for(;!l&&!d?.aborted||a;){const n=c;if(c+=1,n>=t.length)return;if(a&&d?.aborted){const o=new e.HeicConverterError("aborted",r.Aborted);for(let e=n;e<t.length;e++)s[e]={index:e,ok:!1,error:o};return void(c=t.length)}try{const e=await o(t[n],n);s[n]={index:n,ok:!0,result:e},u+=1}catch(e){if(p+=1,a){s[n]={index:n,ok:!1,error:e instanceof Error?e:new Error(String(e))};continue}l?f.length<2&&f.push(e instanceof Error?e.message:String(e)):(l=!0,v=e,h=n,g?.())}}})());try{if(a)return await Promise.all(y),s;if(await Promise.race([Promise.all(y),m]),u===t.length)return s.map(n=>{if(!n||!n.ok)throw new e.HeicConverterError("batch_item_failed",r.BatchItemProducedNoResult((n?.index??0)+1,t.length));return n.result});if(d?.aborted)throw new e.HeicConverterError("aborted",r.Aborted);if(l){const n=v instanceof Error?v.message:String(v);let o=r.ConvertManyItemFailed(h+1,t.length,n);throw p>1&&(o+=r.ConvertManyExtraFailures(p,t.length),f.length>0&&(o+=r.ConvertManyOtherErrors(f))),new e.HeicConverterError("batch_item_failed",o,{cause:v,itemIndex:h,itemTotal:t.length,failedCount:p})}throw new e.HeicConverterError("batch_item_failed",r.BatchEndedWithoutSettling(t.length))}finally{d?.removeEventListener("abort",b)}},exports.throwIfAborted=function(t){if(t?.aborted)throw new e.HeicConverterError("aborted",r.Aborted)},exports.validateBatchOptions=function(e){a("continueOnError",e?.continueOnError),a("reuseDecoders",e?.reuseDecoders)},exports.validateConcurrency=function(t){if(!Number.isInteger(t)||t<1||t>64)throw new e.HeicConverterError("invalid_concurrency",r.ConcurrencyInvalid(t,64))},exports.validateConvertOptions=function(t){d(t?.to??"jpeg"),void 0!==t?.quality&&function(t){if("number"!=typeof t||!Number.isFinite(t)||t<0||t>1)throw new e.HeicConverterError("invalid_quality",r.QualityInvalid(t))}(t.quality),a("applyOrientation",t?.applyOrientation),function(t){if(void 0!==t&&"blob"!==t&&"dataUrl"!==t&&"arrayBuffer"!==t)throw new e.HeicConverterError("invalid_input",r.OutputShapeInvalid(t))}(t?.output),function(t){if(void 0!==t&&("object"!=typeof t||null===t||"function"!=typeof t.addEventListener))throw new e.HeicConverterError("invalid_input",r.SignalInvalid(t))}(t?.signal),c(t?.crop),a("preserveExif",t?.preserveExif),a("nativeDecode",t?.nativeDecode),s(t)},exports.validateCrop=c,exports.validateFormat=d,exports.validateResize=s;
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable, machine-readable error codes attached to every error the library
|
|
3
|
+
* throws (as `HeicConverterError.code`). Codes are part of the public API:
|
|
4
|
+
* they are additive-only and never repurposed, so callers can branch on
|
|
5
|
+
* `error.code` instead of matching on message strings.
|
|
6
|
+
*/
|
|
7
|
+
export 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';
|
|
8
|
+
/**
|
|
9
|
+
* Error thrown by all first-party code paths. Extends `Error` so existing
|
|
10
|
+
* `instanceof Error` / message-based handling keeps working; the `code`
|
|
11
|
+
* (and, for batch failures, `itemIndex`/`itemTotal`/`failedCount`) fields
|
|
12
|
+
* add a structured discriminator without changing message text.
|
|
13
|
+
*/
|
|
14
|
+
export declare class HeicConverterError extends Error {
|
|
15
|
+
readonly code: HeicConverterErrorCode;
|
|
16
|
+
/** 0-based index of the failing input. Only set on `batch_item_failed` errors. */
|
|
17
|
+
readonly itemIndex?: number;
|
|
18
|
+
/** Total number of inputs in the batch. Only set on `batch_item_failed` errors. */
|
|
19
|
+
readonly itemTotal?: number;
|
|
20
|
+
/** How many items failed overall. Only set on `batch_item_failed` errors. */
|
|
21
|
+
readonly failedCount?: number;
|
|
22
|
+
constructor(code: HeicConverterErrorCode, message: string, options?: {
|
|
23
|
+
cause?: unknown;
|
|
24
|
+
itemIndex?: number;
|
|
25
|
+
itemTotal?: number;
|
|
26
|
+
failedCount?: number;
|
|
27
|
+
});
|
|
28
|
+
}
|
package/dist/heic-decoder.wasm
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|