@squoosh-kit/visdif 0.2.5 → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge.d.ts +4 -0
- package/dist/bridge.d.ts.map +1 -1
- package/dist/index.browser.mjs +6 -4
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.bun.js +6 -4
- package/dist/index.bun.js.map +4 -4
- package/dist/index.node.cjs +17 -15
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.mjs +6 -4
- package/dist/index.node.mjs.map +4 -4
- package/dist/visdif.worker.browser.mjs +6 -4
- package/dist/visdif.worker.browser.mjs.map +3 -3
- package/dist/visdif.worker.bun.js +6 -4
- package/dist/visdif.worker.bun.js.map +3 -3
- package/dist/visdif.worker.node.cjs +17 -15
- package/dist/visdif.worker.node.cjs.map +3 -3
- package/dist/visdif.worker.node.mjs +6 -4
- package/dist/visdif.worker.node.mjs.map +3 -3
- package/package.json +2 -2
|
@@ -133,8 +133,9 @@ function createCodecWorker(workerFilename, options) {
|
|
|
133
133
|
console.log(`[worker-helper] In browser environment. Trying to create worker:`);
|
|
134
134
|
console.log(`[worker-helper] - Package Name: ${packageName}`);
|
|
135
135
|
console.log(`[worker-helper] - Worker File: ${workerFile}`);
|
|
136
|
-
|
|
137
|
-
|
|
136
|
+
const assetPath = options?.assetPath === undefined ? DEFAULT_BROWSER_ASSET_PATH : options.assetPath;
|
|
137
|
+
if (assetPath) {
|
|
138
|
+
let normalizedAssetPath = assetPath;
|
|
138
139
|
if (!normalizedAssetPath.startsWith("/")) {
|
|
139
140
|
normalizedAssetPath = "/" + normalizedAssetPath;
|
|
140
141
|
}
|
|
@@ -143,7 +144,7 @@ function createCodecWorker(workerFilename, options) {
|
|
|
143
144
|
}
|
|
144
145
|
const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;
|
|
145
146
|
const workerUrl = new URL(workerPath, window.location.origin).href;
|
|
146
|
-
console.log(`[worker-helper] Using
|
|
147
|
+
console.log(`[worker-helper] Using assetPath. Full Worker URL: ${workerUrl}`);
|
|
147
148
|
try {
|
|
148
149
|
const worker = new Worker(workerUrl, { type: "module" });
|
|
149
150
|
console.log(`[worker-helper] Successfully created worker with assetPath: ${workerUrl}`);
|
|
@@ -257,6 +258,7 @@ function createReadyWorker(workerFilename, options, timeoutMs = 1e4) {
|
|
|
257
258
|
worker.postMessage({ type: "worker:ping" });
|
|
258
259
|
});
|
|
259
260
|
}
|
|
261
|
+
var DEFAULT_BROWSER_ASSET_PATH = "/squoosh-kit";
|
|
260
262
|
var init_worker_helper = () => {};
|
|
261
263
|
|
|
262
264
|
// ../runtime/src/wasm-loader.ts
|
|
@@ -416,4 +418,4 @@ export {
|
|
|
416
418
|
visdifCompareClient
|
|
417
419
|
};
|
|
418
420
|
|
|
419
|
-
//# debugId=
|
|
421
|
+
//# debugId=89BA6C173B83879C64756E2164756E21
|
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Runtime environment detection utilities\n */\n\n/**\n * Detect if running in a Web Worker context\n */\nexport function isWorker(): boolean {\n return (\n typeof self !== 'undefined' &&\n typeof (globalThis as unknown as { DedicatedWorkerGlobalScope?: unknown })\n .DedicatedWorkerGlobalScope !== 'undefined'\n );\n}\n\n/**\n * Detect if running in a browser context\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Detect if running in Bun\n */\nexport function isBun(): boolean {\n return typeof Bun !== 'undefined';\n}\n\n/**\n * Detect if running in Node.js\n */\nexport function isNode(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n );\n}\n\n/**\n * Check if ImageData is available in the current environment\n */\nexport function hasImageData(): boolean {\n return typeof ImageData !== 'undefined';\n}\n",
|
|
6
6
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n 'avif.worker.js': {\n package: '@squoosh-kit/avif',\n specifier: 'avif.worker.js',\n },\n 'mozjpeg.worker.js': {\n package: '@squoosh-kit/mozjpeg',\n specifier: 'mozjpeg.worker.js',\n },\n 'jxl.worker.js': {\n package: '@squoosh-kit/jxl',\n specifier: 'jxl.worker.js',\n },\n 'oxipng.worker.js': {\n package: '@squoosh-kit/oxipng',\n specifier: 'oxipng.worker.js',\n },\n 'png.worker.js': {\n package: '@squoosh-kit/png',\n specifier: 'png.worker.js',\n },\n 'imagequant.worker.js': {\n package: '@squoosh-kit/imagequant',\n specifier: 'imagequant.worker.js',\n },\n 'qoi.worker.js': {\n package: '@squoosh-kit/qoi',\n specifier: 'qoi.worker.js',\n },\n 'wp2.worker.js': {\n package: '@squoosh-kit/wp2',\n specifier: 'wp2.worker.js',\n },\n 'hqx.worker.js': {\n package: '@squoosh-kit/hqx',\n specifier: 'hqx.worker.js',\n },\n 'rotate.worker.js': {\n package: '@squoosh-kit/rotate',\n specifier: 'rotate.worker.js',\n },\n 'visdif.worker.js': {\n package: '@squoosh-kit/visdif',\n specifier: 'visdif.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e }\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const pkgName = workerConfig.package.split('/')[1]; // e.g. 'avif', 'webp', 'resize'\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = `../../${pkgName}/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = `../../${pkgName}/dist/${baseName}.${platformExt.slice(1)}`;\n\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`,\n { cause: error }\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
7
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport const DEFAULT_BROWSER_ASSET_PATH = '/squoosh-kit';\n\nexport type CreateWorkerOptions = {\n /**\n * Public URL prefix for worker and WASM files.\n * Defaults to `/squoosh-kit` in the browser (the path used by\n * `@squoosh-kit/vite-plugin`). Pass an empty string to resolve workers\n * relative to the installed package instead.\n */\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browsers, workers load from `/squoosh-kit/{package}/` by default.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n 'avif.worker.js': {\n package: '@squoosh-kit/avif',\n specifier: 'avif.worker.js',\n },\n 'mozjpeg.worker.js': {\n package: '@squoosh-kit/mozjpeg',\n specifier: 'mozjpeg.worker.js',\n },\n 'jxl.worker.js': {\n package: '@squoosh-kit/jxl',\n specifier: 'jxl.worker.js',\n },\n 'oxipng.worker.js': {\n package: '@squoosh-kit/oxipng',\n specifier: 'oxipng.worker.js',\n },\n 'png.worker.js': {\n package: '@squoosh-kit/png',\n specifier: 'png.worker.js',\n },\n 'imagequant.worker.js': {\n package: '@squoosh-kit/imagequant',\n specifier: 'imagequant.worker.js',\n },\n 'qoi.worker.js': {\n package: '@squoosh-kit/qoi',\n specifier: 'qoi.worker.js',\n },\n 'wp2.worker.js': {\n package: '@squoosh-kit/wp2',\n specifier: 'wp2.worker.js',\n },\n 'hqx.worker.js': {\n package: '@squoosh-kit/hqx',\n specifier: 'hqx.worker.js',\n },\n 'rotate.worker.js': {\n package: '@squoosh-kit/rotate',\n specifier: 'rotate.worker.js',\n },\n 'visdif.worker.js': {\n package: '@squoosh-kit/visdif',\n specifier: 'visdif.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browsers, workers load from /squoosh-kit by default\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n const assetPath =\n options?.assetPath === undefined\n ? DEFAULT_BROWSER_ASSET_PATH\n : options.assetPath;\n\n if (assetPath) {\n let normalizedAssetPath = assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e }\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const pkgName = workerConfig.package.split('/')[1]; // e.g. 'avif', 'webp', 'resize'\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = `../../${pkgName}/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = `../../${pkgName}/dist/${baseName}.${platformExt.slice(1)}`;\n\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`,\n { cause: error }\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
8
|
"/**\n * Load WASM binary from various sources with fallback strategies\n *\n * Supports:\n * - Node.js (fs/promises)\n * - Browsers (fetch)\n * - Workers (fetch)\n */\nexport async function loadWasmBinary(\n relativePath: string,\n baseUrlOverride?: string | URL\n): Promise<ArrayBuffer> {\n // Get the base URL depending on the environment (worker or main thread)\n // If a base URL is provided, use it; otherwise use import.meta.url from this module\n // In a worker, import.meta.url is the worker's own URL.\n // In the main thread, it's the URL of the current module.\n const baseUrl = baseUrlOverride\n ? typeof baseUrlOverride === 'string'\n ? new URL('.', baseUrlOverride)\n : new URL('.', baseUrlOverride.href)\n : new URL('.', import.meta.url);\n const fullUrl = new URL(relativePath, baseUrl);\n\n console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);\n console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);\n console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);\n\n try {\n const response = await fetch(fullUrl.href);\n\n console.log(\n `[WasmLoader] Fetch response status for ${fullUrl.href}: ${response.status}`\n );\n\n if (!response.ok) {\n const responseText = await response.text();\n console.error(\n `[WasmLoader] Fetch response text (first 500 chars):`,\n responseText.substring(0, 500)\n );\n throw new Error(\n `Failed to fetch WASM module at ${fullUrl.href}: ${response.status} ${response.statusText}`\n );\n }\n\n const contentType = response.headers.get('content-type');\n console.log(`[WasmLoader] Response Content-Type: ${contentType}`);\n if (!contentType || !contentType.includes('application/wasm')) {\n console.warn(\n `[WasmLoader] Warning: WASM module at ${fullUrl.href} served with incorrect MIME type: \"${contentType}\". Should be \"application/wasm\".`\n );\n }\n\n return await response.arrayBuffer();\n } catch (error) {\n console.error(\n `[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`,\n error\n );\n throw error;\n }\n}\n\n/**\n * Load WASM JavaScript module with fallback strategies\n *\n * Strategy 1: Static relative import (works everywhere)\n * Strategy 2: import.meta.resolve (Node.js 22+)\n * Strategy 3: URL-based import (browsers/workers)\n */\nexport async function loadWasmModule(\n modulePath: string\n): Promise<WebAssembly.Module> {\n // Strategy 1: Try direct static import\n try {\n return await import(/* @vite-ignore */ modulePath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e1) {\n // Continue to next strategy\n }\n\n // Strategy 2: Try import.meta.resolve (Node.js 22+)\n try {\n const resolvedPath = await import.meta.resolve(modulePath);\n\n return await import(/* @vite-ignore */ resolvedPath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e2) {\n // Continue to next strategy\n }\n\n // Strategy 3: Try URL-based import\n try {\n const url = new URL(/* @vite-ignore */ modulePath, import.meta.url);\n\n return await import(/* @vite-ignore */ url.href);\n } catch (e3) {\n throw new Error(\n `Failed to load WASM module from \"${modulePath}\". ` +\n `Ensure WASM files are in the expected location and the module can be resolved.`,\n { cause: e3 }\n );\n }\n}\n",
|
|
9
9
|
"/**\n * @squoosh-kit/runtime\n *\n * Core runtime logic for squoosh-kit, including environment utilities\n * and worker communication helpers.\n */\n\nexport * from './env.js';\nexport * from './worker-call.js';\nexport * from './types.js';\nexport * from './worker-helper.js';\nexport * from './wasm-loader.js';\nexport * from './validators.js';\nexport * from './simd-detector.js';\nexport * from './image-data-polyfill.js';\n",
|
|
10
10
|
"/**\n * VisDif Butteraugli comparison - Emscripten-based worker/client implementation\n */\n\nimport { loadWasmBinary } from '@squoosh-kit/runtime';\nimport type {\n WorkerRequest,\n WorkerResponse,\n ImageInput,\n} from '@squoosh-kit/runtime';\n\ntype VisDifModuleInstance = {\n VisDiff: new (\n data: string,\n w: number,\n h: number\n ) => { distance: (d: string) => number };\n};\n\nlet cachedModule: VisDifModuleInstance | null = null;\n\nasync function loadVisDifModule(): Promise<VisDifModuleInstance> {\n if (cachedModule) return cachedModule;\n\n // Apply Emscripten polyfills\n const globalSelf = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf.location) {\n (globalSelf as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n if (typeof self === 'undefined' && typeof globalThis !== 'undefined') {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n const workerBaseUrl = new URL('.', import.meta.url);\n const isSource = import.meta.url.includes('/src/');\n const jsPaths = isSource\n ? ['../wasm/visdif/visdif.js', './wasm/visdif/visdif.js']\n : ['./wasm/visdif/visdif.js', '../wasm/visdif/visdif.js'];\n\n let moduleFactory:\n ((config: Record<string, unknown>) => Promise<unknown>) | null = null;\n let lastJsError: Error | null = null;\n for (const jsPath of jsPaths) {\n try {\n moduleFactory = (await import(/* @vite-ignore */ jsPath)).default;\n break;\n } catch (error) {\n lastJsError = error instanceof Error ? error : new Error(String(error));\n }\n }\n if (!moduleFactory) {\n throw lastJsError || new Error('Could not load VisDif JS module');\n }\n\n const wasmPaths = isSource\n ? ['../wasm/visdif/visdif.wasm', './wasm/visdif/visdif.wasm']\n : ['./wasm/visdif/visdif.wasm', '../wasm/visdif/visdif.wasm'];\n\n let wasmBinary: ArrayBuffer | null = null;\n let lastWasmError: Error | null = null;\n for (const wasmPath of wasmPaths) {\n try {\n wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);\n break;\n } catch (error) {\n lastWasmError = error instanceof Error ? error : new Error(String(error));\n }\n }\n if (!wasmBinary) {\n throw lastWasmError || new Error('Could not load VisDif WASM');\n }\n\n // Re-apply polyfills right before factory call (Emscripten checks during init)\n const globalSelf2 = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf2.location) {\n (globalSelf2 as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n if (typeof self === 'undefined' && typeof globalThis !== 'undefined') {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n cachedModule = (await moduleFactory({\n noInitialRun: true,\n wasmBinary,\n })) as VisDifModuleInstance;\n return cachedModule;\n}\n\nfunction imageToString(image: ImageInput): string {\n // Convert RGBA pixel data to a string (Emscripten std::string format)\n const { data } = image;\n const bytes = new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.byteLength\n );\n\n // Build string from char codes\n let result = '';\n for (let i = 0; i < bytes.length; i++) {\n result += String.fromCharCode(bytes[i]);\n }\n return result;\n}\n\nexport async function visdifCompareClient(\n image1: ImageInput,\n image2: ImageInput,\n signal?: AbortSignal\n): Promise<number> {\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n if (image1.width !== image2.width || image1.height !== image2.height) {\n throw new Error('Images must have the same dimensions for comparison');\n }\n\n const module = await loadVisDifModule();\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n const data1 = imageToString(image1);\n const data2 = imageToString(image2);\n\n const visDiff = new module.VisDiff(data1, image1.width, image1.height);\n return visDiff.distance(data2);\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const request = data as WorkerRequest<{\n image1: ImageInput;\n image2: ImageInput;\n }>;\n const response: WorkerResponse<number> = { id: request.id, ok: false };\n\n try {\n if (request.type === 'visdif:compare') {\n const result = await visdifCompareClient(\n request.payload.image1,\n request.payload.image2\n );\n response.ok = true;\n response.data = result;\n self.postMessage(response);\n } else {\n response.error = `Unknown message type: ${request.type}`;\n self.postMessage(response);\n }\n } catch (error) {\n response.error = error instanceof Error ? error.message : String(error);\n self.postMessage(response);\n }\n };\n}\n"
|
|
11
11
|
],
|
|
12
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAyBO,SAAS,KAAK,GAAY;AAAA,EAC/B,OAAO,OAAO,QAAQ;AAAA;;;ACGxB,eAAsB,UAA+B,CACnD,QACA,MACA,SACA,QACA,UACoB;AAAA,EACpB,OAAO,IAAI,QAAmB,CAAC,SAAS,WAAW;AAAA,IACjD,MAAM,KAAK,EAAE;AAAA,IAGb,IAAI,QAAQ,SAAS;AAAA,MACnB,OAAO,IAAI,aAAa,WAAW,YAAY,CAAC;AAAA,MAChD;AAAA,IACF;AAAA,IAEA,MAAM,gBAAgB,CAAC,UAAwB;AAAA,MAC7C,MAAM,WAAW,MAAM;AAAA,MACvB,IAAI,SAAS,OAAO;AAAA,QAAI;AAAA,MAExB,QAAQ;AAAA,MAER,IAAI,SAAS,MAAM,SAAS,SAAS,WAAW;AAAA,QAC9C,QAAQ,SAAS,IAAI;AAAA,MACvB,EAAO;AAAA,QACL,OAAO,IAAI,MAAM,SAAS,SAAS,sBAAsB,CAAC;AAAA;AAAA;AAAA,IAI9D,MAAM,cAAc,CAAC,UAAsB;AAAA,MACzC,QAAQ;AAAA,MACR,OAAO,IAAI,MAAM,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c,MAAM;AAAA,EAElC,MAAM,UAAU,IAAI,OAAO,QAAQ,OAAO,OAAO,OAAO,OAAO,MAAM;AAAA,EACrE,OAAO,QAAQ,SAAS,KAAK;AAAA;AAAA,IAjH3B,eAA4C;AAAA;AAAA,EAfhD;AAAA,EAsIA,IAAI,OAAO,SAAS,aAAa;AAAA,IAC/B,KAAK,YAAY,OAAO,UAAwB;AAAA,MAC9C,MAAM,OAAO,MAAM;AAAA,MAGnB,IAAI,MAAM,SAAS,eAAe;AAAA,QAChC,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAAA,QACzC;AAAA,MACF;AAAA,MAEA,MAAM,UAAU;AAAA,MAIhB,MAAM,WAAmC,EAAE,IAAI,QAAQ,IAAI,IAAI,MAAM;AAAA,MAErE,IAAI;AAAA,QACF,IAAI,QAAQ,SAAS,kBAAkB;AAAA,UACrC,MAAM,SAAS,MAAM,oBACnB,QAAQ,QAAQ,QAChB,QAAQ,QAAQ,MAClB;AAAA,UACA,SAAS,KAAK;AAAA,UACd,SAAS,OAAO;AAAA,UAChB,KAAK,YAAY,QAAQ;AAAA,QAC3B,EAAO;AAAA,UACL,SAAS,QAAQ,yBAAyB,QAAQ;AAAA,UAClD,KAAK,YAAY,QAAQ;AAAA;AAAA,QAE3B,OAAO,OAAO;AAAA,QACd,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QACtE,KAAK,YAAY,QAAQ;AAAA;AAAA;AAAA,EAG/B;AAAA;",
|
|
13
|
+
"debugId": "89BA6C173B83879C64756E2164756E21",
|
|
14
14
|
"names": []
|
|
15
15
|
}
|
|
@@ -155,8 +155,9 @@ function createCodecWorker(workerFilename, options) {
|
|
|
155
155
|
console.log(`[worker-helper] In browser environment. Trying to create worker:`);
|
|
156
156
|
console.log(`[worker-helper] - Package Name: ${packageName}`);
|
|
157
157
|
console.log(`[worker-helper] - Worker File: ${workerFile}`);
|
|
158
|
-
|
|
159
|
-
|
|
158
|
+
const assetPath = options?.assetPath === undefined ? DEFAULT_BROWSER_ASSET_PATH : options.assetPath;
|
|
159
|
+
if (assetPath) {
|
|
160
|
+
let normalizedAssetPath = assetPath;
|
|
160
161
|
if (!normalizedAssetPath.startsWith("/")) {
|
|
161
162
|
normalizedAssetPath = "/" + normalizedAssetPath;
|
|
162
163
|
}
|
|
@@ -165,7 +166,7 @@ function createCodecWorker(workerFilename, options) {
|
|
|
165
166
|
}
|
|
166
167
|
const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;
|
|
167
168
|
const workerUrl = new URL(workerPath, window.location.origin).href;
|
|
168
|
-
console.log(`[worker-helper] Using
|
|
169
|
+
console.log(`[worker-helper] Using assetPath. Full Worker URL: ${workerUrl}`);
|
|
169
170
|
try {
|
|
170
171
|
const worker = new Worker(workerUrl, { type: "module" });
|
|
171
172
|
console.log(`[worker-helper] Successfully created worker with assetPath: ${workerUrl}`);
|
|
@@ -183,9 +184,9 @@ function createCodecWorker(workerFilename, options) {
|
|
|
183
184
|
let lastError = null;
|
|
184
185
|
for (const relPath of pathStrategies) {
|
|
185
186
|
console.log("relPath:", relPath);
|
|
186
|
-
console.log("import.meta.url:", "file:///home/
|
|
187
|
+
console.log("import.meta.url:", "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/worker-helper.ts");
|
|
187
188
|
try {
|
|
188
|
-
const workerUrl = new URL(relPath, "file:///home/
|
|
189
|
+
const workerUrl = new URL(relPath, "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/worker-helper.ts");
|
|
189
190
|
console.log(`[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`);
|
|
190
191
|
const worker = new Worker(workerUrl, {
|
|
191
192
|
type: "module"
|
|
@@ -208,17 +209,17 @@ function createCodecWorker(workerFilename, options) {
|
|
|
208
209
|
const pkgName = workerConfig.package.split("/")[1];
|
|
209
210
|
const srcRelPath = `../../${pkgName}/src/${baseName}.ts`;
|
|
210
211
|
console.log("srcRelPath:", srcRelPath);
|
|
211
|
-
console.log("import.meta.url:", "file:///home/
|
|
212
|
+
console.log("import.meta.url:", "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/worker-helper.ts");
|
|
212
213
|
try {
|
|
213
|
-
return new Worker(new URL(srcRelPath, "file:///home/
|
|
214
|
+
return new Worker(new URL(srcRelPath, "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/worker-helper.ts"), {
|
|
214
215
|
type: "module"
|
|
215
216
|
});
|
|
216
217
|
} catch {
|
|
217
218
|
const distRelPath = `../../${pkgName}/dist/${baseName}.${platformExt.slice(1)}`;
|
|
218
219
|
console.log("distRelPath:", distRelPath);
|
|
219
|
-
console.log("import.meta.url:", "file:///home/
|
|
220
|
+
console.log("import.meta.url:", "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/worker-helper.ts");
|
|
220
221
|
try {
|
|
221
|
-
return new Worker(new URL(distRelPath, "file:///home/
|
|
222
|
+
return new Worker(new URL(distRelPath, "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/worker-helper.ts"), {
|
|
222
223
|
type: "module"
|
|
223
224
|
});
|
|
224
225
|
} catch {
|
|
@@ -279,11 +280,12 @@ function createReadyWorker(workerFilename, options, timeoutMs = 1e4) {
|
|
|
279
280
|
worker.postMessage({ type: "worker:ping" });
|
|
280
281
|
});
|
|
281
282
|
}
|
|
283
|
+
var DEFAULT_BROWSER_ASSET_PATH = "/squoosh-kit";
|
|
282
284
|
var init_worker_helper = () => {};
|
|
283
285
|
|
|
284
286
|
// ../runtime/src/wasm-loader.ts
|
|
285
287
|
async function loadWasmBinary(relativePath, baseUrlOverride) {
|
|
286
|
-
const baseUrl = baseUrlOverride ? typeof baseUrlOverride === "string" ? new URL(".", baseUrlOverride) : new URL(".", baseUrlOverride.href) : new URL(".", "file:///home/
|
|
288
|
+
const baseUrl = baseUrlOverride ? typeof baseUrlOverride === "string" ? new URL(".", baseUrlOverride) : new URL(".", baseUrlOverride.href) : new URL(".", "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/runtime/src/wasm-loader.ts");
|
|
287
289
|
const fullUrl = new URL(relativePath, baseUrl);
|
|
288
290
|
console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);
|
|
289
291
|
console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);
|
|
@@ -328,14 +330,14 @@ async function loadVisDifModule() {
|
|
|
328
330
|
const globalSelf = typeof self !== "undefined" ? self : globalThis;
|
|
329
331
|
if (!globalSelf.location) {
|
|
330
332
|
globalSelf.location = {
|
|
331
|
-
href: "file:///home/
|
|
333
|
+
href: "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/visdif/src/visdif.worker.ts"
|
|
332
334
|
};
|
|
333
335
|
}
|
|
334
336
|
if (typeof self === "undefined" && typeof globalThis !== "undefined") {
|
|
335
337
|
globalThis.self = globalThis;
|
|
336
338
|
}
|
|
337
|
-
const workerBaseUrl = new URL(".", "file:///home/
|
|
338
|
-
const isSource = "file:///home/
|
|
339
|
+
const workerBaseUrl = new URL(".", "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/visdif/src/visdif.worker.ts");
|
|
340
|
+
const isSource = "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/visdif/src/visdif.worker.ts".includes("/src/");
|
|
339
341
|
const jsPaths = isSource ? ["../wasm/visdif/visdif.js", "./wasm/visdif/visdif.js"] : ["./wasm/visdif/visdif.js", "../wasm/visdif/visdif.js"];
|
|
340
342
|
let moduleFactory = null;
|
|
341
343
|
let lastJsError = null;
|
|
@@ -367,7 +369,7 @@ async function loadVisDifModule() {
|
|
|
367
369
|
const globalSelf2 = typeof self !== "undefined" ? self : globalThis;
|
|
368
370
|
if (!globalSelf2.location) {
|
|
369
371
|
globalSelf2.location = {
|
|
370
|
-
href: "file:///home/
|
|
372
|
+
href: "file:///home/runner/work/squoosh-kit/squoosh-kit/packages/visdif/src/visdif.worker.ts"
|
|
371
373
|
};
|
|
372
374
|
}
|
|
373
375
|
if (typeof self === "undefined" && typeof globalThis !== "undefined") {
|
|
@@ -435,4 +437,4 @@ var init_visdif_worker = __esm(() => {
|
|
|
435
437
|
});
|
|
436
438
|
init_visdif_worker();
|
|
437
439
|
|
|
438
|
-
//# debugId=
|
|
440
|
+
//# debugId=FF0C21D24CCDEE1964756E2164756E21
|
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Runtime environment detection utilities\n */\n\n/**\n * Detect if running in a Web Worker context\n */\nexport function isWorker(): boolean {\n return (\n typeof self !== 'undefined' &&\n typeof (globalThis as unknown as { DedicatedWorkerGlobalScope?: unknown })\n .DedicatedWorkerGlobalScope !== 'undefined'\n );\n}\n\n/**\n * Detect if running in a browser context\n */\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * Detect if running in Bun\n */\nexport function isBun(): boolean {\n return typeof Bun !== 'undefined';\n}\n\n/**\n * Detect if running in Node.js\n */\nexport function isNode(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n );\n}\n\n/**\n * Check if ImageData is available in the current environment\n */\nexport function hasImageData(): boolean {\n return typeof ImageData !== 'undefined';\n}\n",
|
|
6
6
|
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n resolve(response.data);\n } else {\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
7
|
-
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport type CreateWorkerOptions = {\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browser environments, uses relative paths within node_modules that Vite can resolve.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n 'avif.worker.js': {\n package: '@squoosh-kit/avif',\n specifier: 'avif.worker.js',\n },\n 'mozjpeg.worker.js': {\n package: '@squoosh-kit/mozjpeg',\n specifier: 'mozjpeg.worker.js',\n },\n 'jxl.worker.js': {\n package: '@squoosh-kit/jxl',\n specifier: 'jxl.worker.js',\n },\n 'oxipng.worker.js': {\n package: '@squoosh-kit/oxipng',\n specifier: 'oxipng.worker.js',\n },\n 'png.worker.js': {\n package: '@squoosh-kit/png',\n specifier: 'png.worker.js',\n },\n 'imagequant.worker.js': {\n package: '@squoosh-kit/imagequant',\n specifier: 'imagequant.worker.js',\n },\n 'qoi.worker.js': {\n package: '@squoosh-kit/qoi',\n specifier: 'qoi.worker.js',\n },\n 'wp2.worker.js': {\n package: '@squoosh-kit/wp2',\n specifier: 'wp2.worker.js',\n },\n 'hqx.worker.js': {\n package: '@squoosh-kit/hqx',\n specifier: 'hqx.worker.js',\n },\n 'rotate.worker.js': {\n package: '@squoosh-kit/rotate',\n specifier: 'rotate.worker.js',\n },\n 'visdif.worker.js': {\n package: '@squoosh-kit/visdif',\n specifier: 'visdif.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browser contexts, use relative paths within the installed packages\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n // If a custom asset path is provided, use it directly\n if (options?.assetPath) {\n // Normalize the asset path - ensure it starts with / and ends without /\n let normalizedAssetPath = options.assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using provided assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e }\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const pkgName = workerConfig.package.split('/')[1]; // e.g. 'avif', 'webp', 'resize'\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = `../../${pkgName}/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = `../../${pkgName}/dist/${baseName}.${platformExt.slice(1)}`;\n\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`,\n { cause: error }\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
7
|
+
"/**\n * Worker helper utilities for creating and managing Web Workers\n *\n * This module provides centralized logic for creating worker instances\n * in different environments (browser, Node.js, Bun) using import.meta.resolve\n * for server-side and package-relative paths for browsers.\n */\n\nimport { isBun } from './env';\n\nexport const DEFAULT_BROWSER_ASSET_PATH = '/squoosh-kit';\n\nexport type CreateWorkerOptions = {\n /**\n * Public URL prefix for worker and WASM files.\n * Defaults to `/squoosh-kit` in the browser (the path used by\n * `@squoosh-kit/vite-plugin`). Pass an empty string to resolve workers\n * relative to the installed package instead.\n */\n assetPath?: string;\n};\n\n/**\n * Create a Web Worker for a specific codec\n *\n * In Node.js/Bun environments, uses import.meta.resolve to locate worker files.\n * In browsers, workers load from `/squoosh-kit/{package}/` by default.\n *\n * @param workerFilename - The name of the worker file (e.g., 'resize.worker' or 'webp.worker')\n * @returns Worker instance\n * @throws Error if worker creation fails with detailed error message\n */\nexport function createCodecWorker(\n workerFilename: string,\n options?: CreateWorkerOptions\n): Worker {\n // Ensure filename has correct format\n const normalizedName = workerFilename.endsWith('.js')\n ? workerFilename\n : `${workerFilename}.js`;\n\n // Map worker filenames to their package and export\n const workerMap: Record<string, { package: string; specifier: string }> = {\n 'resize.worker.js': {\n package: '@squoosh-kit/resize',\n specifier: 'resize.worker.js',\n },\n 'webp.worker.js': {\n package: '@squoosh-kit/webp',\n specifier: 'webp.worker.js',\n },\n 'avif.worker.js': {\n package: '@squoosh-kit/avif',\n specifier: 'avif.worker.js',\n },\n 'mozjpeg.worker.js': {\n package: '@squoosh-kit/mozjpeg',\n specifier: 'mozjpeg.worker.js',\n },\n 'jxl.worker.js': {\n package: '@squoosh-kit/jxl',\n specifier: 'jxl.worker.js',\n },\n 'oxipng.worker.js': {\n package: '@squoosh-kit/oxipng',\n specifier: 'oxipng.worker.js',\n },\n 'png.worker.js': {\n package: '@squoosh-kit/png',\n specifier: 'png.worker.js',\n },\n 'imagequant.worker.js': {\n package: '@squoosh-kit/imagequant',\n specifier: 'imagequant.worker.js',\n },\n 'qoi.worker.js': {\n package: '@squoosh-kit/qoi',\n specifier: 'qoi.worker.js',\n },\n 'wp2.worker.js': {\n package: '@squoosh-kit/wp2',\n specifier: 'wp2.worker.js',\n },\n 'hqx.worker.js': {\n package: '@squoosh-kit/hqx',\n specifier: 'hqx.worker.js',\n },\n 'rotate.worker.js': {\n package: '@squoosh-kit/rotate',\n specifier: 'rotate.worker.js',\n },\n 'visdif.worker.js': {\n package: '@squoosh-kit/visdif',\n specifier: 'visdif.worker.js',\n },\n };\n\n const workerConfig = workerMap[normalizedName];\n if (!workerConfig) {\n throw new Error(\n `Unknown worker: ${normalizedName}. ` +\n `Supported workers: ${Object.keys(workerMap).join(', ')}`\n );\n }\n\n try {\n // In browsers, workers load from /squoosh-kit by default\n if (typeof window !== 'undefined') {\n const packageName = workerConfig.package.split('/')[1]; // Extract 'resize' or 'webp'\n const workerFile = normalizedName.replace('.js', '.browser.mjs');\n\n console.log(\n `[worker-helper] In browser environment. Trying to create worker:`\n );\n console.log(`[worker-helper] - Package Name: ${packageName}`);\n console.log(`[worker-helper] - Worker File: ${workerFile}`);\n\n const assetPath =\n options?.assetPath === undefined\n ? DEFAULT_BROWSER_ASSET_PATH\n : options.assetPath;\n\n if (assetPath) {\n let normalizedAssetPath = assetPath;\n if (!normalizedAssetPath.startsWith('/')) {\n normalizedAssetPath = '/' + normalizedAssetPath;\n }\n if (normalizedAssetPath.endsWith('/')) {\n normalizedAssetPath = normalizedAssetPath.slice(0, -1);\n }\n\n // Construct absolute URL: {origin}{assetPath}/{package}/{workerFile}\n const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;\n const workerUrl = new URL(workerPath, window.location.origin).href;\n\n console.log(\n `[worker-helper] Using assetPath. Full Worker URL: ${workerUrl}`\n );\n try {\n const worker = new Worker(workerUrl, { type: 'module' });\n console.log(\n `[worker-helper] Successfully created worker with assetPath: ${workerUrl}`\n );\n return worker;\n } catch (e) {\n console.error(\n `[worker-helper] Failed to load worker from assetPath URL: ${workerUrl}`,\n e\n );\n throw new Error(\n `Worker failed to load from ${workerUrl}: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e }\n );\n }\n }\n\n // Try multiple path strategies to support both:\n // 1. Monorepo development structure: ../../{package}/dist/{workerFile}\n // 2. npm installed structure: ../../../{package}/dist/{workerFile}\n const pathStrategies = [\n // First try monorepo structure (when runtime is at packages/runtime/src)\n `../../${packageName}/dist/${workerFile}`,\n // Then try npm structure (when runtime is at node_modules/@squoosh-kit/runtime)\n `../../../node_modules/@squoosh-kit/${packageName}/dist/${workerFile}`,\n // Alternative npm structure for cases where packages are flattened\n `../../../${packageName}/dist/${workerFile}`,\n ];\n\n let lastError: Error | null = null;\n\n for (const relPath of pathStrategies) {\n console.log('relPath:', relPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n const workerUrl = new URL(relPath, import.meta.url);\n console.log(\n `[worker-helper] Trying path strategy. Full Worker URL: ${workerUrl.href}`\n );\n const worker = new Worker(workerUrl, {\n type: 'module',\n });\n console.log(\n `[worker-helper] Successfully created worker with URL: ${workerUrl.href}`\n );\n return worker;\n } catch (error) {\n console.warn(\n `[worker-helper] Path strategy failed for ${relPath}:`,\n error\n );\n lastError = error instanceof Error ? error : new Error(String(error));\n // Continue to next strategy\n }\n }\n\n // If all strategies failed, throw the last error\n if (lastError) {\n console.error('[worker-helper] All path strategies failed.', lastError);\n throw lastError;\n }\n throw new Error(\n `Could not resolve worker ${normalizedName} using any available path strategy`\n );\n }\n\n // Fallbacks for monorepo/dev without build artifacts\n const platformExt = isBun() ? '.bun.js' : '.node.mjs';\n const baseName = normalizedName.replace('.js', '');\n const pkgName = workerConfig.package.split('/')[1]; // e.g. 'avif', 'webp', 'resize'\n\n // 1) Try TypeScript source first (Bun can transpile TS, works in dev)\n const srcRelPath = `../../${pkgName}/src/${baseName}.ts`;\n\n console.log('srcRelPath:', srcRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(srcRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 2) Try dist output (if already built)\n const distRelPath = `../../${pkgName}/dist/${baseName}.${platformExt.slice(1)}`;\n\n console.log('distRelPath:', distRelPath);\n console.log('import.meta.url:', import.meta.url);\n try {\n return new Worker(new URL(distRelPath, import.meta.url), {\n type: 'module',\n });\n } catch {\n // 3) Try import.meta.resolve as last resort\n if (typeof import.meta.resolve === 'function') {\n try {\n const resolved = import.meta.resolve(\n `${workerConfig.package}/${workerConfig.specifier}`\n );\n console.log('resolved:', resolved);\n return new Worker(resolved, { type: 'module' });\n } catch {\n // Continue to error below\n }\n }\n }\n }\n\n // If we get here, all fallbacks failed\n throw new Error(\n `Failed to create worker from ${normalizedName}. ` +\n `Tried TypeScript source, dist output, and import.meta.resolve. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed.`\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to create worker from ${normalizedName}: ${errorMessage}. ` +\n `Ensure the @squoosh-kit/resize and @squoosh-kit/webp packages are installed. ` +\n `If you're using Vite, ensure the worker files are not being optimized as dependencies.`,\n { cause: error }\n );\n }\n}\n\n/**\n * Create a worker with initialization timeout and ready signal handling\n *\n * This is a higher-level function that creates a worker and waits for it\n * to signal that it's ready to receive messages.\n *\n * @param workerFilename - The name of the worker file\n * @param timeoutMs - Timeout in milliseconds (default: 10000)\n * @returns Promise that resolves to a ready Worker instance\n * @throws Error if worker creation fails or times out\n */\nexport function createReadyWorker(\n workerFilename: string,\n options?: CreateWorkerOptions,\n timeoutMs: number = 10000\n): Promise<Worker> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(\n `Worker initialization timeout after ${timeoutMs}ms. Worker file: ${workerFilename}`\n )\n );\n }, timeoutMs);\n\n let worker: Worker;\n try {\n worker = createCodecWorker(workerFilename, options);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type === 'worker:ready') {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n resolve(worker);\n }\n };\n\n const handleError = (event: ErrorEvent) => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker failed to start: ${event?.message || 'Unknown error'}. Worker file: ${workerFilename}`\n )\n );\n };\n\n const handleMessageError = () => {\n clearTimeout(timeout);\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n worker.removeEventListener('messageerror', handleMessageError);\n reject(\n new Error(\n `Worker message error during initialization. Worker file: ${workerFilename}`\n )\n );\n };\n\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n worker.addEventListener('messageerror', handleMessageError);\n worker.postMessage({ type: 'worker:ping' });\n });\n}\n",
|
|
8
8
|
"/**\n * Load WASM binary from various sources with fallback strategies\n *\n * Supports:\n * - Node.js (fs/promises)\n * - Browsers (fetch)\n * - Workers (fetch)\n */\nexport async function loadWasmBinary(\n relativePath: string,\n baseUrlOverride?: string | URL\n): Promise<ArrayBuffer> {\n // Get the base URL depending on the environment (worker or main thread)\n // If a base URL is provided, use it; otherwise use import.meta.url from this module\n // In a worker, import.meta.url is the worker's own URL.\n // In the main thread, it's the URL of the current module.\n const baseUrl = baseUrlOverride\n ? typeof baseUrlOverride === 'string'\n ? new URL('.', baseUrlOverride)\n : new URL('.', baseUrlOverride.href)\n : new URL('.', import.meta.url);\n const fullUrl = new URL(relativePath, baseUrl);\n\n console.log(`[WasmLoader] Loading WASM from relative path: ${relativePath}`);\n console.log(`[WasmLoader] Base URL (import.meta.url): ${baseUrl.href}`);\n console.log(`[WasmLoader] Constructed full URL: ${fullUrl.href}`);\n\n try {\n const response = await fetch(fullUrl.href);\n\n console.log(\n `[WasmLoader] Fetch response status for ${fullUrl.href}: ${response.status}`\n );\n\n if (!response.ok) {\n const responseText = await response.text();\n console.error(\n `[WasmLoader] Fetch response text (first 500 chars):`,\n responseText.substring(0, 500)\n );\n throw new Error(\n `Failed to fetch WASM module at ${fullUrl.href}: ${response.status} ${response.statusText}`\n );\n }\n\n const contentType = response.headers.get('content-type');\n console.log(`[WasmLoader] Response Content-Type: ${contentType}`);\n if (!contentType || !contentType.includes('application/wasm')) {\n console.warn(\n `[WasmLoader] Warning: WASM module at ${fullUrl.href} served with incorrect MIME type: \"${contentType}\". Should be \"application/wasm\".`\n );\n }\n\n return await response.arrayBuffer();\n } catch (error) {\n console.error(\n `[WasmLoader] CRITICAL: Fetching WASM binary from ${fullUrl.href} failed.`,\n error\n );\n throw error;\n }\n}\n\n/**\n * Load WASM JavaScript module with fallback strategies\n *\n * Strategy 1: Static relative import (works everywhere)\n * Strategy 2: import.meta.resolve (Node.js 22+)\n * Strategy 3: URL-based import (browsers/workers)\n */\nexport async function loadWasmModule(\n modulePath: string\n): Promise<WebAssembly.Module> {\n // Strategy 1: Try direct static import\n try {\n return await import(/* @vite-ignore */ modulePath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e1) {\n // Continue to next strategy\n }\n\n // Strategy 2: Try import.meta.resolve (Node.js 22+)\n try {\n const resolvedPath = await import.meta.resolve(modulePath);\n\n return await import(/* @vite-ignore */ resolvedPath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e2) {\n // Continue to next strategy\n }\n\n // Strategy 3: Try URL-based import\n try {\n const url = new URL(/* @vite-ignore */ modulePath, import.meta.url);\n\n return await import(/* @vite-ignore */ url.href);\n } catch (e3) {\n throw new Error(\n `Failed to load WASM module from \"${modulePath}\". ` +\n `Ensure WASM files are in the expected location and the module can be resolved.`,\n { cause: e3 }\n );\n }\n}\n",
|
|
9
9
|
"/**\n * @squoosh-kit/runtime\n *\n * Core runtime logic for squoosh-kit, including environment utilities\n * and worker communication helpers.\n */\n\nexport * from './env.js';\nexport * from './worker-call.js';\nexport * from './types.js';\nexport * from './worker-helper.js';\nexport * from './wasm-loader.js';\nexport * from './validators.js';\nexport * from './simd-detector.js';\nexport * from './image-data-polyfill.js';\n",
|
|
10
10
|
"/**\n * VisDif Butteraugli comparison - Emscripten-based worker/client implementation\n */\n\nimport { loadWasmBinary } from '@squoosh-kit/runtime';\nimport type {\n WorkerRequest,\n WorkerResponse,\n ImageInput,\n} from '@squoosh-kit/runtime';\n\ntype VisDifModuleInstance = {\n VisDiff: new (\n data: string,\n w: number,\n h: number\n ) => { distance: (d: string) => number };\n};\n\nlet cachedModule: VisDifModuleInstance | null = null;\n\nasync function loadVisDifModule(): Promise<VisDifModuleInstance> {\n if (cachedModule) return cachedModule;\n\n // Apply Emscripten polyfills\n const globalSelf = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf.location) {\n (globalSelf as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n if (typeof self === 'undefined' && typeof globalThis !== 'undefined') {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n const workerBaseUrl = new URL('.', import.meta.url);\n const isSource = import.meta.url.includes('/src/');\n const jsPaths = isSource\n ? ['../wasm/visdif/visdif.js', './wasm/visdif/visdif.js']\n : ['./wasm/visdif/visdif.js', '../wasm/visdif/visdif.js'];\n\n let moduleFactory:\n ((config: Record<string, unknown>) => Promise<unknown>) | null = null;\n let lastJsError: Error | null = null;\n for (const jsPath of jsPaths) {\n try {\n moduleFactory = (await import(/* @vite-ignore */ jsPath)).default;\n break;\n } catch (error) {\n lastJsError = error instanceof Error ? error : new Error(String(error));\n }\n }\n if (!moduleFactory) {\n throw lastJsError || new Error('Could not load VisDif JS module');\n }\n\n const wasmPaths = isSource\n ? ['../wasm/visdif/visdif.wasm', './wasm/visdif/visdif.wasm']\n : ['./wasm/visdif/visdif.wasm', '../wasm/visdif/visdif.wasm'];\n\n let wasmBinary: ArrayBuffer | null = null;\n let lastWasmError: Error | null = null;\n for (const wasmPath of wasmPaths) {\n try {\n wasmBinary = await loadWasmBinary(wasmPath, workerBaseUrl);\n break;\n } catch (error) {\n lastWasmError = error instanceof Error ? error : new Error(String(error));\n }\n }\n if (!wasmBinary) {\n throw lastWasmError || new Error('Could not load VisDif WASM');\n }\n\n // Re-apply polyfills right before factory call (Emscripten checks during init)\n const globalSelf2 = typeof self !== 'undefined' ? self : globalThis;\n if (!globalSelf2.location) {\n (globalSelf2 as { location?: { href: string } }).location = {\n href: import.meta.url,\n };\n }\n if (typeof self === 'undefined' && typeof globalThis !== 'undefined') {\n (globalThis as { self?: typeof globalThis }).self = globalThis;\n }\n\n cachedModule = (await moduleFactory({\n noInitialRun: true,\n wasmBinary,\n })) as VisDifModuleInstance;\n return cachedModule;\n}\n\nfunction imageToString(image: ImageInput): string {\n // Convert RGBA pixel data to a string (Emscripten std::string format)\n const { data } = image;\n const bytes = new Uint8Array(\n data.buffer as ArrayBuffer,\n data.byteOffset,\n data.byteLength\n );\n\n // Build string from char codes\n let result = '';\n for (let i = 0; i < bytes.length; i++) {\n result += String.fromCharCode(bytes[i]);\n }\n return result;\n}\n\nexport async function visdifCompareClient(\n image1: ImageInput,\n image2: ImageInput,\n signal?: AbortSignal\n): Promise<number> {\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n if (image1.width !== image2.width || image1.height !== image2.height) {\n throw new Error('Images must have the same dimensions for comparison');\n }\n\n const module = await loadVisDifModule();\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n const data1 = imageToString(image1);\n const data2 = imageToString(image2);\n\n const visDiff = new module.VisDiff(data1, image1.width, image1.height);\n return visDiff.distance(data2);\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (event: MessageEvent) => {\n const data = event.data;\n\n // Handle worker ping for initialization\n if (data?.type === 'worker:ping') {\n self.postMessage({ type: 'worker:ready' });\n return;\n }\n\n const request = data as WorkerRequest<{\n image1: ImageInput;\n image2: ImageInput;\n }>;\n const response: WorkerResponse<number> = { id: request.id, ok: false };\n\n try {\n if (request.type === 'visdif:compare') {\n const result = await visdifCompareClient(\n request.payload.image1,\n request.payload.image2\n );\n response.ok = true;\n response.data = result;\n self.postMessage(response);\n } else {\n response.error = `Unknown message type: ${request.type}`;\n self.postMessage(response);\n }\n } catch (error) {\n response.error = error instanceof Error ? error.message : String(error);\n self.postMessage(response);\n }\n };\n}\n"
|
|
11
11
|
],
|
|
12
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,SAAS,KAAK,GAAY;AAAA,EAC/B,OAAO,OAAO,QAAQ;AAAA;;;ACGxB,eAAsB,UAA+B,CACnD,QACA,MACA,SACA,QACA,UACoB;AAAA,EACpB,OAAO,IAAI,QAAmB,CAAC,SAAS,WAAW;AAAA,IACjD,MAAM,KAAK,EAAE;AAAA,IAGb,IAAI,QAAQ,SAAS;AAAA,MACnB,OAAO,IAAI,aAAa,WAAW,YAAY,CAAC;AAAA,MAChD;AAAA,IACF;AAAA,IAEA,MAAM,gBAAgB,CAAC,UAAwB;AAAA,MAC7C,MAAM,WAAW,MAAM;AAAA,MACvB,IAAI,SAAS,OAAO;AAAA,QAAI;AAAA,MAExB,QAAQ;AAAA,MAER,IAAI,SAAS,MAAM,SAAS,SAAS,WAAW;AAAA,QAC9C,QAAQ,SAAS,IAAI;AAAA,MACvB,EAAO;AAAA,QACL,OAAO,IAAI,MAAM,SAAS,SAAS,sBAAsB,CAAC;AAAA;AAAA;AAAA,IAI9D,MAAM,cAAc,CAAC,UAAsB;AAAA,MACzC,QAAQ;AAAA,MACR,OAAO,IAAI,MAAM,iBAAiB,MAAM,SAAS,CAAC;AAAA;AAAA,IAGpD,MAAM,cAAc,MAAM;AAAA,MACxB,QAAQ;AAAA,MACR,OAAO,IAAI,aAAa,WAAW,YAAY,CAAC;AAAA;AAAA,IAGlD,MAAM,UAAU,MAAM;AAAA,MACpB,OAAO,oBAAoB,WAAW,aAAa;AAAA,MACnD,OAAO,oBAAoB,SAAS,WAAW;AAAA,MAC/C,QAAQ,oBAAoB,SAAS,WAAW;AAAA;AAAA,IAIlD,OAAO,iBAAiB,WAAW,aAAa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AAe,CAAC;AAAA,QACzC;AAAA,MACF;AAAA,MAEA,MAAM,UAAU;AAAA,MAIhB,MAAM,WAAmC,EAAE,IAAI,QAAQ,IAAI,IAAI,MAAM;AAAA,MAErE,IAAI;AAAA,QACF,IAAI,QAAQ,SAAS,kBAAkB;AAAA,UACrC,MAAM,SAAS,MAAM,oBACnB,QAAQ,QAAQ,QAChB,QAAQ,QAAQ,MAClB;AAAA,UACA,SAAS,KAAK;AAAA,UACd,SAAS,OAAO;AAAA,UAChB,KAAK,YAAY,QAAQ;AAAA,QAC3B,EAAO;AAAA,UACL,SAAS,QAAQ,yBAAyB,QAAQ;AAAA,UAClD,KAAK,YAAY,QAAQ;AAAA;AAAA,QAE3B,OAAO,OAAO;AAAA,QACd,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QACtE,KAAK,YAAY,QAAQ;AAAA;AAAA;AAAA,EAG/B;AAAA;",
|
|
13
|
+
"debugId": "FF0C21D24CCDEE1964756E2164756E21",
|
|
14
14
|
"names": []
|
|
15
15
|
}
|
|
@@ -132,8 +132,9 @@ function createCodecWorker(workerFilename, options) {
|
|
|
132
132
|
console.log(`[worker-helper] In browser environment. Trying to create worker:`);
|
|
133
133
|
console.log(`[worker-helper] - Package Name: ${packageName}`);
|
|
134
134
|
console.log(`[worker-helper] - Worker File: ${workerFile}`);
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
const assetPath = options?.assetPath === undefined ? DEFAULT_BROWSER_ASSET_PATH : options.assetPath;
|
|
136
|
+
if (assetPath) {
|
|
137
|
+
let normalizedAssetPath = assetPath;
|
|
137
138
|
if (!normalizedAssetPath.startsWith("/")) {
|
|
138
139
|
normalizedAssetPath = "/" + normalizedAssetPath;
|
|
139
140
|
}
|
|
@@ -142,7 +143,7 @@ function createCodecWorker(workerFilename, options) {
|
|
|
142
143
|
}
|
|
143
144
|
const workerPath = `${normalizedAssetPath}/${packageName}/${workerFile}`;
|
|
144
145
|
const workerUrl = new URL(workerPath, window.location.origin).href;
|
|
145
|
-
console.log(`[worker-helper] Using
|
|
146
|
+
console.log(`[worker-helper] Using assetPath. Full Worker URL: ${workerUrl}`);
|
|
146
147
|
try {
|
|
147
148
|
const worker = new Worker(workerUrl, { type: "module" });
|
|
148
149
|
console.log(`[worker-helper] Successfully created worker with assetPath: ${workerUrl}`);
|
|
@@ -256,6 +257,7 @@ function createReadyWorker(workerFilename, options, timeoutMs = 1e4) {
|
|
|
256
257
|
worker.postMessage({ type: "worker:ping" });
|
|
257
258
|
});
|
|
258
259
|
}
|
|
260
|
+
var DEFAULT_BROWSER_ASSET_PATH = "/squoosh-kit";
|
|
259
261
|
var init_worker_helper = () => {};
|
|
260
262
|
|
|
261
263
|
// ../runtime/src/wasm-loader.ts
|
|
@@ -415,4 +417,4 @@ export {
|
|
|
415
417
|
visdifCompareClient
|
|
416
418
|
};
|
|
417
419
|
|
|
418
|
-
//# debugId=
|
|
420
|
+
//# debugId=601871C3C09F205164756E2164756E21
|