@keeratita/heic-converter 0.6.2-prerelease → 0.6.2

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.ts CHANGED
@@ -1,16 +1,398 @@
1
- import type { ConvertItemResult, ConvertManyOptions, ConvertOptions, ConvertResult, HeicInput, OutputShape } from './types';
2
- export * from './types';
3
- export { LibheifDecoder } from './wasm';
4
- export type { LibheifDecoderOptions } from './wasm';
5
- export type { WorkerConvertOptions, WorkerBatchOptions, WorkerResultMessage, WorkerProgressMessage, } from './worker';
6
- import type { WorkerBatchOptions, WorkerConvertOptions } from './worker';
1
+ interface DecodedImage {
2
+ width: number;
3
+ height: number;
4
+ /**
5
+ * RGBA pixel data, interleaved, row-major, 4 bytes per pixel. Always a
6
+ * plain `ArrayBuffer` owned by the returned array — never a WASM-heap
7
+ * view — so it stays valid after `LibheifDecoder.free()` and passes
8
+ * directly to `new ImageData(...)` / `putImageData`, including the
9
+ * `ImageData` overload that requires `Uint8ClampedArray<ArrayBuffer>`
10
+ * under TS >= 5.7.
11
+ */
12
+ data: Uint8ClampedArray;
13
+ /**
14
+ * Raw EXIF block copied from the source file, normalized to the JPEG APP1
15
+ * payload form: `"Exif\0\0"` followed by the TIFF structure. Present
16
+ * whenever the file carries an Exif item — including files where libheif
17
+ * already applied `irot`/`imir` (reported independently of
18
+ * {@link DecodedImage.orientation}). `convertHeic` re-injects it into
19
+ * JPEG (APP1) and PNG (`eXIf`) output when `preserveExif: true`;
20
+ * raw-decode consumers can attach it to their own encoder output (e.g.
21
+ * `sharp`'s `.withMetadata({ exif })`). Owned by the returned object,
22
+ * never a WASM-heap view.
23
+ */
24
+ exif?: Uint8Array;
25
+ /**
26
+ * EXIF orientation of the **stored** pixels (1–8, EXIF tag 274 semantics;
27
+ * 1 = upright). Absent or 1 means no rotation is pending. libheif applies
28
+ * `irot`/`imir` container transforms at decode — for those files this is
29
+ * 1 and the pixels are upright. A value > 1 means the orientation comes
30
+ * only from the Exif item: `convertHeic` applies it automatically unless
31
+ * `applyOrientation: false`; raw `decode()` consumers get stored pixels
32
+ * and must apply it themselves. Decoders that do not report orientation
33
+ * may omit this field.
34
+ */
35
+ orientation?: number;
36
+ }
37
+ /**
38
+ * Decoder contract used by {@link ConvertOptions.decoder} /
39
+ * {@link ConvertManyOptions.decoder} and implemented by `LibheifDecoder`.
40
+ *
41
+ * Lifecycle rules followed by the library (implementations may rely on them):
42
+ * - `initialize()` is called before every `decode()`; repeated/concurrent
43
+ * calls must be cheap (e.g. memoize the load promise).
44
+ * - `decode()` is awaited before the library calls `free()`; the returned
45
+ * `DecodedImage` must therefore not reference decoder-owned memory that
46
+ * `free()` releases (copy pixels out, as `LibheifDecoder` does).
47
+ * - `free()` is called at most once per conversion. Decoders **injected**
48
+ * via options are never freed by the library — the caller owns their
49
+ * lifetime.
50
+ *
51
+ * Concurrency: with `convertMany`, a single injected decoder is shared by
52
+ * all concurrent conversions, so `decode()` must be safe to call concurrently
53
+ * on one instance (no shared mutable state across in-flight decodes).
54
+ */
55
+ interface IHeicDecoder {
56
+ /** Initializes the decoder (e.g. loading the WebAssembly module). */
57
+ initialize(): Promise<void>;
58
+ /**
59
+ * Decodes HEIC binary data into raw RGBA pixel data; `onProgress`
60
+ * receives the progress percentage.
61
+ */
62
+ decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
63
+ /** Cleans up allocated resources. Idempotent: safe to call multiple times. */
64
+ free(): void;
65
+ }
66
+ type ImageFormat = 'jpeg' | 'jpg' | 'png' | 'svg' | 'webp' | 'avif';
67
+ /**
68
+ * Formats accepted by {@link ConvertOptions.to} (case-insensitive).
69
+ * `'jpg'` is an alias of `'jpeg'`. `'avif'` requires an environment whose
70
+ * canvas can encode AVIF (Chromium/Firefox today); elsewhere it rejects with
71
+ * `format_unsupported`.
72
+ */
73
+ declare const SUPPORTED_FORMATS: readonly ImageFormat[];
74
+ /** Default encoding quality used when `quality` is not provided. */
75
+ declare const DEFAULT_QUALITY = 0.92;
76
+ /**
77
+ * Accepted input for every convert entry point. `ArrayBufferView` is a
78
+ * declared (tested) surface: `DataView` and non-Uint8 typed arrays are read
79
+ * as raw bytes via byteOffset/byteLength, SharedArrayBuffer-backed views
80
+ * included. Cross-realm Blob-likes (anything exposing `arrayBuffer()`, e.g.
81
+ * a Blob from another frame) are accepted at runtime even though
82
+ * `instanceof Blob` cannot see them.
83
+ */
84
+ type HeicInput = Blob | ArrayBuffer | ArrayBufferView;
85
+ /**
86
+ * How {@link convertHeic} returns the converted image.
87
+ * - `'blob'` — a `Blob` (the default; browser-native, works everywhere)
88
+ * - `'dataUrl'` — a `data:image/...;base64,…` string (previews, `<img src>`)
89
+ * - `'arrayBuffer'` — raw bytes (uploads, WebCodecs, Node-friendly transfer)
90
+ */
91
+ type OutputShape = 'blob' | 'dataUrl' | 'arrayBuffer';
92
+ /** Resolved return type of `convertHeic`/`convertMany` for an output shape. */
93
+ type ConvertResult<S extends OutputShape> = S extends 'dataUrl' ? string : S extends 'arrayBuffer' ? ArrayBuffer : Blob;
94
+ /** Crop rectangle in **post-orientation display pixels** (top-left origin). */
95
+ interface CropOptions {
96
+ /** Left edge of the crop box. @default 0 */
97
+ x?: number;
98
+ /** Top edge of the crop box. @default 0 */
99
+ y?: number;
100
+ /** Crop width in pixels. Must be a positive integer and fit inside the image. */
101
+ width: number;
102
+ /** Crop height in pixels. Must be a positive integer and fit inside the image. */
103
+ height: number;
104
+ }
105
+ /** Per-item outcome when `continueOnError: true`. */
106
+ type ConvertItemResult<T = Blob> = {
107
+ index: number;
108
+ ok: true;
109
+ result: T;
110
+ } | {
111
+ index: number;
112
+ ok: false;
113
+ error: Error;
114
+ };
115
+ interface ResizeOptions {
116
+ /**
117
+ * Maximum width in pixels; downscaled to fit while preserving the aspect
118
+ * ratio. Images smaller than the bound are never upscaled.
119
+ */
120
+ maxWidth?: number;
121
+ /**
122
+ * Maximum height in pixels; downscaled to fit while preserving the aspect
123
+ * ratio. Images smaller than the bound are never upscaled.
124
+ */
125
+ maxHeight?: number;
126
+ /**
127
+ * Uniform scale factor for both dimensions (e.g. 0.5 halves the image).
128
+ * Takes precedence over `maxWidth`/`maxHeight` when set.
129
+ */
130
+ scale?: number;
131
+ }
132
+ interface ConvertOptions extends ResizeOptions {
133
+ /**
134
+ * Target format; must be one of {@link SUPPORTED_FORMATS}. An unknown
135
+ * value is rejected up front, before the input is decoded.
136
+ * @default 'jpeg'
137
+ */
138
+ to?: ImageFormat;
139
+ /**
140
+ * Quality between 0.0 and 1.0 (inclusive). Applies to `'jpeg'`, `'jpg'`,
141
+ * `'webp'` and `'avif'` but is validated for every format: an out-of-range
142
+ * value (e.g. `90` from a 0-100 scale) throws regardless of `to`.
143
+ * @default 0.92
144
+ */
145
+ quality?: number;
146
+ /**
147
+ * Custom decoder to inject; a default `LibheifDecoder` is used otherwise.
148
+ * The library never calls `free()` on an injected decoder.
149
+ */
150
+ decoder?: IHeicDecoder;
151
+ /**
152
+ * Progress callback receiving percentages normalized and clamped to
153
+ * 0–100; the final 100% is emitted only when the conversion succeeds. A
154
+ * callback that throws rejects the conversion with
155
+ * `progress_callback_failed`.
156
+ */
157
+ onProgress?: (percent: number) => void;
158
+ /**
159
+ * Rotate/flip the output to match the source's EXIF orientation, applied
160
+ * as a canvas transform during rendering; `irot`/`imir` container
161
+ * transforms are already applied by the decoder and never stacked on top.
162
+ * `false` keeps the exact stored-pixel geometry. A non-boolean value is
163
+ * rejected up front with `invalid_input`.
164
+ * @default true
165
+ */
166
+ applyOrientation?: boolean;
167
+ /**
168
+ * Representation of the converted image. See {@link OutputShape}.
169
+ * @default 'blob'
170
+ */
171
+ output?: OutputShape;
172
+ /**
173
+ * Cancels the conversion at stage boundaries (input read, decoder init,
174
+ * before/after decode, before encode). `convertHeicInWorker` aborts
175
+ * immediately by terminating the worker; the synchronous WASM decode
176
+ * itself cannot be preempted mid-call. An aborted signal rejects with
177
+ * code `aborted`.
178
+ */
179
+ signal?: AbortSignal;
180
+ /**
181
+ * Crop rectangle in post-orientation display pixels (the geometry the
182
+ * image will be displayed in). Applied before resize: `scale`/`maxWidth`/
183
+ * `maxHeight` then downscale the cropped region. Out-of-bounds crops
184
+ * reject with `invalid_crop`.
185
+ */
186
+ crop?: CropOptions;
187
+ /**
188
+ * Copy the source HEIC's EXIF block into JPEG (APP1) and PNG (`eXIf`
189
+ * chunk) output so converted files keep camera metadata (orientation, GPS,
190
+ * timestamps). This **preserves private data** like GPS — set
191
+ * deliberately. Ignored for `webp`/`svg` output.
192
+ * @default false
193
+ */
194
+ preserveExif?: boolean;
195
+ /**
196
+ * Decode with the platform's native HEIC stack (`createImageBitmap` on
197
+ * Safari/iOS, Edge, Windows) instead of the bundled libheif WASM decoder,
198
+ * skipping its ~300 KB payload. Hosts without native HEIC support fall
199
+ * back to libheif on the same conversion; the refusal is cached per realm.
200
+ * Ignored (libheif used) with an injected `decoder`, `preserveExif: true`
201
+ * or `applyOrientation: false`. Native output is upright and progress
202
+ * fires only at completion (tile progress is a libheif feature).
203
+ * @default false
204
+ */
205
+ nativeDecode?: boolean;
206
+ }
207
+ interface ConvertManyOptions extends Omit<ConvertOptions, 'onProgress'> {
208
+ /**
209
+ * Maximum number of conversions running concurrently.
210
+ * @default 4
211
+ */
212
+ concurrency?: number;
213
+ /**
214
+ * Progress callback receiving the 0-based item index and its percentage
215
+ * (normalized to 0–100) during decoding.
216
+ */
217
+ onProgress?: (index: number, percent: number) => void;
218
+ /**
219
+ * Custom decoder to inject; the same instance is shared by all concurrent
220
+ * conversions, so it must be safe for concurrent `decode()` calls (see
221
+ * {@link IHeicDecoder}). A fresh default `LibheifDecoder` is created per
222
+ * item otherwise.
223
+ */
224
+ decoder?: IHeicDecoder;
225
+ /**
226
+ * Resolve with `ConvertItemResult[]` in input order instead of rejecting
227
+ * the whole batch on the first failure; all items run to completion.
228
+ * Up-front option validation failures still reject normally (a typo is a
229
+ * caller bug, not an item failure).
230
+ * @default false
231
+ */
232
+ continueOnError?: boolean;
233
+ /**
234
+ * Reuse one library-owned `LibheifDecoder` per concurrent runner across
235
+ * items instead of creating (and WASM-initializing) a fresh instance per
236
+ * item — amortizes the module load in large batches while preserving the
237
+ * exclusive-use invariant (an instance is only ever held by one runner,
238
+ * never decodes concurrently). Ignored when `decoder` is injected.
239
+ * @default false
240
+ */
241
+ reuseDecoders?: boolean;
242
+ }
243
+
244
+ interface LibheifDecoderOptions {
245
+ /**
246
+ * Custom WASM file locator, for serving the binary from a custom route or CDN.
247
+ */
248
+ locateFile?: (path: string, prefix: string) => string;
249
+ /**
250
+ * Raw WASM binary, used instead of fetching the file. Accepts an
251
+ * `ArrayBuffer` or any `ArrayBufferView` (e.g. a Node.js `Buffer` from
252
+ * `fs.readFileSync`).
253
+ */
254
+ wasmBinary?: ArrayBuffer | ArrayBufferView;
255
+ /**
256
+ * Advanced: extra properties merged into the Emscripten module argument
257
+ * object (e.g. `instantiateWasm` for streaming compilation). Prefer
258
+ * `locateFile`/`wasmBinary` for the common cases; keys must not collide
259
+ * with them.
260
+ */
261
+ moduleOverrides?: Record<string, unknown>;
262
+ }
263
+ declare class LibheifDecoder implements IHeicDecoder {
264
+ private options?;
265
+ private module;
266
+ private initPromise;
267
+ private initGeneration;
268
+ constructor(options?: LibheifDecoderOptions);
269
+ /**
270
+ * Initializes the WebAssembly module (the raw C-ABI decoder surface).
271
+ * Safe to call concurrently: the module is loaded at most once per instance.
272
+ */
273
+ initialize(): Promise<void>;
274
+ /**
275
+ * Decodes HEIC binary data into raw RGBA pixel data.
276
+ * @param onProgress Optional progress callback; receives percentages
277
+ * normalized and clamped to 0-100.
278
+ */
279
+ decode(data: Uint8Array, onProgress?: (percent: number) => void): Promise<DecodedImage>;
280
+ /**
281
+ * Cleans up the WebAssembly decoder resources. Idempotent. After `free()`,
282
+ * the next `initialize()` — or `decode()` directly, which re-initializes
283
+ * transparently — loads a fresh module. Safe during an in-flight
284
+ * `initialize()`: a load completing after `free()` discards itself instead
285
+ * of resurrecting state.
286
+ */
287
+ free(): void;
288
+ }
289
+
290
+ interface WorkerConvertOptions extends Omit<ConvertOptions, 'decoder'> {
291
+ /**
292
+ * URL of the worker script. Should be a compile-time constant (e.g.
293
+ * `new URL('./worker.js', import.meta.url)` under a bundler); the script
294
+ * runs with the page's privileges.
295
+ */
296
+ workerUrl: string | URL;
297
+ /**
298
+ * Milliseconds to wait for the worker result before rejecting with a
299
+ * timeout. Queueing for a free worker slot counts toward this. Defaults to
300
+ * 60000; 0 disables the timeout.
301
+ */
302
+ timeoutMs?: number;
303
+ /**
304
+ * Worker script type. Use `'module'` when the script uses ES module
305
+ * imports (e.g. `import { convertHeic } from ...`); `'classic'`
306
+ * scripts must be pre-bundled.
307
+ * @default 'classic'
308
+ */
309
+ workerType?: 'classic' | 'module';
310
+ /**
311
+ * Upper bound on simultaneously live workers for this worker script; calls
312
+ * beyond the bound queue until a slot frees, keeping bulk conversions from
313
+ * exhausting memory or the browser's worker limit. Must be an integer from
314
+ * 1 to 64 — each worker is a full WASM boot with its own heap, so an
315
+ * unbounded value is a page-taking-down footgun, not capacity. Defaults to
316
+ * `navigator.hardwareConcurrency` clamped to 1–8.
317
+ */
318
+ maxConcurrentWorkers?: number;
319
+ }
320
+ interface CorrelatedMessage {
321
+ id: number;
322
+ }
323
+ /** Progress message a worker script posts to report decode progress. */
324
+ interface WorkerProgressMessage extends CorrelatedMessage {
325
+ type: 'progress';
326
+ percent: number;
327
+ }
328
+ /** Result message a worker script posts to settle a conversion. */
329
+ interface WorkerResultMessage extends CorrelatedMessage {
330
+ type: 'result';
331
+ ok: boolean;
332
+ /**
333
+ * The converted image as `convertHeic` returned it inside the worker:
334
+ * `Blob`, data-URL string, or `ArrayBuffer`. The field name `blob` is kept
335
+ * for protocol compatibility.
336
+ */
337
+ blob?: Blob | string | ArrayBuffer;
338
+ error?: string;
339
+ }
340
+ /**
341
+ * Options for {@link convertManyInWorker}: the {@link convertHeicInWorker}
342
+ * worker options plus the batch semantics of `convertMany`.
343
+ */
344
+ interface WorkerBatchOptions extends Omit<WorkerConvertOptions, 'onProgress'> {
345
+ /**
346
+ * Per-item progress callback: receives the 0-based item index and its
347
+ * progress percentage (normalized 0–100). Values below 100 may also be
348
+ * reported for items that ultimately fail; the 100% event fires only for
349
+ * items that succeed.
350
+ */
351
+ onProgress?: (index: number, percent: number) => void;
352
+ /**
353
+ * Resolve with per-item results instead of rejecting the batch on the
354
+ * first failure; all items run to completion (see
355
+ * `ConvertManyOptions.continueOnError`).
356
+ * @default false
357
+ */
358
+ continueOnError?: boolean;
359
+ }
360
+
361
+ /**
362
+ * Stable, machine-readable error codes attached to every error the library
363
+ * throws (as `HeicConverterError.code`). Codes are part of the public API:
364
+ * they are additive-only and never repurposed, so callers can branch on
365
+ * `error.code` instead of matching on message strings.
366
+ */
367
+ 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';
368
+ /**
369
+ * Error thrown by all first-party code paths. Extends `Error` so existing
370
+ * `instanceof Error` / message-based handling keeps working; the `code`
371
+ * (and, for batch failures, `itemIndex`/`itemTotal`/`failedCount`) fields
372
+ * add a structured discriminator without changing message text.
373
+ */
374
+ declare class HeicConverterError extends Error {
375
+ readonly code: HeicConverterErrorCode;
376
+ /** 0-based index of the failing input. Only set on `batch_item_failed` errors. */
377
+ readonly itemIndex?: number;
378
+ /** Total number of inputs in the batch. Only set on `batch_item_failed` errors. */
379
+ readonly itemTotal?: number;
380
+ /** How many items failed overall. Only set on `batch_item_failed` errors. */
381
+ readonly failedCount?: number;
382
+ constructor(code: HeicConverterErrorCode, message: string, options?: {
383
+ cause?: unknown;
384
+ itemIndex?: number;
385
+ itemTotal?: number;
386
+ failedCount?: number;
387
+ });
388
+ }
389
+
7
390
  /**
8
391
  * Converts a HEIC image inside a Web Worker so the main thread stays responsive
9
- * during the (potentially slow) WASM decode. This is the public entry point; the
10
- * implementation lives in `src/worker.ts` and is fetched as a lazy chunk on the
11
- * first call, so a deployment missing that chunk rejects with
12
- * `worker_load_failed` (original failure on `cause`) rather than a raw
13
- * module-load error.
392
+ * during the (potentially slow) WASM decode. The implementation lives in
393
+ * `src/worker.ts`, fetched as a lazy chunk on the first call — a deployment
394
+ * missing that chunk rejects with `worker_load_failed` (original failure on
395
+ * `cause`) rather than a raw module-load error.
14
396
  *
15
397
  * The worker script is user-provided and must handle the following message
16
398
  * protocol (types are exported as {@link WorkerProgressMessage} and
@@ -72,7 +454,7 @@ import type { WorkerBatchOptions, WorkerConvertOptions } from './worker';
72
454
  * @returns The converted image as a Blob, data URL string, or ArrayBuffer
73
455
  * depending on `options.output` (default Blob).
74
456
  */
