@squoosh-kit/wp2 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.
Files changed (45) hide show
  1. package/dist/bridge.d.ts +16 -0
  2. package/dist/bridge.d.ts.map +1 -0
  3. package/dist/index.browser.mjs +813 -0
  4. package/dist/index.browser.mjs.map +20 -0
  5. package/dist/index.bun.js +814 -0
  6. package/dist/index.bun.js.map +20 -0
  7. package/dist/index.d.ts +86 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.node.cjs +841 -0
  10. package/dist/index.node.cjs.map +20 -0
  11. package/dist/index.node.mjs +813 -0
  12. package/dist/index.node.mjs.map +20 -0
  13. package/dist/types.d.ts +4 -0
  14. package/dist/types.d.ts.map +1 -0
  15. package/dist/validators.d.ts +2 -0
  16. package/dist/validators.d.ts.map +1 -0
  17. package/dist/wasm/wp2-dec/wp2_dec.d.ts +7 -0
  18. package/dist/wasm/wp2-dec/wp2_dec.js +16 -0
  19. package/dist/wasm/wp2-dec/wp2_dec.wasm +0 -0
  20. package/dist/wasm/wp2-dec/wp2_node_dec.js +16 -0
  21. package/dist/wasm/wp2-dec/wp2_node_dec.wasm +0 -0
  22. package/dist/wasm/wp2-enc/wp2_enc.d.ts +38 -0
  23. package/dist/wasm/wp2-enc/wp2_enc.js +16 -0
  24. package/dist/wasm/wp2-enc/wp2_enc.wasm +0 -0
  25. package/dist/wasm/wp2-enc/wp2_enc_mt.d.ts +1 -0
  26. package/dist/wasm/wp2-enc/wp2_enc_mt.js +16 -0
  27. package/dist/wasm/wp2-enc/wp2_enc_mt.wasm +0 -0
  28. package/dist/wasm/wp2-enc/wp2_enc_mt.worker.js +1 -0
  29. package/dist/wasm/wp2-enc/wp2_enc_mt_simd.d.ts +1 -0
  30. package/dist/wasm/wp2-enc/wp2_enc_mt_simd.js +16 -0
  31. package/dist/wasm/wp2-enc/wp2_enc_mt_simd.wasm +0 -0
  32. package/dist/wasm/wp2-enc/wp2_enc_mt_simd.worker.js +1 -0
  33. package/dist/wasm/wp2-enc/wp2_node_enc.js +16 -0
  34. package/dist/wasm/wp2-enc/wp2_node_enc.wasm +0 -0
  35. package/dist/wp2.worker.browser.mjs +701 -0
  36. package/dist/wp2.worker.browser.mjs.map +18 -0
  37. package/dist/wp2.worker.bun.js +702 -0
  38. package/dist/wp2.worker.bun.js.map +18 -0
  39. package/dist/wp2.worker.d.ts +14 -0
  40. package/dist/wp2.worker.d.ts.map +1 -0
  41. package/dist/wp2.worker.node.cjs +720 -0
  42. package/dist/wp2.worker.node.cjs.map +18 -0
  43. package/dist/wp2.worker.node.mjs +701 -0
  44. package/dist/wp2.worker.node.mjs.map +18 -0
  45. package/package.json +52 -0
