@squoosh-kit/qoi 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,683 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __returnValue = (v) => v;
3
+ function __exportSetter(name, newValue) {
4
+ this[name] = __returnValue.bind(null, newValue);
5
+ }
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true,
11
+ configurable: true,
12
+ set: __exportSetter.bind(all, name)
13
+ });
14
+ };
15
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
16
+
17
+ // ../runtime/src/env.ts
18
+ function isBun() {
19
+ return typeof Bun !== "undefined";
20
+ }
21
+
22
+ // ../runtime/src/worker-call.ts
23
+ async function callWorker(worker, type, payload, signal, transfer) {
24
+ return new Promise((resolve, reject) => {
25
+ const id = ++requestId;
26
+ if (signal?.aborted) {
27
+ reject(new DOMException("Aborted", "AbortError"));
28
+ return;
29
+ }
30
+ const handleMessage = (event) => {
31
+ const response = event.data;
32
+ if (response.id !== id)
33
+ return;
34
+ cleanup();
35
+ if (response.ok && response.data !== undefined) {
36
+ resolve(response.data);
37
+ } else {
38
+ reject(new Error(response.error || "Unknown worker error"));
39
+ }
40
+ };
41
+ const handleError = (error) => {
42
+ cleanup();
43
+ reject(new Error(`Worker error: ${error.message}`));
44
+ };
45
+ const handleAbort = () => {
46
+ cleanup();
47
+ reject(new DOMException("Aborted", "AbortError"));
48
+ };
49
+ const cleanup = () => {
50
+ worker.removeEventListener("message", handleMessage);
51
+ worker.removeEventListener("error", handleError);
52
+ signal?.removeEventListener("abort", handleAbort);
53
+ };
54
+ worker.addEventListener("message", handleMessage);
55
+ worker.addEventListener("error", handleError);
56
+ signal?.addEventListener("abort", handleAbort);
57
+ const request = { type, id, payload };
58
+ if (transfer && transfer.length > 0) {
59
+ worker.postMessage(request, transfer);
60
+ } else {
61
+ worker.postMessage(request);
62
+ }
63
+ });
64
+ }
65
+ var requestId = 0;
66
+
67
+ // ../runtime/src/worker-helper.ts
68
+ function createCodecWorker(workerFilename, options) {
69
+ const normalizedName = workerFilename.endsWith(".js") ? workerFilename : `${workerFilename}.js`;
70
+ const workerMap = {
71
+ "resize.worker.js": {
72
+ package: "@squoosh-kit/resize",
73
+ specifier: "resize.worker.js"
74
+ },
75
+ "webp.worker.js": {
76
+ package: "@squoosh-kit/webp",
77
+ specifier: "webp.worker.js"
78
+ },
79
+ "avif.worker.js": {
80
+ package: "@squoosh-kit/avif",
81
+ specifier: "avif.worker.js"
82
+ },
83
+ "mozjpeg.worker.js": {
84
+ package: "@squoosh-kit/mozjpeg",
85
+ specifier: "mozjpeg.worker.js"
86
+ },
87
+ "jxl.worker.js": {
88
+ package: "@squoosh-kit/jxl",
89
+ specifier: "jxl.worker.js"
90
+ },
91
+ "oxipng.worker.js": {
92
+ package: "@squoosh-kit/oxipng",
93
+ specifier: "oxipng.worker.js"
94
+ },
95
+ "png.worker.js": {
96
+ package: "@squoosh-kit/png",
97
+ specifier: "png.worker.js"
98
+ },
99
+ "imagequant.worker.js": {
100
+ package: "@squoosh-kit/imagequant",
101
+ specifier: "imagequant.worker.js"
102
+ },
103
+ "qoi.worker.js": {
104
+ package: "@squoosh-kit/qoi",
105
+ specifier: "qoi.worker.js"
106
+ },
107
+ "wp2.worker.js": {
108
+ package: "@squoosh-kit/wp2",
109
+ specifier: "wp2.worker.js"
110
+ },
111
+ "hqx.worker.js": {
112
+ package: "@squoosh-kit/hqx",
113
+ specifier: "hqx.worker.js"
114
+ },
115
+ "rotate.worker.js": {
116
+ package: "@squoosh-kit/rotate",
117
+ specifier: "rotate.worker.js"
118
+ },
119
+ "visdif.worker.js": {
120
+ package: "@squoosh-kit/visdif",
121
+ specifier: "visdif.worker.js"
122
+ }
123
+ };
124
+ const workerConfig = workerMap[normalizedName];
125
+ if (!workerConfig) {
126
+ throw new Error(`Unknown worker: ${normalizedName}. ` + `Supported workers: ${Object.keys(workerMap).join(", ")}`);
127
+ }
128
+ try {
129
+ if (typeof window !== "undefined") {
130
+ const packageName = workerConfig.package.split("/")[1];
131
+ const workerFile = normalizedName.replace(".js", ".browser.mjs");
132
+ console.log(`[worker-helper] In browser environment. Trying to create worker:`);
133
+ console.log(`[worker-helper] - Package Name: ${packageName}`);
134
+ console.log(`[worker-helper] - Worker File: ${workerFile}`);
135
+ if (options?.assetPath) {
136
+ let normalizedAssetPath = options.assetPath;
137
+ if (!normalizedAssetPath.startsWith("/")) {
138
+ normalizedAssetPath = "/" + normalizedAssetPath;
139
+ }
140
+ if (normalizedAssetPath.endsWith("/")) {
141
+ normalizedAssetPath = normalizedAssetPath.slice(0, -1);
142
+ }
143
+ const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;
144
+ const workerUrl = new URL(workerPath, window.location.origin).href;
145
+ console.log(`[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`);
146
+ try {
147
+ const worker = new Worker(workerUrl, { type: "module" });
148
+ console.log(`[worker-helper] Successfully created worker with assetPath: ${workerUrl}`);
149
+ return worker;
150
+ } catch (e) {
151
+ console.error(`[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`, e);
152
+ throw new Error(`Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
153
+ }
154
+ }
155
+ const pathStrategies = [
156
+ `../../${packageName}/dist/${workerFile}`,
157
+ `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,
158
+ `../../../${packageName}/dist/${workerFile}`
159
+ ];
160
+ let lastError = null;
161
+ for (const relPath of pathStrategies) {
162
+ console.log("relPath:", relPath);
163
+ console.log("import.meta.url:", import.meta.url);
164
+ try {
165
+ const workerUrl = new URL(relPath, import.meta.url);
166
+ console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`);
167
+ const worker = new Worker(workerUrl, {
168
+ type: "module"
169
+ });
170
+ console.log(`[worker-helper] Successfully created worker with URL: ${workerUrl.href}`);
171
+ return worker;
172
+ } catch (error) {
173
+ console.warn(`[worker-helper] Path strategy failed for ${relPath}:`, error);
174
+ lastError = error instanceof Error ? error : new Error(String(error));
175
+ }
176
+ }
177
+ if (lastError) {
178
+ console.error("[worker-helper] All path strategies failed.", lastError);
179
+ throw lastError;
180
+ }
181
+ throw new Error(`Could not resolve worker ${normalizedName} using any available path strategy`);
182
+ }
183
+ const platformExt = isBun() ? ".bun.js" : ".node.mjs";
184
+ const baseName = normalizedName.replace(".js", "");
185
+ const pkgName = workerConfig.package.split("/")[1];
186
+ const srcRelPath = `../../${pkgName}/src/${baseName}.ts`;
187
+ console.log("srcRelPath:", srcRelPath);
188
+ console.log("import.meta.url:", import.meta.url);
189
+ try {
190
+ return new Worker(new URL(srcRelPath, import.meta.url), {
191
+ type: "module"
192
+ });
193
+ } catch {
194
+ const distRelPath = `../../${pkgName}/dist/${baseName}.${platformExt.slice(1)}`;
195
+ console.log("distRelPath:", distRelPath);
196
+ console.log("import.meta.url:", import.meta.url);
197
+ try {
198
+ return new Worker(new URL(distRelPath, import.meta.url), {
199
+ type: "module"
200
+ });
201
+ } catch {
202
+ if (typeof import.meta.resolve === "function") {
203
+ try {
204
+ const resolved = import.meta.resolve(`${workerConfig.package}/${workerConfig.specifier}`);
205
+ console.log("resolved:", resolved);
206
+ return new Worker(resolved, { type: "module" });
207
+ } catch {}
208
+ }
209
+ }
210
+ }
211
+ throw new Error(`Failed to create worker from ${normalizedName}. ` + `Tried TypeScript source, dist output, and import.meta.resolve. ` + `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`);
212
+ } catch (error) {
213
+ const errorMessage = error instanceof Error ? error.message : String(error);
214
+ throw new Error(`Failed to create worker from ${normalizedName}: ${errorMessage}. ` + `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` + `If you're using Vite, ensure the worker files are not being optimized as dependencies.`, { cause: error });
215
+ }
216
+ }
217
+ function createReadyWorker(workerFilename, options, timeoutMs = 1e4) {
218
+ return new Promise((resolve, reject) => {
219
+ const timeout = setTimeout(() => {
220
+ reject(new Error(`Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`));
221
+ }, timeoutMs);
222
+ let worker;
223
+ try {
224
+ worker = createCodecWorker(workerFilename, options);
225
+ } catch (error) {
226
+ clearTimeout(timeout);
227
+ reject(error);
228
+ return;
229
+ }
230
+ const handleMessage = (event) => {
231
+ if (event.data?.type === "worker:ready") {
232
+ clearTimeout(timeout);
233
+ worker.removeEventListener("message", handleMessage);
234
+ worker.removeEventListener("error", handleError);
235
+ worker.removeEventListener("messageerror", handleMessageError);
236
+ resolve(worker);
237
+ }
238
+ };
239
+ const handleError = (event) => {
240
+ clearTimeout(timeout);
241
+ worker.removeEventListener("message", handleMessage);
242
+ worker.removeEventListener("error", handleError);
243
+ worker.removeEventListener("messageerror", handleMessageError);
244
+ reject(new Error(`Worker failed to start: ${event?.message || "Unknown error"}. Worker file: ${workerFilename}`));
245
+ };
246
+ const handleMessageError = () => {
247
+ clearTimeout(timeout);
248
+ worker.removeEventListener("message", handleMessage);
249
+ worker.removeEventListener("error", handleError);
250
+ worker.removeEventListener("messageerror", handleMessageError);
251
+ reject(new Error(`Worker message error during initialization. Worker file: ${workerFilename}`));
252
+ };
253
+ worker.addEventListener("message", handleMessage);
254
+ worker.addEventListener("error", handleError);
255
+ worker.addEventListener("messageerror", handleMessageError);
256
+ worker.postMessage({ type: "worker:ping" });
257
+ });
258
+ }
259
+ var init_worker_helper = () => {};
260
+
261
+ // ../runtime/src/wasm-loader.ts
262
+ async function loadWasmBinary(relativePath, baseUrlOverride) {
263
+ const baseUrl = baseUrlOverride ? typeof baseUrlOverride === "string" ? new URL(".", baseUrlOverride) : new URL(".", baseUrlOverride.href) : new URL(".", import.meta.url);
264
+ const fullUrl = new URL(relativePath, baseUrl);
265
+ console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);
266
+ console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);
267
+ console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);
268
+ try {
269
+ const response = await fetch(fullUrl.href);
270
+ console.log(`[WasmLoader] Fetch response status for ${fullUrl.href}: ${response.status}`);
271
+ if (!response.ok) {
272
+ const responseText = await response.text();
273
+ console.error(`[WasmLoader] Fetch response text (first 500 chars):`, responseText.substring(0, 500));
274
+ throw new Error(`Failed to fetch WASM module at ${fullUrl.href}: ${response.status} ${response.statusText}`);
275
+ }
276
+ const contentType = response.headers.get("content-type");
277
+ console.log(`[WasmLoader] Response Content-Type: ${contentType}`);
278
+ if (!contentType || !contentType.includes("application/wasm")) {
279
+ console.warn(`[WasmLoader] Warning: WASM module at ${fullUrl.href} served with incorrect MIME type: "${contentType}". Should be "application/wasm".`);
280
+ }
281
+ return await response.arrayBuffer();
282
+ } catch (error) {
283
+ console.error(`[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`, error);
284
+ throw error;
285
+ }
286
+ }
287
+
288
+ // ../runtime/src/validators.ts
289
+ function validateImageInput(image) {
290
+ if (!image || typeof image !== "object") {
291
+ throw new TypeError("image must be an object");
292
+ }
293
+ const imageObj = image;
294
+ if (!("data" in imageObj)) {
295
+ throw new TypeError("image.data is required");
296
+ }
297
+ const { data } = imageObj;
298
+ if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray)) {
299
+ throw new TypeError("image.data must be Uint8Array or Uint8ClampedArray");
300
+ }
301
+ if (!("width" in imageObj) || !("height" in imageObj)) {
302
+ throw new TypeError("image.width and image.height are required");
303
+ }
304
+ const { width, height } = imageObj;
305
+ if (typeof width !== "number" || !Number.isInteger(width) || width <= 0) {
306
+ throw new RangeError(`image.width must be a positive integer, got ${width}`);
307
+ }
308
+ if (typeof height !== "number" || !Number.isInteger(height) || height <= 0) {
309
+ throw new RangeError(`image.height must be a positive integer, got ${height}`);
310
+ }
311
+ const expectedSize = width * height * 4;
312
+ if (data.length < expectedSize) {
313
+ throw new RangeError(`image.data too small: ${data.length} bytes, expected at least ${expectedSize} bytes for ${width}x${height} RGBA image`);
314
+ }
315
+ }
316
+ // ../runtime/src/simd-detector.ts
317
+ var init_simd_detector = () => {};
318
+
319
+ // ../runtime/src/image-data-polyfill.ts
320
+ function polyfillImageData() {
321
+ if (typeof ImageData === "undefined") {
322
+ globalThis.ImageData = class {
323
+ data;
324
+ width;
325
+ height;
326
+ colorSpace = "srgb";
327
+ constructor(data, width, height) {
328
+ this.data = data;
329
+ this.width = width;
330
+ this.height = height;
331
+ }
332
+ };
333
+ }
334
+ }
335
+
336
+ // ../runtime/src/index.ts
337
+ var init_src = __esm(() => {
338
+ init_worker_helper();
339
+ init_simd_detector();
340
+ });
341
+
342
+ // src/qoi.worker.ts
343
+ var exports_qoi_worker = {};
344
+ __export(exports_qoi_worker, {
345
+ qoiEncodeClient: () => qoiEncodeClient,
346
+ qoiDecodeClient: () => qoiDecodeClient
347
+ });
348
+ async function loadQoiEncModule() {
349
+ if (cachedEncModule) {
350
+ return cachedEncModule;
351
+ }
352
+ const globalSelf = typeof self !== "undefined" ? self : globalThis;
353
+ if (!globalSelf.location) {
354
+ globalSelf.location = {
355
+ href: import.meta.url
356
+ };
357
+ }
358
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
359
+ globalThis.self = globalThis;
360
+ }
361
+ const modulePath = "qoi-enc/qoi_enc.js";
362
+ console.log("[QOI Worker] Loading encoder module.");
363
+ console.log(`[QOI Worker] Attempting to import encoder module from path: ${modulePath}`);
364
+ let moduleFactory;
365
+ const isSource = import.meta.url.includes("/src/");
366
+ const pathsToTry = isSource ? ["../wasm/" + modulePath, "./wasm/" + modulePath] : ["./wasm/" + modulePath, "../wasm/" + modulePath];
367
+ let lastError = null;
368
+ for (const importPath of pathsToTry) {
369
+ try {
370
+ moduleFactory = (await import(importPath)).default;
371
+ console.log(`[QOI Worker] Successfully loaded encoder module from: ${importPath}`);
372
+ break;
373
+ } catch (error) {
374
+ lastError = error instanceof Error ? error : new Error(String(error));
375
+ console.warn(`[QOI Worker] Failed to load encoder from ${importPath}, trying next path...`);
376
+ }
377
+ }
378
+ if (!moduleFactory) {
379
+ throw lastError || new Error("Could not load QOI encoder module from any path");
380
+ }
381
+ console.log("[QOI Worker] Encoder module factory loaded successfully.");
382
+ const wasmFile = "qoi-enc/qoi_enc.wasm";
383
+ const wasmPathsToTry = isSource ? ["../wasm/" + wasmFile, "./wasm/" + wasmFile] : ["./wasm/" + wasmFile, "../wasm/" + wasmFile];
384
+ console.log(`[QOI Worker] Preparing to load encoder WASM binary. Will try paths: ${wasmPathsToTry.join(", ")}`);
385
+ const workerBaseUrl = new URL(".", import.meta.url);
386
+ let wasmLastError = null;
387
+ for (const wasmPath of wasmPathsToTry) {
388
+ try {
389
+ console.log(`[QOI Worker] Calling loadWasmBinary with path: ${wasmPath}`);
390
+ const wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);
391
+ console.log(`[QOI Worker] Successfully fetched encoder WASM binary from ${wasmPath}. Size: ${wasmBinary.byteLength} bytes.`);
392
+ const globalSelf2 = typeof self !== "undefined" ? self : globalThis;
393
+ if (!globalSelf2.location) {
394
+ globalSelf2.location = {
395
+ href: import.meta.url
396
+ };
397
+ }
398
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
399
+ globalThis.self = globalThis;
400
+ }
401
+ cachedEncModule = await moduleFactory({
402
+ noInitialRun: true,
403
+ wasmBinary
404
+ });
405
+ console.log("[QOI Worker] QOI encoder module initialized successfully.");
406
+ return cachedEncModule;
407
+ } catch (err) {
408
+ wasmLastError = err instanceof Error ? err : new Error(String(err));
409
+ console.warn(`[QOI Worker] Failed to load encoder WASM from ${wasmPath}, trying next path...`);
410
+ }
411
+ }
412
+ throw wasmLastError || new Error("Could not load encoder WASM binary from any of the attempted paths");
413
+ }
414
+ async function loadQoiDecModule() {
415
+ if (cachedDecModule) {
416
+ return cachedDecModule;
417
+ }
418
+ const globalSelf = typeof self !== "undefined" ? self : globalThis;
419
+ if (!globalSelf.location) {
420
+ globalSelf.location = {
421
+ href: import.meta.url
422
+ };
423
+ }
424
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
425
+ globalThis.self = globalThis;
426
+ }
427
+ polyfillImageData();
428
+ const modulePath = "qoi-dec/qoi_dec.js";
429
+ console.log("[QOI Worker] Loading decoder module.");
430
+ console.log(`[QOI Worker] Attempting to import decoder module from path: ${modulePath}`);
431
+ let moduleFactory;
432
+ const isSource = import.meta.url.includes("/src/");
433
+ const pathsToTry = isSource ? ["../wasm/" + modulePath, "./wasm/" + modulePath] : ["./wasm/" + modulePath, "../wasm/" + modulePath];
434
+ let lastError = null;
435
+ for (const importPath of pathsToTry) {
436
+ try {
437
+ moduleFactory = (await import(importPath)).default;
438
+ console.log(`[QOI Worker] Successfully loaded decoder module from: ${importPath}`);
439
+ break;
440
+ } catch (error) {
441
+ lastError = error instanceof Error ? error : new Error(String(error));
442
+ console.warn(`[QOI Worker] Failed to load decoder from ${importPath}, trying next path...`);
443
+ }
444
+ }
445
+ if (!moduleFactory) {
446
+ throw lastError || new Error("Could not load QOI decoder module from any path");
447
+ }
448
+ console.log("[QOI Worker] Decoder module factory loaded successfully.");
449
+ const wasmFile = "qoi-dec/qoi_dec.wasm";
450
+ const wasmPathsToTry = isSource ? ["../wasm/" + wasmFile, "./wasm/" + wasmFile] : ["./wasm/" + wasmFile, "../wasm/" + wasmFile];
451
+ console.log(`[QOI Worker] Preparing to load decoder WASM binary. Will try paths: ${wasmPathsToTry.join(", ")}`);
452
+ const workerBaseUrl = new URL(".", import.meta.url);
453
+ let wasmLastError = null;
454
+ for (const wasmPath of wasmPathsToTry) {
455
+ try {
456
+ console.log(`[QOI Worker] Calling loadWasmBinary with path: ${wasmPath}`);
457
+ const wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);
458
+ console.log(`[QOI Worker] Successfully fetched decoder WASM binary from ${wasmPath}. Size: ${wasmBinary.byteLength} bytes.`);
459
+ const globalSelf2 = typeof self !== "undefined" ? self : globalThis;
460
+ if (!globalSelf2.location) {
461
+ globalSelf2.location = {
462
+ href: import.meta.url
463
+ };
464
+ }
465
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
466
+ globalThis.self = globalThis;
467
+ }
468
+ cachedDecModule = await moduleFactory({
469
+ noInitialRun: true,
470
+ wasmBinary
471
+ });
472
+ console.log("[QOI Worker] QOI decoder module initialized successfully.");
473
+ return cachedDecModule;
474
+ } catch (err) {
475
+ wasmLastError = err instanceof Error ? err : new Error(String(err));
476
+ console.warn(`[QOI Worker] Failed to load decoder WASM from ${wasmPath}, trying next path...`);
477
+ }
478
+ }
479
+ throw wasmLastError || new Error("Could not load decoder WASM binary from any of the attempted paths");
480
+ }
481
+ async function qoiEncodeClient(image, signal) {
482
+ validateImageInput(image);
483
+ if (signal?.aborted) {
484
+ throw new DOMException("Aborted", "AbortError");
485
+ }
486
+ const width = image.width;
487
+ const height = image.height;
488
+ const data = image.data;
489
+ if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {
490
+ throw new Error("Image data must be Uint8Array or Uint8ClampedArray");
491
+ }
492
+ const module = await loadQoiEncModule();
493
+ if (signal?.aborted) {
494
+ throw new DOMException("Aborted", "AbortError");
495
+ }
496
+ const dataBuffer = data instanceof Uint8ClampedArray ? new Uint8Array(data.buffer, data.byteOffset, data.length) : new Uint8Array(data.buffer, data.byteOffset, data.length);
497
+ const options = {};
498
+ const result = module.encode(dataBuffer, width, height, options);
499
+ if (signal?.aborted) {
500
+ throw new DOMException("Aborted", "AbortError");
501
+ }
502
+ if (!result) {
503
+ throw new Error("QOI encoding failed");
504
+ }
505
+ return result;
506
+ }
507
+ async function qoiDecodeClient(data, signal) {
508
+ if (signal?.aborted) {
509
+ throw new DOMException("Aborted", "AbortError");
510
+ }
511
+ const module = await loadQoiDecModule();
512
+ if (signal?.aborted) {
513
+ throw new DOMException("Aborted", "AbortError");
514
+ }
515
+ const result = module.decode(data);
516
+ if (signal?.aborted) {
517
+ throw new DOMException("Aborted", "AbortError");
518
+ }
519
+ if (!result) {
520
+ throw new Error("QOI decoding failed");
521
+ }
522
+ return result;
523
+ }
524
+ var cachedEncModule = null, cachedDecModule = null;
525
+ var init_qoi_worker = __esm(() => {
526
+ init_src();
527
+ if (typeof self !== "undefined") {
528
+ self.onmessage = async (event) => {
529
+ const data = event.data;
530
+ if (data?.type === "worker:ping") {
531
+ self.postMessage({ type: "worker:ready" });
532
+ return;
533
+ }
534
+ if (data?.type === "qoi:encode") {
535
+ const request2 = data;
536
+ const response2 = {
537
+ id: request2.id,
538
+ ok: false
539
+ };
540
+ try {
541
+ const { image } = request2.payload;
542
+ const result = await qoiEncodeClient(image);
543
+ response2.ok = true;
544
+ response2.data = result;
545
+ self.postMessage(response2);
546
+ } catch (error) {
547
+ response2.error = error instanceof Error ? error.message : String(error);
548
+ self.postMessage(response2);
549
+ }
550
+ return;
551
+ }
552
+ if (data?.type === "qoi:decode") {
553
+ const request2 = data;
554
+ const response2 = {
555
+ id: request2.id,
556
+ ok: false
557
+ };
558
+ try {
559
+ const result = await qoiDecodeClient(request2.payload.data);
560
+ response2.ok = true;
561
+ response2.data = result;
562
+ self.postMessage(response2);
563
+ } catch (error) {
564
+ response2.error = error instanceof Error ? error.message : String(error);
565
+ self.postMessage(response2);
566
+ }
567
+ return;
568
+ }
569
+ const request = data;
570
+ const response = {
571
+ id: request.id,
572
+ ok: false,
573
+ error: `Unknown message type: ${data?.type}`
574
+ };
575
+ self.postMessage(response);
576
+ };
577
+ }
578
+ });
579
+
580
+ // src/bridge.ts
581
+ init_src();
582
+
583
+ class QoiClientBridge {
584
+ async encode(image, signal) {
585
+ const module = await Promise.resolve().then(() => (init_qoi_worker(), exports_qoi_worker));
586
+ const qoiEncodeClient2 = module.qoiEncodeClient;
587
+ return qoiEncodeClient2(image, signal);
588
+ }
589
+ async decode(data, signal) {
590
+ const module = await Promise.resolve().then(() => (init_qoi_worker(), exports_qoi_worker));
591
+ const qoiDecodeClient2 = module.qoiDecodeClient;
592
+ return qoiDecodeClient2(data, signal);
593
+ }
594
+ async terminate() {}
595
+ }
596
+
597
+ class QoiWorkerBridge {
598
+ worker = null;
599
+ workerReady = null;
600
+ options;
601
+ constructor(options) {
602
+ console.log("[qoi/bridge] QoiWorkerBridge constructor called with options:", options);
603
+ this.options = options;
604
+ }
605
+ async getWorker() {
606
+ if (!this.workerReady) {
607
+ this.workerReady = this.createWorker();
608
+ }
609
+ return this.workerReady;
610
+ }
611
+ async createWorker() {
612
+ console.log("[qoi/bridge] createWorker called. Creating ready worker...");
613
+ this.worker = await createReadyWorker("qoi.worker.js", this.options);
614
+ console.log("[qoi/bridge] createWorker: Ready worker created successfully.");
615
+ return this.worker;
616
+ }
617
+ async encode(image, signal) {
618
+ const worker = await this.getWorker();
619
+ validateImageInput(image);
620
+ return callWorker(worker, "qoi:encode", { image }, signal);
621
+ }
622
+ async decode(data, signal) {
623
+ const worker = await this.getWorker();
624
+ return callWorker(worker, "qoi:decode", { data }, signal);
625
+ }
626
+ async terminate() {
627
+ if (this.worker) {
628
+ this.worker.terminate();
629
+ this.worker = null;
630
+ this.workerReady = null;
631
+ }
632
+ }
633
+ }
634
+ function createBridge(mode, options) {
635
+ console.log(`[qoi/bridge] createBridge called with mode: ${mode}`);
636
+ if (mode === "worker") {
637
+ return new QoiWorkerBridge(options);
638
+ }
639
+ return new QoiClientBridge;
640
+ }
641
+
642
+ // src/index.ts
643
+ var globalClientBridge = null;
644
+ async function encode(image, signal) {
645
+ if (!globalClientBridge) {
646
+ globalClientBridge = createBridge("worker");
647
+ }
648
+ return globalClientBridge.encode(image, signal);
649
+ }
650
+ async function decode(data, signal) {
651
+ if (!globalClientBridge) {
652
+ globalClientBridge = createBridge("worker");
653
+ }
654
+ return globalClientBridge.decode(data, signal);
655
+ }
656
+ function createQoiEncoder(mode = "worker", options) {
657
+ const bridge = createBridge(mode, options);
658
+ return Object.assign((image, signal) => {
659
+ return bridge.encode(image, signal);
660
+ }, {
661
+ terminate: async () => {
662
+ await bridge.terminate();
663
+ }
664
+ });
665
+ }
666
+ function createQoiDecoder(mode = "worker", options) {
667
+ const bridge = createBridge(mode, options);
668
+ return Object.assign((data, signal) => {
669
+ return bridge.decode(data, signal);
670
+ }, {
671
+ terminate: async () => {
672
+ await bridge.terminate();
673
+ }
674
+ });
675
+ }
676
+ export {
677
+ encode,
678
+ decode,
679
+ createQoiEncoder,
680
+ createQoiDecoder
681
+ };
682
+
683
+ //# debugId=FC3BF36956E6E24B64756E2164756E21