75
- export declare function convertHeicInWorker<S extends OutputShape = 'blob'>(input: HeicInput, options: WorkerConvertOptions & {
457
+ declare function convertHeicInWorker<S extends OutputShape = 'blob'>(input: HeicInput, options: WorkerConvertOptions & {
76
458
  output?: S;
77
459
  }): Promise<ConvertResult<S>>;
78
460
  /**
@@ -80,14 +462,12 @@ export declare function convertHeicInWorker<S extends OutputShape = 'blob'>(inpu
80
462
  * semantics (input order, bounded concurrency, `batch_item_failed` aggregation
81
463
  * or `continueOnError` per-item results). Concurrency is bounded by
82
464
  * `maxConcurrentWorkers` (default `navigator.hardwareConcurrency` clamped to
83
- * 1–8): items queue behind the worker semaphore, so a large batch never
84
- * exhausts memory or the browser's worker limit. Workers are pooled per
85
- * `workerUrl`, so items reuse live instances rather than paying boot per
86
- * item (see the worker-protocol note above — the script must stay alive
87
- * across requests). Via {@link convertHeicInWorker}, which means `decoder`
88
- * cannot be injected and `workerUrl` is required. See that function for the
89
- * worker script protocol and the caveats about `timeoutMs`, the worker
90
- * boundary, and `worker_load_failed`.
465
+ * 1–8), so a large batch never exhausts memory or the browser's worker limit;
466
+ * workers are pooled per `workerUrl`, so items reuse live instances instead
467
+ * of paying boot per item (the script must stay alive across requests — see
468
+ * the protocol above). Runs via {@link convertHeicInWorker}: `decoder` cannot
469
+ * be injected and `workerUrl` is required — see it for the protocol and the
470
+ * `timeoutMs`, worker-boundary, and `worker_load_failed` caveats.
91
471
  *
92
472
  * ```ts
93
473
  * const blobs = await convertManyInWorker(heicFiles, {
@@ -107,27 +487,26 @@ export declare function convertHeicInWorker<S extends OutputShape = 'blob'>(inpu
107
487
  * @returns The converted images in input order, or per-item result entries
108
488
  * when `continueOnError: true`.
109
489
  */
110
- export declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
490
+ declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
111
491
  output?: S;
112
492
  continueOnError: true;
113
493
  }): Promise<ConvertItemResult<ConvertResult<S>>[]>;
