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