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