@@ -0,0 +1,813 @@
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/validators.ts
343
+ function validateWp2Options(options) {
344
+ if (options === undefined) {
345
+ return;
346
+ }
347
+ if (typeof options !== "object" || options === null) {
348
+ throw new TypeError("options must be an object or undefined");
349
+ }
350
+ const opts = options;
351
+ if ("quality" in opts && opts.quality !== undefined) {
352
+ const quality = opts.quality;
353
+ if (Number.isNaN(quality)) {
354
+ throw new RangeError("quality must be a valid number in the range 0-100, got NaN");
355
+ }
356
+ if (typeof quality !== "number") {
357
+ throw new TypeError("quality must be a number");
358
+ }
359
+ if (!Number.isFinite(quality) || !Number.isInteger(quality)) {
360
+ throw new RangeError("quality must be an integer in the range 0-100, got floating point");
361
+ }
362
+ if (quality < 0 || quality > 100) {
363
+ throw new RangeError(`quality must be in the range 0-100, got ${quality}`);
364
+ }
365
+ }
366
+ if ("alpha_quality" in opts && opts.alpha_quality !== undefined) {
367
+ const alphaQuality = opts.alpha_quality;
368
+ if (Number.isNaN(alphaQuality)) {
369
+ throw new RangeError("alpha_quality must be a valid number in the range 0-100, got NaN");
370
+ }
371
+ if (typeof alphaQuality !== "number") {
372
+ throw new TypeError("alpha_quality must be a number");
373
+ }
374
+ if (!Number.isFinite(alphaQuality) || !Number.isInteger(alphaQuality)) {
375
+ throw new RangeError("alpha_quality must be an integer in the range 0-100, got floating point");
376
+ }
377
+ if (alphaQuality < 0 || alphaQuality > 100) {
378
+ throw new RangeError(`alpha_quality must be in the range 0-100, got ${alphaQuality}`);
379
+ }
380
+ }
381
+ if ("effort" in opts && opts.effort !== undefined) {
382
+ const effort = opts.effort;
383
+ if (Number.isNaN(effort)) {
384
+ throw new RangeError("effort must be a valid number in the range 0-9, got NaN");
385
+ }
386
+ if (typeof effort !== "number") {
387
+ throw new TypeError("effort must be a number");
388
+ }
389
+ if (!Number.isFinite(effort) || !Number.isInteger(effort)) {
390
+ throw new RangeError("effort must be an integer in the range 0-9, got floating point");
391
+ }
392
+ if (effort < 0 || effort > 9) {
393
+ throw new RangeError(`effort must be in the range 0-9, got ${effort}`);
394
+ }
395
+ }
396
+ if ("pass" in opts && opts.pass !== undefined) {
397
+ const pass = opts.pass;
398
+ if (Number.isNaN(pass)) {
399
+ throw new RangeError("pass must be a valid number in the range 1-10, got NaN");
400
+ }
401
+ if (typeof pass !== "number") {
402
+ throw new TypeError("pass must be a number");
403
+ }
404
+ if (!Number.isFinite(pass) || !Number.isInteger(pass)) {
405
+ throw new RangeError("pass must be an integer in the range 1-10, got floating point");
406
+ }
407
+ if (pass < 1 || pass > 10) {
408
+ throw new RangeError(`pass must be in the range 1-10, got ${pass}`);
409
+ }
410
+ }
411
+ if ("sns" in opts && opts.sns !== undefined) {
412
+ const sns = opts.sns;
413
+ if (Number.isNaN(sns)) {
414
+ throw new RangeError("sns must be a valid number in the range 0-100, got NaN");
415
+ }
416
+ if (typeof sns !== "number") {
417
+ throw new TypeError("sns must be a number");
418
+ }
419
+ if (!Number.isFinite(sns) || !Number.isInteger(sns)) {
420
+ throw new RangeError("sns must be an integer in the range 0-100, got floating point");
421
+ }
422
+ if (sns < 0 || sns > 100) {
423
+ throw new RangeError(`sns must be in the range 0-100, got ${sns}`);
424
+ }
425
+ }
426
+ }
427
+
428
+ // src/wp2.worker.ts
429
+ var exports_wp2_worker = {};
430
+ __export(exports_wp2_worker, {
431
+ wp2EncodeClient: () => wp2EncodeClient,
432
+ wp2DecodeClient: () => wp2DecodeClient
433
+ });
434
+ async function loadWp2Module() {
435
+ if (cachedModule) {
436
+ return cachedModule;
437
+ }
438
+ const isNodeOrBun = typeof process !== "undefined" && (process.versions?.bun !== undefined || process.versions?.node !== undefined);
439
+ const modulePath = isNodeOrBun ? "wp2-enc/wp2_node_enc.js" : "wp2-enc/wp2_enc.js";
440
+ try {
441
+ console.log("[WP2 Worker] Initializing. Environment:", isNodeOrBun ? "Node/Bun" : "Browser");
442
+ console.log(`[WP2 Worker] Attempting to import module from path: ${modulePath}`);
443
+ const globalSelf = typeof self !== "undefined" ? self : globalThis;
444
+ if (!globalSelf.location) {
445
+ globalSelf.location = {
446
+ href: import.meta.url
447
+ };
448
+ }
449
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
450
+ globalThis.self = globalThis;
451
+ }
452
+ let moduleFactory;
453
+ const isSource = import.meta.url.includes("/src/");
454
+ const pathsToTry = isSource ? ["../wasm/" + modulePath, "./wasm/" + modulePath] : ["./wasm/" + modulePath, "../wasm/" + modulePath];
455
+ let lastError = null;
456
+ for (const importPath of pathsToTry) {
457
+ try {
458
+ moduleFactory = (await import(importPath)).default;
459
+ console.log(`[WP2 Worker] Successfully loaded module from: ${importPath}`);
460
+ break;
461
+ } catch (error) {
462
+ lastError = error instanceof Error ? error : new Error(String(error));
463
+ console.warn(`[WP2 Worker] Failed to load from ${importPath}, trying next path...`);
464
+ }
465
+ }
466
+ if (!moduleFactory) {
467
+ throw lastError || new Error("Could not load WP2 module from any path");
468
+ }
469
+ console.log("[WP2 Worker] Module factory loaded successfully.");
470
+ const wasmFile = isNodeOrBun ? "wp2_node_enc.wasm" : "wp2_enc.wasm";
471
+ const wasmPathsToTry = isSource ? [`../wasm/wp2-enc/${wasmFile}`, `./wasm/wp2-enc/${wasmFile}`] : [`./wasm/wp2-enc/${wasmFile}`, `../wasm/wp2-enc/${wasmFile}`];
472
+ console.log(`[WP2 Worker] Preparing to load WASM binary. Will try paths: ${wasmPathsToTry.join(", ")}`);
473
+ const initModuleWithBinary = async (moduleFactory2, wasmPaths) => {
474
+ const workerBaseUrl = new URL(".", import.meta.url);
475
+ let lastError2 = null;
476
+ for (const wasmPath of wasmPaths) {
477
+ try {
478
+ console.log(`[WP2 Worker] Calling loadWasmBinary with path: ${wasmPath}`);
479
+ const wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);
480
+ console.log(`[WP2 Worker] Successfully fetched WASM binary from ${wasmPath}. Size: ${wasmBinary.byteLength} bytes.`);
481
+ const globalSelf2 = typeof self !== "undefined" ? self : globalThis;
482
+ if (!globalSelf2.location) {
483
+ globalSelf2.location = {
484
+ href: import.meta.url
485
+ };
486
+ }
487
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
488
+ globalThis.self = globalThis;
489
+ }
490
+ return await moduleFactory2({
491
+ noInitialRun: true,
492
+ wasmBinary
493
+ });
494
+ } catch (err) {
495
+ lastError2 = err instanceof Error ? err : new Error(String(err));
496
+ console.warn(`[WP2 Worker] Failed to load WASM from ${wasmPath}, trying next path...`);
497
+ }
498
+ }
499
+ throw lastError2 || new Error("Could not load WASM binary from any of the attempted paths");
500
+ };
501
+ cachedModule = await initModuleWithBinary(moduleFactory, wasmPathsToTry);
502
+ console.log("[WP2 Worker] WP2 module initialized successfully.");
503
+ return cachedModule;
504
+ } catch (err) {
505
+ console.error(`[WP2 Worker] CRITICAL: Failed to load WP2 module from path: ${modulePath}`, err);
506
+ throw err;
507
+ }
508
+ }
509
+ function createEncodeOptions(options) {
510
+ return {
511
+ quality: options?.quality ?? 75,
512
+ alpha_quality: options?.alpha_quality ?? 75,
513
+ effort: options?.effort ?? 5,
514
+ pass: options?.pass ?? 1,
515
+ sns: options?.sns ?? 50,
516
+ uv_mode: options?.uv_mode ?? UVModeAuto,
517
+ csp_type: options?.csp_type ?? kYCoCg,
518
+ error_diffusion: options?.error_diffusion ?? 0,
519
+ use_random_matrix: options?.use_random_matrix ?? false
520
+ };
521
+ }
522
+ async function wp2EncodeClient(image, options, signal) {
523
+ validateImageInput(image);
524
+ validateWp2Options(options);
525
+ if (signal?.aborted) {
526
+ throw new DOMException("Aborted", "AbortError");
527
+ }
528
+ const width = image.width;
529
+ const height = image.height;
530
+ const data = image.data;
531
+ if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {
532
+ throw new Error("Image data must be Uint8Array or Uint8ClampedArray");
533
+ }
534
+ const module = await loadWp2Module();
535
+ if (signal?.aborted) {
536
+ throw new DOMException("Aborted", "AbortError");
537
+ }
538
+ const encodeOptions = createEncodeOptions(options);
539
+ const dataArray = data instanceof Uint8ClampedArray ? new Uint8Array(data.buffer, data.byteOffset, data.length) : new Uint8Array(data.buffer, data.byteOffset, data.length);
540
+ const result = module.encode(dataArray, width, height, encodeOptions);
541
+ if (signal?.aborted) {
542
+ throw new DOMException("Aborted", "AbortError");
543
+ }
544
+ if (!result) {
545
+ throw new Error("WP2 encoding failed");
546
+ }
547
+ return result;
548
+ }
549
+ async function loadWp2DecModule() {
550
+ if (cachedDecModule) {
551
+ return cachedDecModule;
552
+ }
553
+ const isNodeOrBun = typeof process !== "undefined" && (process.versions?.bun !== undefined || process.versions?.node !== undefined);
554
+ const modulePath = isNodeOrBun ? "wp2-dec/wp2_node_dec.js" : "wp2-dec/wp2_dec.js";
555
+ try {
556
+ console.log("[WP2 Worker] Initializing dec. Environment:", isNodeOrBun ? "Node/Bun" : "Browser");
557
+ console.log(`[WP2 Worker] Attempting to import dec module from path: ${modulePath}`);
558
+ const globalSelf = typeof self !== "undefined" ? self : globalThis;
559
+ if (!globalSelf.location) {
560
+ globalSelf.location = {
561
+ href: import.meta.url
562
+ };
563
+ }
564
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
565
+ globalThis.self = globalThis;
566
+ }
567
+ polyfillImageData();
568
+ let moduleFactory;
569
+ const isSource = import.meta.url.includes("/src/");
570
+ const pathsToTry = isSource ? ["../wasm/" + modulePath, "./wasm/" + modulePath] : ["./wasm/" + modulePath, "../wasm/" + modulePath];
571
+ let lastError = null;
572
+ for (const importPath of pathsToTry) {
573
+ try {
574
+ moduleFactory = (await import(importPath)).default;
575
+ console.log(`[WP2 Worker] Successfully loaded dec module from: ${importPath}`);
576
+ break;
577
+ } catch (error) {
578
+ lastError = error instanceof Error ? error : new Error(String(error));
579
+ console.warn(`[WP2 Worker] Failed to load dec from ${importPath}, trying next path...`);
580
+ }
581
+ }
582
+ if (!moduleFactory) {
583
+ throw lastError || new Error("Could not load WP2 dec module from any path");
584
+ }
585
+ console.log("[WP2 Worker] Dec module factory loaded successfully.");
586
+ const wasmFile = isNodeOrBun ? "wp2_node_dec.wasm" : "wp2_dec.wasm";
587
+ const wasmPathsToTry = isSource ? [`../wasm/wp2-dec/${wasmFile}`, `./wasm/wp2-dec/${wasmFile}`] : [`./wasm/wp2-dec/${wasmFile}`, `../wasm/wp2-dec/${wasmFile}`];
588
+ console.log(`[WP2 Worker] Preparing to load dec WASM binary. Will try paths: ${wasmPathsToTry.join(", ")}`);
589
+ const initDecModuleWithBinary = async (moduleFactory2, wasmPaths) => {
590
+ const workerBaseUrl = new URL(".", import.meta.url);
591
+ let lastError2 = null;
592
+ for (const wasmPath of wasmPaths) {
593
+ try {
594
+ console.log(`[WP2 Worker] Calling loadWasmBinary with dec path: ${wasmPath}`);
595
+ const wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);
596
+ console.log(`[WP2 Worker] Successfully fetched dec WASM binary from ${wasmPath}. Size: ${wasmBinary.byteLength} bytes.`);
597
+ const globalSelf2 = typeof self !== "undefined" ? self : globalThis;
598
+ if (!globalSelf2.location) {
599
+ globalSelf2.location = {
600
+ href: import.meta.url
601
+ };
602
+ }
603
+ if (typeof self === "undefined" && typeof globalThis !== "undefined") {
604
+ globalThis.self = globalThis;
605
+ }
606
+ return await moduleFactory2({
607
+ noInitialRun: true,
608
+ wasmBinary
609
+ });
610
+ } catch (err) {
611
+ lastError2 = err instanceof Error ? err : new Error(String(err));
612
+ console.warn(`[WP2 Worker] Failed to load dec WASM from ${wasmPath}, trying next path...`);
613
+ }
614
+ }
615
+ throw lastError2 || new Error("Could not load dec WASM binary from any of the attempted paths");
616
+ };
617
+ cachedDecModule = await initDecModuleWithBinary(moduleFactory, wasmPathsToTry);
618
+ console.log("[WP2 Worker] WP2 dec module initialized successfully.");
619
+ return cachedDecModule;
620
+ } catch (err) {
621
+ console.error(`[WP2 Worker] CRITICAL: Failed to load WP2 dec module from path: ${modulePath}`, err);
622
+ throw err;
623
+ }
624
+ }
625
+ async function wp2DecodeClient(data, signal) {
626
+ if (signal?.aborted) {
627
+ throw new DOMException("Aborted", "AbortError");
628
+ }
629
+ const module = await loadWp2DecModule();
630
+ if (signal?.aborted) {
631
+ throw new DOMException("Aborted", "AbortError");
632
+ }
633
+ const result = module.decode(data);
634
+ if (!result) {
635
+ throw new Error("WP2 decoding failed");
636
+ }
637
+ return result;
638
+ }
639
+ var UVModeAuto = 3, kYCoCg = 0, cachedModule = null, cachedDecModule = null;
640
+ var init_wp2_worker = __esm(() => {
641
+ init_src();
642
+ if (typeof self !== "undefined") {
643
+ self.onmessage = async (event) => {
644
+ const data = event.data;
645
+ if (data?.type === "worker:ping") {
646
+ self.postMessage({ type: "worker:ready" });
647
+ return;
648
+ }
649
+ if (data?.type === "wp2:encode") {
650
+ const request2 = data;
651
+ const response2 = {
652
+ id: request2.id,
653
+ ok: false
654
+ };
655
+ try {
656
+ const { image, options } = request2.payload;
657
+ const result = await wp2EncodeClient(image, options);
658
+ response2.ok = true;
659
+ response2.data = result;
660
+ self.postMessage(response2);
661
+ } catch (error) {
662
+ response2.error = error instanceof Error ? error.message : String(error);
663
+ self.postMessage(response2);
664
+ }
665
+ return;
666
+ }
667
+ if (data?.type === "wp2:decode") {
668
+ const request2 = data;
669
+ const response2 = {
670
+ id: request2.id,
671
+ ok: false
672
+ };
673
+ try {
674
+ const result = await wp2DecodeClient(request2.payload.data);
675
+ response2.ok = true;
676
+ response2.data = result;
677
+ self.postMessage(response2);
678
+ } catch (error) {
679
+ response2.error = error instanceof Error ? error.message : String(error);
680
+ self.postMessage(response2);
681
+ }
682
+ return;
683
+ }
684
+ const request = data;
685
+ const response = {
686
+ id: request.id,
687
+ ok: false,
688
+ error: `Unknown message type: ${data?.type}`
689
+ };
690
+ self.postMessage(response);
691
+ };
692
+ }
693
+ });
694
+
695
+ // src/bridge.ts
696
+ init_src();
697
+ init_src();
698
+
699
+ class Wp2ClientBridge {
700
+ async encode(image, options, signal) {
701
+ const module = await Promise.resolve().then(() => (init_wp2_worker(), exports_wp2_worker));
702
+ const wp2EncodeClient2 = module.wp2EncodeClient;
703
+ return wp2EncodeClient2(image, options, signal);
704
+ }
705
+ async decode(data, signal) {
706
+ const module = await Promise.resolve().then(() => (init_wp2_worker(), exports_wp2_worker));
707
+ const wp2DecodeClient2 = module.wp2DecodeClient;
708
+ return wp2DecodeClient2(data, signal);
709
+ }
710
+ async terminate() {}
711
+ }
712
+
713
+ class Wp2WorkerBridge {
714
+ worker = null;
715
+ workerReady = null;
716
+ options;
717
+ constructor(options) {
718
+ console.log("[wp2/bridge] Wp2WorkerBridge constructor called with options:", options);
719
+ this.options = options;
720
+ }
721
+ async getWorker() {
722
+ if (!this.workerReady) {
723
+ this.workerReady = this.createWorker();
724
+ }
725
+ return this.workerReady;
726
+ }
727
+ async createWorker() {
728
+ console.log("[wp2/bridge] createWorker called. Creating ready worker...");
729
+ this.worker = await createReadyWorker("wp2.worker.js", this.options);
730
+ console.log("[wp2/bridge] createWorker: Ready worker created successfully.");
731
+ return this.worker;
732
+ }
733
+ async encode(image, options, signal) {
734
+ const worker = await this.getWorker();
735
+ validateImageInput(image);
736
+ return callWorker(worker, "wp2:encode", { image, options }, signal);
737
+ }
738
+ async decode(data, signal) {
739
+ const worker = await this.getWorker();
740
+ return callWorker(worker, "wp2:decode", { data }, signal);
741
+ }
742
+ async terminate() {
743
+ if (this.worker) {
744
+ this.worker.terminate();
745
+ this.worker = null;
746
+ this.workerReady = null;
747
+ }
748
+ }
749
+ }
750
+ function createBridge(mode, options) {
751
+ console.log(`[wp2/bridge] createBridge called with mode: ${mode}`);
752
+ if (mode === "worker") {
753
+ return new Wp2WorkerBridge(options);
754
+ }
755
+ return new Wp2ClientBridge;
756
+ }
757
+
758
+ // src/index.ts
759
+ var UVMode = {
760
+ UVModeAdapt: 0,
761
+ UVMode420: 1,
762
+ UVMode444: 2,
763
+ UVModeAuto: 3
764
+ };
765
+ var Csp = {
766
+ kYCoCg: 0,
767
+ kYCbCr: 1,
768
+ kCustom: 2,
769
+ kYIQ: 3
770
+ };
771
+ var globalClientBridge = null;
772
+ async function encode(imageData, options, signal) {
773
+ if (!globalClientBridge) {
774
+ globalClientBridge = createBridge("worker");
775
+ }
776
+ return globalClientBridge.encode(imageData, options, signal);
777
+ }
778
+ async function decode(data, signal) {
779
+ if (!globalClientBridge) {
780
+ globalClientBridge = createBridge("worker");
781
+ }
782
+ return globalClientBridge.decode(data, signal);
783
+ }
784
+ function createWp2Encoder(mode = "worker", options) {
785
+ const bridge = createBridge(mode, options);
786
+ return Object.assign((imageData, options2, signal) => {
787
+ return bridge.encode(imageData, options2, signal);
788
+ }, {
789
+ terminate: async () => {
790
+ await bridge.terminate();
791
+ }
792
+ });
793
+ }
794
+ function createWp2Decoder(mode = "worker", options) {
795
+ const bridge = createBridge(mode, options);
796
+ return Object.assign((data, signal) => {
797
+ return bridge.decode(data, signal);
798
+ }, {
799
+ terminate: async () => {
800
+ await bridge.terminate();
801
+ }
802
+ });
803
+ }
804
+ export {
805
+ encode,
806
+ decode,
807
+ createWp2Encoder,
808
+ createWp2Decoder,
809
+ UVMode,
810
+ Csp
811
+ };
812
+
813
+ //# debugId=140654BFCBF380DD64756E2164756E21