114
- export declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
494
+ declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
115
495
  output?: S;
116
496
  continueOnError?: false;
117
497
  }): Promise<ConvertResult<S>[]>;
118
- export declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
498
+ declare function convertManyInWorker<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: WorkerBatchOptions & {
119
499
  output?: S;
120
500
  continueOnError: boolean;
121
501
  }): Promise<Array<ConvertResult<S> | ConvertItemResult<ConvertResult<S>>>>;
122
- export { HeicConverterError } from './errors';
123
- export type { HeicConverterErrorCode } from './errors';
502
+
124
503
  /**
125
504
  * Releases any cached decoder resources.
126
505
  *
127
506
  * Decoders are now created and released per conversion, so there is no shared
128
507
  * instance to free. This function is kept for API compatibility.
129
508
  */
130
- export declare function freeSharedDecoder(): void;
509
+ declare function freeSharedDecoder(): void;
131
510
  /**
132
511
  * Converts HEIC image data to a standard web format (JPEG, PNG, WebP, AVIF,
133
512
  * or SVG).
@@ -148,7 +527,7 @@ export declare function freeSharedDecoder(): void;
148
527
  * in Safari), `aborted` (`options.signal` aborted), or
149
528
  * `render_encode_failed`.
150
529
  */
151
- export declare function convertHeic<S extends OutputShape = 'blob'>(input: HeicInput, options?: ConvertOptions & {
530
+ declare function convertHeic<S extends OutputShape = 'blob'>(input: HeicInput, options?: ConvertOptions & {
152
531
  output?: S;
153
532
  }): Promise<ConvertResult<S>>;
154
533
  /**
@@ -170,15 +549,18 @@ export declare function convertHeic<S extends OutputShape = 'blob'>(input: HeicI
170
549
  * @returns The converted images in input order: results array by default,
171
550
  * or per-item result entries when `continueOnError: true`.
172
551
  */
173
- export declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: ConvertManyOptions & {
552
+ declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: ConvertManyOptions & {
174
553
  output?: S;
175
554
  continueOnError: true;
176
555
  }): Promise<ConvertItemResult<ConvertResult<S>>[]>;
177
- export declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options?: ConvertManyOptions & {
556
+ declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options?: ConvertManyOptions & {
178
557
  output?: S;
179
558
  continueOnError?: false;
180
559
  }): Promise<ConvertResult<S>[]>;
181
- export declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: ConvertManyOptions & {
560
+ declare function convertMany<S extends OutputShape = 'blob'>(inputs: HeicInput[], options: ConvertManyOptions & {
182
561
  output?: S;
183
562
  continueOnError: boolean;
184
563
  }): Promise<Array<ConvertResult<S> | ConvertItemResult<ConvertResult<S>>>>;
564
+
565
+ export { DEFAULT_QUALITY, HeicConverterError, LibheifDecoder, SUPPORTED_FORMATS, convertHeic, convertHeicInWorker, convertMany, convertManyInWorker, freeSharedDecoder };
566
+ export type { ConvertItemResult, ConvertManyOptions, ConvertOptions, ConvertResult, CropOptions, DecodedImage, HeicConverterErrorCode, HeicInput, IHeicDecoder, ImageFormat, LibheifDecoderOptions, OutputShape, ResizeOptions, WorkerBatchOptions, WorkerConvertOptions, WorkerProgressMessage, WorkerResultMessage };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("./chunk-TND3VERK.js"),t=require("./chunk-N2LCVW2Q.js"),r=new WeakSet,n=/[\u0000-\u001f\u007f-\u009f]+/g,i=class{options;module=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const r=++this.initGeneration,n={};this.options?.moduleOverrides&&Object.assign(n,this.options.moduleOverrides),this.options?.locateFile&&(n.locateFile=this.options.locateFile),this.options?.wasmBinary&&(n.wasmBinary=this.options.wasmBinary);const i=import("./heic-decoder-2EERQO7N.js").then(({default:e})=>e(n)).then(n=>{if(r!==this.initGeneration)return null;const i=["function"==typeof n._heic_decode?null:"_heic_decode","function"==typeof n._heic_result_free?null:"_heic_result_free","function"==typeof n._malloc?null:"_malloc","function"==typeof n._free?null:"_free",n.HEAPU8 instanceof Uint8Array?null:"HEAPU8"].filter(e=>null!==e);if(i.length>0)throw new t.HeicConverterError("decoder_init_failed",e.Messages.GlueApiMissing(i.join(", ")));return this.module=n,n}).catch(e=>{throw this.initPromise===i&&(this.initPromise=null),e});this.initPromise=i}await this.initPromise}async decode(i,o){this.module||await this.initialize();const a=this.module;if(!a)throw new t.HeicConverterError("decode_failed",e.Messages.DecoderFreedDuringDecode);let s;const c=o?t=>{try{o(e.clampPercent(t))}catch(e){s=s??e,a.__progressCb=null}}:null,u=i.buffer===a.HEAPU8.buffer?new Uint8Array(i):i;let f,d=0,l=0;try{if(d=a._malloc(u.byteLength),0===d)throw new t.HeicConverterError("decode_failed",e.Messages.DecodeInputAllocFailed(u.byteLength));a.HEAPU8.set(u,d);const r=a.__progressCb??null;a.__progressCb=c;try{l=a._heic_decode(d,u.byteLength)}finally{a.__progressCb=r}const o=a.HEAPU8;if(0===l)throw new TypeError("heic_decode returned a null result");const s=new DataView(o.buffer,l,36),h=s.getInt32(0,!0);if(0===h){const r=s.getUint32(28,!0),a=s.getUint32(32,!0),c=0!==r?(new TextDecoder).decode(o.subarray(r,r+a)):"";throw new t.HeicConverterError("decode_failed",c?e.Messages.DecodeFailedWithDetail(function(e){const t=e.replace(n," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(c),i.byteLength):e.Messages.DecodeFailed(i.byteLength))}const w=s.getInt32(4,!0),g=s.getInt32(8,!0),p=g>=1&&g<=8?g:1,v=s.getUint32(12,!0),y=s.getUint32(16,!0),m=4*h,_=new Uint8ClampedArray(m*w);if(y===m)_.set(o.subarray(v,v+m*w));else for(let e=0;e<w;e++)_.set(o.subarray(v+e*y,v+e*y+m),e*m);f={width:h,height:w,data:_},p>1&&(f.orientation=p);const b=s.getUint32(20,!0),E=s.getUint32(24,!0);0!==b&&E>=14&&(f.exif=o.slice(b,b+E))}catch(n){if(n instanceof t.HeicConverterError)throw n;throw r.add(this),new t.HeicConverterError("decode_failed",e.Messages.DecodeFaulted(i.byteLength),{cause:n})}finally{a.__progressCb=null;try{0!==l&&a._heic_result_free(l),0!==d&&a._free(d)}catch{}}if(void 0!==s)throw e.progressCallbackError(s);return f}free(){this.initGeneration+=1,this.module=null,r.delete(this),this.initPromise=null}},o=16384;function a(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new t.HeicConverterError("unsupported_environment",e.Messages.CanvasUnsupported)}var s=null,c=0;function u(){if(null===s){if(Date.now()<c)return Promise.resolve(void 0);const e=async function(){let e;try{e=w(1,1)}catch{return}const t=h(e,"image/avif");let r;const n=new Promise(e=>{r=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,n]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==r&&clearTimeout(r),g(e)}}().catch(()=>{});s=e,e.then(t=>{void 0===t&&s===e&&(s=null,c=Date.now()+1e4)})}return s}async function f(r){if(e.validateFormat(r),"avif"===String(r).toLowerCase()&&!1===await u())throw new t.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"))}function d(r,n){if(!Number.isFinite(r)||!Number.isFinite(n)||r>o||n>o)throw new t.HeicConverterError("invalid_resize",e.Messages.TargetSizeTooLarge(r,n,o))}async function l(r){try{const e=await r.arrayBuffer(),t=new Uint8Array(e);let n="";const i=32768;for(let e=0;e<t.length;e+=i)n+=String.fromCharCode(...t.subarray(e,e+i));const o=btoa(n);return`data:${r.type};base64,${o}`}catch(r){throw new t.HeicConverterError("render_encode_failed",e.Messages.BlobToBase64FailedWithCause(r instanceof Error?r.message:String(r)),{cause:r})}}function h(r,n,i){return"convertToBlob"in r?r.convertToBlob({type:n,quality:i}):new Promise((o,a)=>{r.toBlob(r=>{r?o(r):a(new t.HeicConverterError("render_encode_failed",e.Messages.CanvasToBlobFailed(n)))},n,i)})}function w(r,n){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(r,n);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=r,e.height=n,e}throw new t.HeicConverterError("unsupported_environment",e.Messages.CanvasUnsupported)}function g(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function p(e,t,r,n){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,r,n),0,0);else{const i=e.createImageData(r,n);i.data.set(t),e.putImageData(i,0,0)}}var v=!1;async function y(t,r,n,i,o){const a=r.exif;if(!n||!a||0===a.length)return t;const s=await import("./exif-H2Q7BO7Y.js").catch(()=>null);if(!s)return v||(v=!0,console.warn(e.Messages.ExifChunkLoadWarning)),t;const{injectExifIntoJpeg:c,injectExifIntoPng:u,normalizeOrientationTag:f}=s,d=o?f(a):a,l=new Uint8Array(await t.arrayBuffer()),h="jpeg"===i?c(l,d):u(l,d);return h===l?t:new Blob([h.buffer],{type:t.type})}function m(){return import("./worker-DISSAV3W.js").catch(r=>{const n=r instanceof Error?r.message:String(r);throw new t.HeicConverterError("worker_load_failed",e.Messages.WorkerChunkLoadFailed(n),{cause:r})})}function _(e){return!0===e?.nativeDecode&&!0!==e?.preserveExif&&!1!==e?.applyOrientation}var b=!1;async function E(r,n){const o=n?.to??"jpeg";e.validateConvertOptions(n),a(),await f(o);const s=n?.signal;e.throwIfAborted(s);const c=n,v=await async function(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if("undefined"!=typeof Blob&&r instanceof Blob)return new Uint8Array(await r.arrayBuffer());if(null!==r&&"object"==typeof r&&"function"==typeof r.arrayBuffer){const e=await r.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new t.HeicConverterError("invalid_input",e.Messages.UnsupportedInputType(Object.prototype.toString.call(r)))}(r);let m,E;e.throwIfAborted(s);let C,I=!1;if(n?.decoder)m=n.decoder,E=!1;else if(_(n)){try{C=await(import("./native-JFFONPCS.js"))}catch(t){M=t instanceof Error?t.message:String(t),b||(b=!0,console.warn(e.Messages.NativeChunkLoadWarning(M)))}void 0===C||C.isNativeHeicRefused()?m=new i:(m=new C.NativeHeicDecoder,I=!0),E=!0}else m=new i,E=!0;var M;let H=!1;const U=()=>{if(E&&!H){H=!0;try{m.free()}catch{}}};try{const r=e.progressGateFor(n?.onProgress),a=async n=>{try{await n.initialize()}catch(r){throw new t.HeicConverterError("decoder_init_failed",e.Messages.DecoderInitFailed(r instanceof Error?r.message:String(r)),{cause:r})}return e.throwIfAborted(s),n.decode(v,r?r.report:void 0)};let f;try{f=await a(m)}catch(r){if(!I)throw r;if(r instanceof t.HeicConverterError&&"aborted"===r.code)throw r;r instanceof t.HeicConverterError&&"decoder_init_failed"===r.code&&C.markNativeHeicRefused(),e.throwIfAborted(s),U(),m=new i,H=!1,I=!1,f=await a(m)}U(),e.throwIfAborted(s);const _=void 0!==n?.quality?n.quality:e.DEFAULT_QUALITY;let b;try{b=await async function(r,n,i,o,a=!0,s,c=!1){e.validateFormat(n),e.validateCrop(s);const f=n.toLowerCase();if("avif"===f&&!1===await u())throw new t.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"));const{width:v,height:m,data:_}=r;if(!Number.isInteger(v)||v<=0||!Number.isInteger(m)||m<=0)throw new t.HeicConverterError("render_encode_failed",e.Messages.InvalidDimensions(v,m));const b=v*m*4;if(_.length!==b)throw new t.HeicConverterError("render_encode_failed",e.Messages.DataLengthMismatch(b,v,m,_.length));const E=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(r.orientation,a),C=!(void 0!==r.orientation&&r.orientation>=2&&r.orientation<=8)||a,I=function(e,t,r){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,r];case 4:return[1,0,0,-1,0,r];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,r,0];case 7:return[0,-1,-1,0,r,t];case 8:return[0,-1,1,0,0,t];default:return null}}(E,v,m),M=E>=5,H=M?m:v,U=M?v:m,A=s?.x??0,F=s?.y??0,O=s?s.width:H,P=s?s.height:U;if(s&&(A+O>H||F+P>U))throw new t.HeicConverterError("invalid_crop",e.Messages.CropOutOfBounds(A,F,O,P,H,U));const x=function(t,r,n){if(e.validateResize(n),!n)return{width:t,height:r};const{maxWidth:i,maxHeight:o,scale:a}=n;if(void 0!==a){const e=Math.max(1,Math.round(t*a)),n=Math.max(1,Math.round(r*a));return d(e,n),{width:e,height:n}}if(void 0===i&&void 0===o)return{width:t,height:r};const s=Math.min(void 0!==i?i/t:Number.POSITIVE_INFINITY,void 0!==o?o/r:Number.POSITIVE_INFINITY);if(s>=1)return{width:t,height:r};const c=Math.min(Math.max(1,Math.round(t*s)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),u=Math.min(Math.max(1,Math.round(r*s)),void 0!==o?Math.floor(o):Number.POSITIVE_INFINITY);return d(c,u),{width:c,height:u}}(O,P,o),D=x.width!==O||x.height!==P,T=null!==I||void 0!==s,B=w(x.width,x.height),N=B.getContext("2d");if(!N)throw new t.HeicConverterError("render_encode_failed",e.Messages.ContextUnavailable);if(T||D){const r=w(v,m),n=r.getContext("2d");if(!n)throw new t.HeicConverterError("render_encode_failed",e.Messages.ContextUnavailable);if(p(n,_,v,m),T){const e=x.width/O,t=x.height/P,n=I?I[0]:1,i=I?I[1]:0,o=I?I[2]:0,a=I?I[3]:1,s=I?I[4]:0,c=I?I[5]:0;N.setTransform(n*e,i*t,o*e,a*t,e*(s-A),t*(c-F)),N.drawImage(r,0,0)}else N.drawImage(r,0,0,x.width,x.height);g(r)}else p(N,_,v,m);if("png"===f){const e=await h(B,"image/png");return g(B),y(e,r,c,"png",C)}if("jpeg"===f||"jpg"===f){const e=await h(B,"image/jpeg",i);return g(B),y(e,r,c,"jpeg",C)}if("webp"===f){const e=await h(B,"image/webp",i);return g(B),e}if("avif"===f){const r=await h(B,"image/avif",i);if(g(B),"image/avif"!==r.type)throw new t.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"));return r}if("svg"===f){const e=await h(B,"image/png");g(B);const t=await l(e),r=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${x.width} ${x.height}" width="${x.width}" height="${x.height}">\n <image width="${x.width}" height="${x.height}" href="`;return new Blob([r,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new t.HeicConverterError("invalid_format",e.Messages.UnsupportedFormat(String(n)))}(f,o,_,c,n?.applyOrientation??!0,n?.crop,n?.preserveExif??!1)}catch(r){if(r instanceof t.HeicConverterError)throw r;throw new t.HeicConverterError("render_encode_failed",e.Messages.RenderEncodeFailed(o,r instanceof Error?r.message:String(r)),{cause:r})}return e.throwIfAborted(s),r?.complete(),async function(e,t){return"dataUrl"===t?await l(e):"arrayBuffer"===t?await e.arrayBuffer():e}(b,n?.output??"blob")}finally{U()}}var C=class{idle=[];disposed=!1;acquire(){return this.idle.pop()??new i}release(e){if(this.disposed||function(e){return r.has(e)}(e))try{e.free()}catch{}else this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0}};Object.defineProperty(exports,"DEFAULT_QUALITY",{enumerable:!0,get:function(){return e.DEFAULT_QUALITY}}),Object.defineProperty(exports,"SUPPORTED_FORMATS",{enumerable:!0,get:function(){return e.SUPPORTED_FORMATS}}),Object.defineProperty(exports,"HeicConverterError",{enumerable:!0,get:function(){return t.HeicConverterError}}),exports.LibheifDecoder=i,exports.convertHeic=E,exports.convertHeicInWorker=function(e,t){return m().then(r=>r.convertHeicInWorker(e,t))},exports.convertMany=async function(r,n){if(!Array.isArray(r))throw new t.HeicConverterError("invalid_input",e.Messages.InputsMustBeArray);const i=n?.concurrency??4;e.validateConcurrency(i),e.validateConvertOptions(n),e.validateBatchOptions(n),a(),await f(n?.to??"jpeg");const{concurrency:o,onProgress:s,continueOnError:c,reuseDecoders:u,...d}=n??{},l=e.progressCallbackFor(s),h=!0!==u||void 0!==n?.decoder||_(n)?null:new C;try{return await e.runBoundedBatch(r,i,async(e,t)=>{const r=h?h.acquire():null;try{return await E(e,{...d,...r?{decoder:r}:{},onProgress:l?e=>l(t,e):void 0})}finally{r&&h.release(r)}},{continueOnError:!0===n?.continueOnError,signal:n?.signal})}finally{h?.dispose()}},exports.convertManyInWorker=function(e,t){return m().then(r=>r.convertManyInWorker(e,t))},exports.freeSharedDecoder=function(){};
1
+ var e=require("./chunk-6XIPSRPS.js"),t=require("./chunk-N2LCVW2Q.js"),r=new WeakSet,n=/[\u0000-\u001f\u007f-\u009f]+/g,i=class{options;module=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const r=++this.initGeneration,n={};this.options?.moduleOverrides&&Object.assign(n,this.options.moduleOverrides),this.options?.locateFile&&(n.locateFile=this.options.locateFile);const i=import("./heic-decoder-LWGIYGE3.js").then(async({default:e})=>{if(this.options?.wasmBinary){const e=await WebAssembly.compile(this.options.wasmBinary);n.instantiateWasm=(t,r)=>r(new WebAssembly.Instance(e,t))}return e(n)}).then(n=>{if(r!==this.initGeneration)return null;const i=["function"==typeof n._heic_decode?null:"_heic_decode","function"==typeof n._heic_result_free?null:"_heic_result_free","function"==typeof n._malloc?null:"_malloc","function"==typeof n._free?null:"_free",n.HEAPU8 instanceof Uint8Array?null:"HEAPU8"].filter(e=>null!==e);if(i.length>0)throw new t.HeicConverterError("decoder_init_failed",e.Messages.GlueApiMissing(i.join(", ")));return this.module=n,n}).catch(e=>{throw this.initPromise===i&&(this.initPromise=null),e});this.initPromise=i}await this.initPromise}async decode(i,o){this.module||await this.initialize();const a=this.module;if(!a)throw new t.HeicConverterError("decode_failed",e.Messages.DecoderFreedDuringDecode);let s;const c=o?t=>{try{o(e.clampPercent(t))}catch(e){s=s??e,a.__progressCb=null}}:null,u=i.buffer===a.HEAPU8.buffer?new Uint8Array(i):i;let f,d=0,l=0;try{if(d=a._malloc(u.byteLength),0===d)throw new t.HeicConverterError("decode_failed",e.Messages.DecodeInputAllocFailed(u.byteLength));a.HEAPU8.set(u,d);const r=a.__progressCb??null;a.__progressCb=c;try{l=a._heic_decode(d,u.byteLength)}finally{a.__progressCb=r}const o=a.HEAPU8;if(0===l)throw new TypeError("heic_decode returned a null result");const s=new DataView(o.buffer,l,36),h=s.getInt32(0,!0);if(0===h){const r=s.getUint32(28,!0),a=s.getUint32(32,!0),c=0!==r?(new TextDecoder).decode(o.subarray(r,r+a)):"";throw new t.HeicConverterError("decode_failed",c?e.Messages.DecodeFailedWithDetail(function(e){const t=e.replace(n," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(c),i.byteLength):e.Messages.DecodeFailed(i.byteLength))}const w=s.getInt32(4,!0),g=s.getInt32(8,!0),p=g>=1&&g<=8?g:1,v=s.getUint32(12,!0),y=s.getUint32(16,!0),m=4*h,_=new Uint8ClampedArray(m*w);if(y===m)_.set(o.subarray(v,v+m*w));else for(let e=0;e<w;e++)_.set(o.subarray(v+e*y,v+e*y+m),e*m);f={width:h,height:w,data:_},p>1&&(f.orientation=p);const b=s.getUint32(20,!0),C=s.getUint32(24,!0);0!==b&&C>=14&&(f.exif=o.slice(b,b+C))}catch(n){if(n instanceof t.HeicConverterError)throw n;throw r.add(this),new t.HeicConverterError("decode_failed",e.Messages.DecodeFaulted(i.byteLength),{cause:n})}finally{a.__progressCb=null;try{0!==l&&a._heic_result_free(l),0!==d&&a._free(d)}catch{}}if(void 0!==s)throw e.progressCallbackError(s);return f}free(){this.initGeneration+=1,this.module=null,r.delete(this),this.initPromise=null}},o=16384;function a(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new t.HeicConverterError("unsupported_environment",e.Messages.CanvasUnsupported)}var s=null,c=0;function u(){if(null===s){if(Date.now()<c)return Promise.resolve(void 0);const e=async function(){let e;try{e=w(1,1)}catch{return}const t=h(e,"image/avif");let r;const n=new Promise(e=>{r=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,n]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==r&&clearTimeout(r),g(e)}}().catch(()=>{});s=e,e.then(t=>{void 0===t&&s===e&&(s=null,c=Date.now()+1e4)})}return s}async function f(r){if(e.validateFormat(r),"avif"===String(r).toLowerCase()&&!1===await u())throw new t.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"))}function d(r,n){if(!Number.isFinite(r)||!Number.isFinite(n)||r>o||n>o)throw new t.HeicConverterError("invalid_resize",e.Messages.TargetSizeTooLarge(r,n,o))}async function l(r){try{const e=await r.arrayBuffer(),t=new Uint8Array(e);let n="";const i=32768;for(let e=0;e<t.length;e+=i)n+=String.fromCharCode(...t.subarray(e,e+i));const o=btoa(n);return`data:${r.type};base64,${o}`}catch(r){throw new t.HeicConverterError("render_encode_failed",e.Messages.BlobToBase64FailedWithCause(r instanceof Error?r.message:String(r)),{cause:r})}}function h(r,n,i){return"convertToBlob"in r?r.convertToBlob({type:n,quality:i}):new Promise((o,a)=>{r.toBlob(r=>{r?o(r):a(new t.HeicConverterError("render_encode_failed",e.Messages.CanvasToBlobFailed(n)))},n,i)})}function w(r,n){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(r,n);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=r,e.height=n,e}throw new t.HeicConverterError("unsupported_environment",e.Messages.CanvasUnsupported)}function g(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function p(e,t,r,n){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,r,n),0,0);else{const i=e.createImageData(r,n);i.data.set(t),e.putImageData(i,0,0)}}var v=!1;async function y(t,r,n,i,o){const a=r.exif;if(!n||!a||0===a.length)return t;const s=await import("./exif-H2Q7BO7Y.js").catch(()=>null);if(!s)return v||(v=!0,console.warn(e.Messages.ExifChunkLoadWarning)),t;const{injectExifIntoJpeg:c,injectExifIntoPng:u,normalizeOrientationTag:f}=s,d=o?f(a):a,l=new Uint8Array(await t.arrayBuffer()),h="jpeg"===i?c(l,d):u(l,d);return h===l?t:new Blob([h.buffer],{type:t.type})}function m(){return import("./worker-4HVYKWRG.js").catch(r=>{const n=r instanceof Error?r.message:String(r);throw new t.HeicConverterError("worker_load_failed",e.Messages.WorkerChunkLoadFailed(n),{cause:r})})}function _(e){return!0===e?.nativeDecode&&!0!==e?.preserveExif&&!1!==e?.applyOrientation}var b=!1;async function C(r,n){const o=n?.to??"jpeg";e.validateConvertOptions(n),a(),await f(o);const s=n?.signal;e.throwIfAborted(s);const c=n,v=await async function(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if("undefined"!=typeof Blob&&r instanceof Blob)return new Uint8Array(await r.arrayBuffer());if(null!==r&&"object"==typeof r&&"function"==typeof r.arrayBuffer){const e=await r.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new t.HeicConverterError("invalid_input",e.Messages.UnsupportedInputType(Object.prototype.toString.call(r)))}(r);let m,C;e.throwIfAborted(s);let E,I=!1;if(n?.decoder)m=n.decoder,C=!1;else if(_(n)){try{E=await(import("./native-JFFONPCS.js"))}catch(t){M=t instanceof Error?t.message:String(t),b||(b=!0,console.warn(e.Messages.NativeChunkLoadWarning(M)))}void 0===E||E.isNativeHeicRefused()?m=new i:(m=new E.NativeHeicDecoder,I=!0),C=!0}else m=new i,C=!0;var M;let H=!1;const A=()=>{if(C&&!H){H=!0;try{m.free()}catch{}}};try{const r=e.progressGateFor(n?.onProgress),a=async n=>{try{await n.initialize()}catch(r){throw new t.HeicConverterError("decoder_init_failed",e.Messages.DecoderInitFailed(r instanceof Error?r.message:String(r)),{cause:r})}return e.throwIfAborted(s),n.decode(v,r?r.report:void 0)};let f;try{f=await a(m)}catch(r){if(!I)throw r;if(r instanceof t.HeicConverterError&&"aborted"===r.code)throw r;r instanceof t.HeicConverterError&&"decoder_init_failed"===r.code&&E.markNativeHeicRefused(),e.throwIfAborted(s),A(),m=new i,H=!1,I=!1,f=await a(m)}A(),e.throwIfAborted(s);const _=void 0!==n?.quality?n.quality:e.DEFAULT_QUALITY;let b;try{b=await async function(r,n,i,o,a=!0,s,c=!1){e.validateFormat(n),e.validateCrop(s);const f=n.toLowerCase();if("avif"===f&&!1===await u())throw new t.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"));const{width:v,height:m,data:_}=r;if(!Number.isInteger(v)||v<=0||!Number.isInteger(m)||m<=0)throw new t.HeicConverterError("render_encode_failed",e.Messages.InvalidDimensions(v,m));const b=v*m*4;if(_.length!==b)throw new t.HeicConverterError("render_encode_failed",e.Messages.DataLengthMismatch(b,v,m,_.length));const C=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(r.orientation,a),E=!(void 0!==r.orientation&&r.orientation>=2&&r.orientation<=8)||a,I=function(e,t,r){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,r];case 4:return[1,0,0,-1,0,r];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,r,0];case 7:return[0,-1,-1,0,r,t];case 8:return[0,-1,1,0,0,t];default:return null}}(C,v,m),M=C>=5,H=M?m:v,A=M?v:m,U=s?.x??0,P=s?.y??0,F=s?s.width:H,x=s?s.height:A;if(s&&(U+F>H||P+x>A))throw new t.HeicConverterError("invalid_crop",e.Messages.CropOutOfBounds(U,P,F,x,H,A));const O=function(t,r,n){if(e.validateResize(n),!n)return{width:t,height:r};const{maxWidth:i,maxHeight:o,scale:a}=n;if(void 0!==a){const e=Math.max(1,Math.round(t*a)),n=Math.max(1,Math.round(r*a));return d(e,n),{width:e,height:n}}if(void 0===i&&void 0===o)return{width:t,height:r};const s=Math.min(void 0!==i?i/t:Number.POSITIVE_INFINITY,void 0!==o?o/r:Number.POSITIVE_INFINITY);if(s>=1)return{width:t,height:r};const c=Math.min(Math.max(1,Math.round(t*s)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),u=Math.min(Math.max(1,Math.round(r*s)),void 0!==o?Math.floor(o):Number.POSITIVE_INFINITY);return d(c,u),{width:c,height:u}}(F,x,o),T=O.width!==F||O.height!==x,D=null!==I||void 0!==s,B=w(O.width,O.height),L=B.getContext("2d");if(!L)throw new t.HeicConverterError("render_encode_failed",e.Messages.ContextUnavailable);if(D||T){const r=w(v,m),n=r.getContext("2d");if(!n)throw new t.HeicConverterError("render_encode_failed",e.Messages.ContextUnavailable);if(p(n,_,v,m),D){const e=O.width/F,t=O.height/x,n=I?I[0]:1,i=I?I[1]:0,o=I?I[2]:0,a=I?I[3]:1,s=I?I[4]:0,c=I?I[5]:0;L.setTransform(n*e,i*t,o*e,a*t,e*(s-U),t*(c-P)),L.drawImage(r,0,0)}else L.drawImage(r,0,0,O.width,O.height);g(r)}else p(L,_,v,m);if("png"===f){const e=await h(B,"image/png");return g(B),y(e,r,c,"png",E)}if("jpeg"===f||"jpg"===f){const e=await h(B,"image/jpeg",i);return g(B),y(e,r,c,"jpeg",E)}if("webp"===f){const e=await h(B,"image/webp",i);return g(B),e}if("avif"===f){const r=await h(B,"image/avif",i);if(g(B),"image/avif"!==r.type)throw new t.HeicConverterError("format_unsupported",e.Messages.FormatUnsupported("avif"));return r}if("svg"===f){const e=await h(B,"image/png");g(B);const t=await l(e),r=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${O.width} ${O.height}" width="${O.width}" height="${O.height}">\n <image width="${O.width}" height="${O.height}" href="`;return new Blob([r,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new t.HeicConverterError("invalid_format",e.Messages.UnsupportedFormat(String(n)))}(f,o,_,c,n?.applyOrientation??!0,n?.crop,n?.preserveExif??!1)}catch(r){if(r instanceof t.HeicConverterError)throw r;throw new t.HeicConverterError("render_encode_failed",e.Messages.RenderEncodeFailed(o,r instanceof Error?r.message:String(r)),{cause:r})}return e.throwIfAborted(s),r?.complete(),async function(e,t){return"dataUrl"===t?await l(e):"arrayBuffer"===t?await e.arrayBuffer():e}(b,n?.output??"blob")}finally{A()}}var E=class{idle=[];disposed=!1;acquire(){return this.idle.pop()??new i}release(e){if(this.disposed||function(e){return r.has(e)}(e))try{e.free()}catch{}else this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0}};Object.defineProperty(exports,"DEFAULT_QUALITY",{enumerable:!0,get:function(){return e.DEFAULT_QUALITY}}),Object.defineProperty(exports,"SUPPORTED_FORMATS",{enumerable:!0,get:function(){return e.SUPPORTED_FORMATS}}),Object.defineProperty(exports,"HeicConverterError",{enumerable:!0,get:function(){return t.HeicConverterError}}),exports.LibheifDecoder=i,exports.convertHeic=C,exports.convertHeicInWorker=function(e,t){return m().then(r=>r.convertHeicInWorker(e,t))},exports.convertMany=async function(r,n){if(!Array.isArray(r))throw new t.HeicConverterError("invalid_input",e.Messages.InputsMustBeArray);const i=n?.concurrency??4;e.validateConcurrency(i),e.validateConvertOptions(n),e.validateBatchOptions(n),a(),await f(n?.to??"jpeg");const{concurrency:o,onProgress:s,continueOnError:c,reuseDecoders:u,...d}=n??{},l=e.progressCallbackFor(s),h=!0!==u||void 0!==n?.decoder||_(n)?null:new E;try{return await e.runBoundedBatch(r,i,async(e,t)=>{const r=h?h.acquire():null;try{return await C(e,{...d,...r?{decoder:r}:{},onProgress:l?e=>l(t,e):void 0})}finally{r&&h.release(r)}},{continueOnError:!0===n?.continueOnError,signal:n?.signal})}finally{h?.dispose()}},exports.convertManyInWorker=function(e,t){return m().then(r=>r.convertManyInWorker(e,t))},exports.freeSharedDecoder=function(){};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Messages as e,validateConvertOptions as t,throwIfAborted as n,progressGateFor as i,DEFAULT_QUALITY as r,validateConcurrency as o,validateBatchOptions as a,progressCallbackFor as s,runBoundedBatch as c,clampPercent as u,progressCallbackError as f,validateFormat as d,validateCrop as l,validateResize as h}from"./chunk-BTAX2PFV.mjs";export{DEFAULT_QUALITY,SUPPORTED_FORMATS}from"./chunk-BTAX2PFV.mjs";import{HeicConverterError as w}from"./chunk-AROQBV5T.mjs";export{HeicConverterError}from"./chunk-AROQBV5T.mjs";var g=new WeakSet,p=/[\u0000-\u001f\u007f-\u009f]+/g,m=class{options;module=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const t=++this.initGeneration,n={};this.options?.moduleOverrides&&Object.assign(n,this.options.moduleOverrides),this.options?.locateFile&&(n.locateFile=this.options.locateFile),this.options?.wasmBinary&&(n.wasmBinary=this.options.wasmBinary);const i=import("./heic-decoder-IZMSMJZ7.mjs").then(({default:e})=>e(n)).then(n=>{if(t!==this.initGeneration)return null;const i=["function"==typeof n._heic_decode?null:"_heic_decode","function"==typeof n._heic_result_free?null:"_heic_result_free","function"==typeof n._malloc?null:"_malloc","function"==typeof n._free?null:"_free",n.HEAPU8 instanceof Uint8Array?null:"HEAPU8"].filter(e=>null!==e);if(i.length>0)throw new w("decoder_init_failed",e.GlueApiMissing(i.join(", ")));return this.module=n,n}).catch(e=>{throw this.initPromise===i&&(this.initPromise=null),e});this.initPromise=i}await this.initPromise}async decode(t,n){this.module||await this.initialize();const i=this.module;if(!i)throw new w("decode_failed",e.DecoderFreedDuringDecode);let r;const o=n?e=>{try{n(u(e))}catch(e){r=r??e,i.__progressCb=null}}:null,a=t.buffer===i.HEAPU8.buffer?new Uint8Array(t):t;let s,c=0,d=0;try{if(c=i._malloc(a.byteLength),0===c)throw new w("decode_failed",e.DecodeInputAllocFailed(a.byteLength));i.HEAPU8.set(a,c);const n=i.__progressCb??null;i.__progressCb=o;try{d=i._heic_decode(c,a.byteLength)}finally{i.__progressCb=n}const r=i.HEAPU8;if(0===d)throw new TypeError("heic_decode returned a null result");const u=new DataView(r.buffer,d,36),f=u.getInt32(0,!0);if(0===f){const n=u.getUint32(28,!0),i=u.getUint32(32,!0),o=0!==n?(new TextDecoder).decode(r.subarray(n,n+i)):"";throw new w("decode_failed",o?e.DecodeFailedWithDetail(function(e){const t=e.replace(p," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(o),t.byteLength):e.DecodeFailed(t.byteLength))}const l=u.getInt32(4,!0),h=u.getInt32(8,!0),g=h>=1&&h<=8?h:1,m=u.getUint32(12,!0),y=u.getUint32(16,!0),v=4*f,_=new Uint8ClampedArray(v*l);if(y===v)_.set(r.subarray(m,m+v*l));else for(let e=0;e<l;e++)_.set(r.subarray(m+e*y,m+e*y+v),e*v);s={width:f,height:l,data:_},g>1&&(s.orientation=g);const b=u.getUint32(20,!0),I=u.getUint32(24,!0);0!==b&&I>=14&&(s.exif=r.slice(b,b+I))}catch(n){if(n instanceof w)throw n;throw g.add(this),new w("decode_failed",e.DecodeFaulted(t.byteLength),{cause:n})}finally{i.__progressCb=null;try{0!==d&&i._heic_result_free(d),0!==c&&i._free(c)}catch{}}if(void 0!==r)throw f(r);return s}free(){this.initGeneration+=1,this.module=null,g.delete(this),this.initPromise=null}},y=16384;function v(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new w("unsupported_environment",e.CanvasUnsupported)}var _=null,b=0;function I(){if(null===_){if(Date.now()<b)return Promise.resolve(void 0);const e=async function(){let e;try{e=T(1,1)}catch{return}const t=E(e,"image/avif");let n;const i=new Promise(e=>{n=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,i]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==n&&clearTimeout(n),F(e)}}().catch(()=>{});_=e,e.then(t=>{void 0===t&&_===e&&(_=null,b=Date.now()+1e4)})}return _}async function U(t){if(d(t),"avif"===String(t).toLowerCase()&&!1===await I())throw new w("format_unsupported",e.FormatUnsupported("avif"))}function A(t,n){if(!Number.isFinite(t)||!Number.isFinite(n)||t>y||n>y)throw new w("invalid_resize",e.TargetSizeTooLarge(t,n,y))}async function B(t){try{const e=await t.arrayBuffer(),n=new Uint8Array(e);let i="";const r=32768;for(let e=0;e<n.length;e+=r)i+=String.fromCharCode(...n.subarray(e,e+r));const o=btoa(i);return`data:${t.type};base64,${o}`}catch(t){throw new w("render_encode_failed",e.BlobToBase64FailedWithCause(t instanceof Error?t.message:String(t)),{cause:t})}}function E(t,n,i){return"convertToBlob"in t?t.convertToBlob({type:n,quality:i}):new Promise((r,o)=>{t.toBlob(t=>{t?r(t):o(new w("render_encode_failed",e.CanvasToBlobFailed(n)))},n,i)})}function T(t,n){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,n);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=t,e.height=n,e}throw new w("unsupported_environment",e.CanvasUnsupported)}function F(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function P(e,t,n,i){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,n,i),0,0);else{const r=e.createImageData(n,i);r.data.set(t),e.putImageData(r,0,0)}}var x=!1;async function C(t,n,i,r,o){const a=n.exif;if(!i||!a||0===a.length)return t;const s=await import("./exif-MBEKII5G.mjs").catch(()=>null);if(!s)return x||(x=!0,console.warn(e.ExifChunkLoadWarning)),t;const{injectExifIntoJpeg:c,injectExifIntoPng:u,normalizeOrientationTag:f}=s,d=o?f(a):a,l=new Uint8Array(await t.arrayBuffer()),h="jpeg"===r?c(l,d):u(l,d);return h===l?t:new Blob([h.buffer],{type:t.type})}function D(){return import("./worker-VA6WQF25.mjs").catch(t=>{const n=t instanceof Error?t.message:String(t);throw new w("worker_load_failed",e.WorkerChunkLoadFailed(n),{cause:t})})}function O(e,t){return D().then(n=>n.convertHeicInWorker(e,t))}function j(e,t){return D().then(n=>n.convertManyInWorker(e,t))}function M(){}function N(e){return!0===e?.nativeDecode&&!0!==e?.preserveExif&&!1!==e?.applyOrientation}var S=!1;async function L(o,a){const s=a?.to??"jpeg";t(a),v(),await U(s);const c=a?.signal;n(c);const u=a,f=await async function(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if("undefined"!=typeof Blob&&t instanceof Blob)return new Uint8Array(await t.arrayBuffer());if(null!==t&&"object"==typeof t&&"function"==typeof t.arrayBuffer){const e=await t.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new w("invalid_input",e.UnsupportedInputType(Object.prototype.toString.call(t)))}(o);let g,p;n(c);let y,_=!1;if(a?.decoder)g=a.decoder,p=!1;else if(N(a)){try{y=await(import("./native-IGARV2W7.mjs"))}catch(t){b=t instanceof Error?t.message:String(t),S||(S=!0,console.warn(e.NativeChunkLoadWarning(b)))}void 0===y||y.isNativeHeicRefused()?g=new m:(g=new y.NativeHeicDecoder,_=!0),p=!0}else g=new m,p=!0;var b;let x=!1;const D=()=>{if(p&&!x){x=!0;try{g.free()}catch{}}};try{const t=i(a?.onProgress),o=async i=>{try{await i.initialize()}catch(t){throw new w("decoder_init_failed",e.DecoderInitFailed(t instanceof Error?t.message:String(t)),{cause:t})}return n(c),i.decode(f,t?t.report:void 0)};let p;try{p=await o(g)}catch(e){if(!_)throw e;if(e instanceof w&&"aborted"===e.code)throw e;e instanceof w&&"decoder_init_failed"===e.code&&y.markNativeHeicRefused(),n(c),D(),g=new m,x=!1,_=!1,p=await o(g)}D(),n(c);const v=void 0!==a?.quality?a.quality:r;let b;try{b=await async function(t,n,i,r,o=!0,a,s=!1){d(n),l(a);const c=n.toLowerCase();if("avif"===c&&!1===await I())throw new w("format_unsupported",e.FormatUnsupported("avif"));const{width:u,height:f,data:g}=t;if(!Number.isInteger(u)||u<=0||!Number.isInteger(f)||f<=0)throw new w("render_encode_failed",e.InvalidDimensions(u,f));const p=u*f*4;if(g.length!==p)throw new w("render_encode_failed",e.DataLengthMismatch(p,u,f,g.length));const m=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(t.orientation,o),y=!(void 0!==t.orientation&&t.orientation>=2&&t.orientation<=8)||o,v=function(e,t,n){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,n];case 4:return[1,0,0,-1,0,n];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,n,0];case 7:return[0,-1,-1,0,n,t];case 8:return[0,-1,1,0,0,t];default:return null}}(m,u,f),_=m>=5,b=_?f:u,U=_?u:f,x=a?.x??0,D=a?.y??0,O=a?a.width:b,j=a?a.height:U;if(a&&(x+O>b||D+j>U))throw new w("invalid_crop",e.CropOutOfBounds(x,D,O,j,b,U));const M=function(e,t,n){if(h(n),!n)return{width:e,height:t};const{maxWidth:i,maxHeight:r,scale:o}=n;if(void 0!==o){const n=Math.max(1,Math.round(e*o)),i=Math.max(1,Math.round(t*o));return A(n,i),{width:n,height:i}}if(void 0===i&&void 0===r)return{width:e,height:t};const a=Math.min(void 0!==i?i/e:Number.POSITIVE_INFINITY,void 0!==r?r/t:Number.POSITIVE_INFINITY);if(a>=1)return{width:e,height:t};const s=Math.min(Math.max(1,Math.round(e*a)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),c=Math.min(Math.max(1,Math.round(t*a)),void 0!==r?Math.floor(r):Number.POSITIVE_INFINITY);return A(s,c),{width:s,height:c}}(O,j,r),N=M.width!==O||M.height!==j,S=null!==v||void 0!==a,L=T(M.width,M.height),k=L.getContext("2d");if(!k)throw new w("render_encode_failed",e.ContextUnavailable);if(S||N){const t=T(u,f),n=t.getContext("2d");if(!n)throw new w("render_encode_failed",e.ContextUnavailable);if(P(n,g,u,f),S){const e=M.width/O,n=M.height/j,i=v?v[0]:1,r=v?v[1]:0,o=v?v[2]:0,a=v?v[3]:1,s=v?v[4]:0,c=v?v[5]:0;k.setTransform(i*e,r*n,o*e,a*n,e*(s-x),n*(c-D)),k.drawImage(t,0,0)}else k.drawImage(t,0,0,M.width,M.height);F(t)}else P(k,g,u,f);if("png"===c){const e=await E(L,"image/png");return F(L),C(e,t,s,"png",y)}if("jpeg"===c||"jpg"===c){const e=await E(L,"image/jpeg",i);return F(L),C(e,t,s,"jpeg",y)}if("webp"===c){const e=await E(L,"image/webp",i);return F(L),e}if("avif"===c){const t=await E(L,"image/avif",i);if(F(L),"image/avif"!==t.type)throw new w("format_unsupported",e.FormatUnsupported("avif"));return t}if("svg"===c){const e=await E(L,"image/png");F(L);const t=await B(e),n=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${M.width} ${M.height}" width="${M.width}" height="${M.height}">\n <image width="${M.width}" height="${M.height}" href="`;return new Blob([n,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new w("invalid_format",e.UnsupportedFormat(String(n)))}(p,s,v,u,a?.applyOrientation??!0,a?.crop,a?.preserveExif??!1)}catch(t){if(t instanceof w)throw t;throw new w("render_encode_failed",e.RenderEncodeFailed(s,t instanceof Error?t.message:String(t)),{cause:t})}return n(c),t?.complete(),async function(e,t){return"dataUrl"===t?await B(e):"arrayBuffer"===t?await e.arrayBuffer():e}(b,a?.output??"blob")}finally{D()}}var k=class{idle=[];disposed=!1;acquire(){return this.idle.pop()??new m}release(e){if(this.disposed||function(e){return g.has(e)}(e))try{e.free()}catch{}else this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0}};async function V(n,i){if(!Array.isArray(n))throw new w("invalid_input",e.InputsMustBeArray);const r=i?.concurrency??4;o(r),t(i),a(i),v(),await U(i?.to??"jpeg");const{concurrency:u,onProgress:f,continueOnError:d,reuseDecoders:l,...h}=i??{},g=s(f),p=!0!==l||void 0!==i?.decoder||N(i)?null:new k;try{return await c(n,r,async(e,t)=>{const n=p?p.acquire():null;try{return await L(e,{...h,...n?{decoder:n}:{},onProgress:g?e=>g(t,e):void 0})}finally{n&&p.release(n)}},{continueOnError:!0===i?.continueOnError,signal:i?.signal})}finally{p?.dispose()}}export{m as LibheifDecoder,L as convertHeic,O as convertHeicInWorker,V as convertMany,j as convertManyInWorker,M as freeSharedDecoder};
1
+ import{Messages as e,validateConvertOptions as t,throwIfAborted as n,progressGateFor as i,DEFAULT_QUALITY as r,validateConcurrency as o,validateBatchOptions as a,progressCallbackFor as s,runBoundedBatch as c,clampPercent as u,progressCallbackError as f,validateFormat as d,validateCrop as l,validateResize as h}from"./chunk-GR5XSYDQ.mjs";export{DEFAULT_QUALITY,SUPPORTED_FORMATS}from"./chunk-GR5XSYDQ.mjs";import{HeicConverterError as w}from"./chunk-AROQBV5T.mjs";export{HeicConverterError}from"./chunk-AROQBV5T.mjs";var g=new WeakSet,p=/[\u0000-\u001f\u007f-\u009f]+/g,m=class{options;module=null;initPromise=null;initGeneration=0;constructor(e){this.options=e}async initialize(){if(!this.initPromise){const t=++this.initGeneration,n={};this.options?.moduleOverrides&&Object.assign(n,this.options.moduleOverrides),this.options?.locateFile&&(n.locateFile=this.options.locateFile);const i=import("./heic-decoder-ZFSRP4EX.mjs").then(async({default:e})=>{if(this.options?.wasmBinary){const e=await WebAssembly.compile(this.options.wasmBinary);n.instantiateWasm=(t,n)=>n(new WebAssembly.Instance(e,t))}return e(n)}).then(n=>{if(t!==this.initGeneration)return null;const i=["function"==typeof n._heic_decode?null:"_heic_decode","function"==typeof n._heic_result_free?null:"_heic_result_free","function"==typeof n._malloc?null:"_malloc","function"==typeof n._free?null:"_free",n.HEAPU8 instanceof Uint8Array?null:"HEAPU8"].filter(e=>null!==e);if(i.length>0)throw new w("decoder_init_failed",e.GlueApiMissing(i.join(", ")));return this.module=n,n}).catch(e=>{throw this.initPromise===i&&(this.initPromise=null),e});this.initPromise=i}await this.initPromise}async decode(t,n){this.module||await this.initialize();const i=this.module;if(!i)throw new w("decode_failed",e.DecoderFreedDuringDecode);let r;const o=n?e=>{try{n(u(e))}catch(e){r=r??e,i.__progressCb=null}}:null,a=t.buffer===i.HEAPU8.buffer?new Uint8Array(t):t;let s,c=0,d=0;try{if(c=i._malloc(a.byteLength),0===c)throw new w("decode_failed",e.DecodeInputAllocFailed(a.byteLength));i.HEAPU8.set(a,c);const n=i.__progressCb??null;i.__progressCb=o;try{d=i._heic_decode(c,a.byteLength)}finally{i.__progressCb=n}const r=i.HEAPU8;if(0===d)throw new TypeError("heic_decode returned a null result");const u=new DataView(r.buffer,d,36),f=u.getInt32(0,!0);if(0===f){const n=u.getUint32(28,!0),i=u.getUint32(32,!0),o=0!==n?(new TextDecoder).decode(r.subarray(n,n+i)):"";throw new w("decode_failed",o?e.DecodeFailedWithDetail(function(e){const t=e.replace(p," ").trim();return t.length>200?`${t.slice(0,197)}...`:t}(o),t.byteLength):e.DecodeFailed(t.byteLength))}const l=u.getInt32(4,!0),h=u.getInt32(8,!0),g=h>=1&&h<=8?h:1,m=u.getUint32(12,!0),y=u.getUint32(16,!0),v=4*f,_=new Uint8ClampedArray(v*l);if(y===v)_.set(r.subarray(m,m+v*l));else for(let e=0;e<l;e++)_.set(r.subarray(m+e*y,m+e*y+v),e*v);s={width:f,height:l,data:_},g>1&&(s.orientation=g);const b=u.getUint32(20,!0),I=u.getUint32(24,!0);0!==b&&I>=14&&(s.exif=r.slice(b,b+I))}catch(n){if(n instanceof w)throw n;throw g.add(this),new w("decode_failed",e.DecodeFaulted(t.byteLength),{cause:n})}finally{i.__progressCb=null;try{0!==d&&i._heic_result_free(d),0!==c&&i._free(c)}catch{}}if(void 0!==r)throw f(r);return s}free(){this.initGeneration+=1,this.module=null,g.delete(this),this.initPromise=null}},y=16384;function v(){if("undefined"==typeof OffscreenCanvas&&"undefined"==typeof document)throw new w("unsupported_environment",e.CanvasUnsupported)}var _=null,b=0;function I(){if(null===_){if(Date.now()<b)return Promise.resolve(void 0);const e=async function(){let e;try{e=D(1,1)}catch{return}const t=B(e,"image/avif");let n;const i=new Promise(e=>{n=setTimeout(()=>e("timeout"),5e3)});try{const e=await Promise.race([t,i]);return"timeout"===e?void 0:"image/avif"===e.type&&e.size>0}finally{void 0!==n&&clearTimeout(n),P(e)}}().catch(()=>{});_=e,e.then(t=>{void 0===t&&_===e&&(_=null,b=Date.now()+1e4)})}return _}async function U(t){if(d(t),"avif"===String(t).toLowerCase()&&!1===await I())throw new w("format_unsupported",e.FormatUnsupported("avif"))}function A(t,n){if(!Number.isFinite(t)||!Number.isFinite(n)||t>y||n>y)throw new w("invalid_resize",e.TargetSizeTooLarge(t,n,y))}async function E(t){try{const e=await t.arrayBuffer(),n=new Uint8Array(e);let i="";const r=32768;for(let e=0;e<n.length;e+=r)i+=String.fromCharCode(...n.subarray(e,e+r));const o=btoa(i);return`data:${t.type};base64,${o}`}catch(t){throw new w("render_encode_failed",e.BlobToBase64FailedWithCause(t instanceof Error?t.message:String(t)),{cause:t})}}function B(t,n,i){return"convertToBlob"in t?t.convertToBlob({type:n,quality:i}):new Promise((r,o)=>{t.toBlob(t=>{t?r(t):o(new w("render_encode_failed",e.CanvasToBlobFailed(n)))},n,i)})}function D(t,n){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(t,n);if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=t,e.height=n,e}throw new w("unsupported_environment",e.CanvasUnsupported)}function P(e){const t=e;"function"==typeof t.close?t.close():e.width=0}function T(e,t,n,i){if("undefined"!=typeof ImageData)e.putImageData(new ImageData(t,n,i),0,0);else{const r=e.createImageData(n,i);r.data.set(t),e.putImageData(r,0,0)}}var x=!1;async function C(t,n,i,r,o){const a=n.exif;if(!i||!a||0===a.length)return t;const s=await import("./exif-MBEKII5G.mjs").catch(()=>null);if(!s)return x||(x=!0,console.warn(e.ExifChunkLoadWarning)),t;const{injectExifIntoJpeg:c,injectExifIntoPng:u,normalizeOrientationTag:f}=s,d=o?f(a):a,l=new Uint8Array(await t.arrayBuffer()),h="jpeg"===r?c(l,d):u(l,d);return h===l?t:new Blob([h.buffer],{type:t.type})}function F(){return import("./worker-N6W3ASWN.mjs").catch(t=>{const n=t instanceof Error?t.message:String(t);throw new w("worker_load_failed",e.WorkerChunkLoadFailed(n),{cause:t})})}function O(e,t){return F().then(n=>n.convertHeicInWorker(e,t))}function N(e,t){return F().then(n=>n.convertManyInWorker(e,t))}function j(){}function S(e){return!0===e?.nativeDecode&&!0!==e?.preserveExif&&!1!==e?.applyOrientation}var M=!1;async function L(o,a){const s=a?.to??"jpeg";t(a),v(),await U(s);const c=a?.signal;n(c);const u=a,f=await async function(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if("undefined"!=typeof Blob&&t instanceof Blob)return new Uint8Array(await t.arrayBuffer());if(null!==t&&"object"==typeof t&&"function"==typeof t.arrayBuffer){const e=await t.arrayBuffer();if(e instanceof ArrayBuffer)return new Uint8Array(e)}if(ArrayBuffer.isView(t)){const e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}throw new w("invalid_input",e.UnsupportedInputType(Object.prototype.toString.call(t)))}(o);let g,p;n(c);let y,_=!1;if(a?.decoder)g=a.decoder,p=!1;else if(S(a)){try{y=await(import("./native-IGARV2W7.mjs"))}catch(t){b=t instanceof Error?t.message:String(t),M||(M=!0,console.warn(e.NativeChunkLoadWarning(b)))}void 0===y||y.isNativeHeicRefused()?g=new m:(g=new y.NativeHeicDecoder,_=!0),p=!0}else g=new m,p=!0;var b;let x=!1;const F=()=>{if(p&&!x){x=!0;try{g.free()}catch{}}};try{const t=i(a?.onProgress),o=async i=>{try{await i.initialize()}catch(t){throw new w("decoder_init_failed",e.DecoderInitFailed(t instanceof Error?t.message:String(t)),{cause:t})}return n(c),i.decode(f,t?t.report:void 0)};let p;try{p=await o(g)}catch(e){if(!_)throw e;if(e instanceof w&&"aborted"===e.code)throw e;e instanceof w&&"decoder_init_failed"===e.code&&y.markNativeHeicRefused(),n(c),F(),g=new m,x=!1,_=!1,p=await o(g)}F(),n(c);const v=void 0!==a?.quality?a.quality:r;let b;try{b=await async function(t,n,i,r,o=!0,a,s=!1){d(n),l(a);const c=n.toLowerCase();if("avif"===c&&!1===await I())throw new w("format_unsupported",e.FormatUnsupported("avif"));const{width:u,height:f,data:g}=t;if(!Number.isInteger(u)||u<=0||!Number.isInteger(f)||f<=0)throw new w("render_encode_failed",e.InvalidDimensions(u,f));const p=u*f*4;if(g.length!==p)throw new w("render_encode_failed",e.DataLengthMismatch(p,u,f,g.length));const m=function(e,t){return t&&"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=8?e:1}(t.orientation,o),y=!(void 0!==t.orientation&&t.orientation>=2&&t.orientation<=8)||o,v=function(e,t,n){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,n];case 4:return[1,0,0,-1,0,n];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,n,0];case 7:return[0,-1,-1,0,n,t];case 8:return[0,-1,1,0,0,t];default:return null}}(m,u,f),_=m>=5,b=_?f:u,U=_?u:f,x=a?.x??0,F=a?.y??0,O=a?a.width:b,N=a?a.height:U;if(a&&(x+O>b||F+N>U))throw new w("invalid_crop",e.CropOutOfBounds(x,F,O,N,b,U));const j=function(e,t,n){if(h(n),!n)return{width:e,height:t};const{maxWidth:i,maxHeight:r,scale:o}=n;if(void 0!==o){const n=Math.max(1,Math.round(e*o)),i=Math.max(1,Math.round(t*o));return A(n,i),{width:n,height:i}}if(void 0===i&&void 0===r)return{width:e,height:t};const a=Math.min(void 0!==i?i/e:Number.POSITIVE_INFINITY,void 0!==r?r/t:Number.POSITIVE_INFINITY);if(a>=1)return{width:e,height:t};const s=Math.min(Math.max(1,Math.round(e*a)),void 0!==i?Math.floor(i):Number.POSITIVE_INFINITY),c=Math.min(Math.max(1,Math.round(t*a)),void 0!==r?Math.floor(r):Number.POSITIVE_INFINITY);return A(s,c),{width:s,height:c}}(O,N,r),S=j.width!==O||j.height!==N,M=null!==v||void 0!==a,L=D(j.width,j.height),W=L.getContext("2d");if(!W)throw new w("render_encode_failed",e.ContextUnavailable);if(M||S){const t=D(u,f),n=t.getContext("2d");if(!n)throw new w("render_encode_failed",e.ContextUnavailable);if(T(n,g,u,f),M){const e=j.width/O,n=j.height/N,i=v?v[0]:1,r=v?v[1]:0,o=v?v[2]:0,a=v?v[3]:1,s=v?v[4]:0,c=v?v[5]:0;W.setTransform(i*e,r*n,o*e,a*n,e*(s-x),n*(c-F)),W.drawImage(t,0,0)}else W.drawImage(t,0,0,j.width,j.height);P(t)}else T(W,g,u,f);if("png"===c){const e=await B(L,"image/png");return P(L),C(e,t,s,"png",y)}if("jpeg"===c||"jpg"===c){const e=await B(L,"image/jpeg",i);return P(L),C(e,t,s,"jpeg",y)}if("webp"===c){const e=await B(L,"image/webp",i);return P(L),e}if("avif"===c){const t=await B(L,"image/avif",i);if(P(L),"image/avif"!==t.type)throw new w("format_unsupported",e.FormatUnsupported("avif"));return t}if("svg"===c){const e=await B(L,"image/png");P(L);const t=await E(e),n=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${j.width} ${j.height}" width="${j.width}" height="${j.height}">\n <image width="${j.width}" height="${j.height}" href="`;return new Blob([n,t,'" />\n</svg>'],{type:"image/svg+xml"})}throw new w("invalid_format",e.UnsupportedFormat(String(n)))}(p,s,v,u,a?.applyOrientation??!0,a?.crop,a?.preserveExif??!1)}catch(t){if(t instanceof w)throw t;throw new w("render_encode_failed",e.RenderEncodeFailed(s,t instanceof Error?t.message:String(t)),{cause:t})}return n(c),t?.complete(),async function(e,t){return"dataUrl"===t?await E(e):"arrayBuffer"===t?await e.arrayBuffer():e}(b,a?.output??"blob")}finally{F()}}var W=class{idle=[];disposed=!1;acquire(){return this.idle.pop()??new m}release(e){if(this.disposed||function(e){return g.has(e)}(e))try{e.free()}catch{}else this.idle.push(e)}dispose(){this.disposed=!0;for(const e of this.idle)try{e.free()}catch{}this.idle.length=0}};async function k(n,i){if(!Array.isArray(n))throw new w("invalid_input",e.InputsMustBeArray);const r=i?.concurrency??4;o(r),t(i),a(i),v(),await U(i?.to??"jpeg");const{concurrency:u,onProgress:f,continueOnError:d,reuseDecoders:l,...h}=i??{},g=s(f),p=!0!==l||void 0!==i?.decoder||S(i)?null:new W;try{return await c(n,r,async(e,t)=>{const n=p?p.acquire():null;try{return await L(e,{...h,...n?{decoder:n}:{},onProgress:g?e=>g(t,e):void 0})}finally{n&&p.release(n)}},{continueOnError:!0===i?.continueOnError,signal:i?.signal})}finally{p?.dispose()}}export{m as LibheifDecoder,L as convertHeic,O as convertHeicInWorker,k as convertMany,N as convertManyInWorker,j as freeSharedDecoder};
@@ -1 +1 @@
1
- "use strict";var e=require("./chunk-N2LCVW2Q.js"),i=16384,t=67108864,r=!1,n=!1;exports.MAX_NATIVE_DECODE_DIMENSION=i,exports.MAX_NATIVE_DECODE_PIXELS=t,exports.NativeHeicDecoder=class{async initialize(){if("function"!=typeof createImageBitmap||"undefined"==typeof OffscreenCanvas)throw new e.HeicConverterError("decoder_init_failed","Native HEIC decoding is unavailable in this environment.")}async decode(r){const n="undefined"!=typeof SharedArrayBuffer&&r.buffer instanceof SharedArrayBuffer?new Uint8Array(r):r,a=await createImageBitmap(new Blob([n],{type:"image/heic"}),{imageOrientation:"from-image"});try{if(a.width>i||a.height>i)throw new e.HeicConverterError("decode_failed",`Native HEIC decoding is limited to 16384px per side, got ${a.width}x${a.height}.`);if(a.width*a.height>t)throw new e.HeicConverterError("decode_failed",`Native HEIC decoding is limited to 64MP total, got ${a.width}x${a.height} (${a.width*a.height} pixels).`);const r=new OffscreenCanvas(a.width,a.height).getContext("2d",{willReadFrequently:!0});if(!r)throw new e.HeicConverterError("decode_failed","Could not acquire a 2D context for native HEIC pixel readback.");r.drawImage(a,0,0);const n=r.getImageData(0,0,a.width,a.height);return{width:n.width,height:n.height,data:n.data}}finally{a.close?.()}}free(){}},exports.__resetNativeHeicProbe=function(){r=!1,n=!1},exports.isNativeHeicRefused=function(){return r},exports.markNativeHeicRefused=function(){r=!0,n||(n=!0,console.warn("@keeratita/heic-converter: native HEIC decoding is unavailable in this environment — nativeDecode conversions will use the bundled decoder on this page."))};
1
+ var e=require("./chunk-N2LCVW2Q.js"),i=16384,t=67108864,r=!1,n=!1;exports.MAX_NATIVE_DECODE_DIMENSION=i,exports.MAX_NATIVE_DECODE_PIXELS=t,exports.NativeHeicDecoder=class{async initialize(){if("function"!=typeof createImageBitmap||"undefined"==typeof OffscreenCanvas)throw new e.HeicConverterError("decoder_init_failed","Native HEIC decoding is unavailable in this environment.")}async decode(r){const n="undefined"!=typeof SharedArrayBuffer&&r.buffer instanceof SharedArrayBuffer?new Uint8Array(r):r,a=await createImageBitmap(new Blob([n],{type:"image/heic"}),{imageOrientation:"from-image"});try{if(a.width>i||a.height>i)throw new e.HeicConverterError("decode_failed",`Native HEIC decoding is limited to 16384px per side, got ${a.width}x${a.height}.`);if(a.width*a.height>t)throw new e.HeicConverterError("decode_failed",`Native HEIC decoding is limited to 64MP total, got ${a.width}x${a.height} (${a.width*a.height} pixels).`);const r=new OffscreenCanvas(a.width,a.height).getContext("2d",{willReadFrequently:!0});if(!r)throw new e.HeicConverterError("decode_failed","Could not acquire a 2D context for native HEIC pixel readback.");r.drawImage(a,0,0);const n=r.getImageData(0,0,a.width,a.height);return{width:n.width,height:n.height,data:n.data}}finally{a.close?.()}}free(){}},exports.__resetNativeHeicProbe=function(){r=!1,n=!1},exports.isNativeHeicRefused=function(){return r},exports.markNativeHeicRefused=function(){r=!0,n||(n=!0,console.warn("@keeratita/heic-converter: native HEIC decoding is unavailable in this environment — nativeDecode conversions will use the bundled decoder on this page."))};