agglomerative-clustering 3.1.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,7 +80,7 @@ slider.oninput = async () => {
80
80
  };
81
81
  ```
82
82
 
83
- Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba', width?, height? }`. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use the same functions from `agglomerative-clustering/worker` (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)).
83
+ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use the same functions from `agglomerative-clustering/worker` (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)).
84
84
 
85
85
  ## How it works
86
86
 
@@ -1,3 +1,3 @@
1
1
  "use strict";var __agglomerativeGlueUrl=typeof __filename=="string"&&typeof process!="undefined"&&typeof process.getBuiltinModule=="function"?process.getBuiltinModule("node:url").pathToFileURL(__filename).href:"";
2
- async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
+ async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
3
3
  ;return Module}module.exports=createWasmModule;
@@ -1,2 +1,2 @@
1
- async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
1
+ async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
2
2
  ;return Module}export default createWasmModule;
Binary file
package/dist/index.cjs CHANGED
@@ -89,7 +89,31 @@ const isWasmModule = value => typeof value === 'object' && value !== null && (ty
89
89
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
90
90
  const codes = {
91
91
  'rgba': 0,
92
- 'rgb': 1
92
+ 'rgb': 1,
93
+ 'bgra': 2,
94
+ 'rgbx': 3,
95
+ 'bgrx': 4
96
+ };
97
+ // A hint for a format name that isn't one: the right case, the name other libraries use for the same bytes, or the nearest
98
+ // supported layout.
99
+ const formatHint = format => {
100
+ if (typeof format !== 'string') {
101
+ return '';
102
+ }
103
+ const lower = format.toLowerCase();
104
+ if (lower !== format && _shared.imageFormats.includes(lower)) {
105
+ return ` Format names are lower case: '${lower}'.`;
106
+ }
107
+ if (lower === 'xrgb' || lower === 'rgb24') {
108
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
109
+ }
110
+ if (lower === 'argb' || lower === 'argb32') {
111
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: convert it to straight alpha and pass 'bgra' (see Input in the API docs).";
112
+ }
113
+ if (lower === 'bgr' || lower === 'bgr24') {
114
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
115
+ }
116
+ return '';
93
117
  };
94
118
  const alphaModeCodes = {
95
119
  'ignore': 0,
@@ -205,6 +229,10 @@ const wasmLoadFailed = (cause, given) => {
205
229
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
206
230
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
207
231
  }
232
+ } else if (/dynamically imported module|node:module/i.test(text)) {
233
+ // The glue took its Node path somewhere that has Node's globals but not Node's module loader.
234
+ reason = `Node's module loader isn't available here, in a page or worker with Node's globals but not its loader (${reason})`;
235
+ advice = "Load the package where it can take its browser path, or report this environment as an issue.";
208
236
  } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
209
237
  // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
210
238
  reason = `the .wasm file could not be fetched${where}: ${reason}`;
@@ -530,7 +558,7 @@ const load = image => {
530
558
  throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
531
559
  }
532
560
  if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
533
- throw (0, _shared.fail)('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
561
+ throw (0, _shared.detachedError)('bare');
534
562
  }
535
563
  if ((0, _shared.isUint8Array)(image)) {
536
564
  const encoded = sniffImageFormat(image);
@@ -547,7 +575,7 @@ const load = image => {
547
575
  }
548
576
  if ((0, _shared.isImageData)(image)) {
549
577
  if ((0, _shared.isDetached)(image.data)) {
550
- throw (0, _shared.fail)('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
578
+ throw (0, _shared.detachedError)('imagedata');
551
579
  }
552
580
  (0, _shared.checkImageDataPixels)(image);
553
581
  return {
@@ -566,16 +594,16 @@ const load = image => {
566
594
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
567
595
  }
568
596
  if ((0, _shared.isDetached)(image.data)) {
569
- throw (0, _shared.fail)('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
597
+ throw (0, _shared.detachedError)('data');
570
598
  }
571
- if (!Object.keys(codes).includes(image.format)) {
572
- throw (0, _shared.fail)('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
599
+ if (!_shared.imageFormats.includes(image.format)) {
600
+ throw (0, _shared.fail)('invalid-argument', `Invalid format: got ${(0, _shared.describe)(image.format)}; it must be ${_shared.formatNames}.${formatHint(image.format)}`, 'image');
573
601
  }
574
- const channels = image.format === 'rgb' ? 3 : 4;
575
- if (image.data.length % channels !== 0) {
576
- throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
602
+ const stride = (0, _shared.channels)(image.format);
603
+ if (image.data.length % stride !== 0) {
604
+ throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
577
605
  }
578
- const pixels = image.data.length / channels;
606
+ const pixels = image.data.length / stride;
579
607
  checkSize(pixels, image.width, 'image width', 'image');
580
608
  checkSize(pixels, image.height, 'image height', 'image');
581
609
  if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
@@ -712,15 +740,15 @@ const parseOptions = (options, allowed, image) => {
712
740
  throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
713
741
  }
714
742
  if (options.width !== undefined && image) {
715
- checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
743
+ checkSize(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
716
744
  }
717
745
  const width = options.width !== undefined ? options.width : image ? image.width : undefined;
718
746
  if (dither > 0) {
719
- const channels = image.format === 'rgb' ? 3 : 4;
747
+ const stride = (0, _shared.channels)(image.format);
720
748
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
721
749
  throw (0, _shared.fail)('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
722
750
  }
723
- if (image.data.length / channels % width !== 0) {
751
+ if (image.data.length / stride % width !== 0) {
724
752
  throw (0, _shared.fail)('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
725
753
  }
726
754
  }
@@ -776,8 +804,8 @@ const checkNotEmpty = (palette, image, cutoff) => {
776
804
  return;
777
805
  }
778
806
  const data = image.data;
779
- let visible = image.format === 'rgb' ? data.length > 0 : false;
780
- for (let i = 3; !visible && i < data.length; i += 4) {
807
+ let visible = (0, _shared.hasAlpha)(image.format) ? false : data.length > 0;
808
+ for (let i = 3; !visible && (0, _shared.hasAlpha)(image.format) && i < data.length; i += 4) {
781
809
  visible = data[i] >= cutoff;
782
810
  }
783
811
  if (visible) {
package/dist/index.d.cts CHANGED
@@ -1,5 +1,15 @@
1
- /** How pixel bytes are laid out: `'rgb'` is 3 bytes per pixel, `'rgba'` is 4 (red, green, blue, alpha). */
2
- export type ImageFormat = 'rgb' | 'rgba';
1
+ /**
2
+ * How pixel bytes are laid out:
3
+ * - `'rgb'`: 3 bytes per pixel, red, green, blue.
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with straight (not premultiplied) alpha last. BGRA is the order of Windows bitmaps and
5
+ * Electron's `nativeImage`, whose `toBitmap()` is premultiplied: convert it first (see Input in docs/api.md).
6
+ * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
+ * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
+ *
9
+ * Mapped images come back in the input's format; palettes are RGB whatever it is. New formats can come in a minor release,
10
+ * so take the names from `imageFormats` rather than spelling them out.
11
+ */
12
+ export type ImageFormat = 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx';
3
13
 
4
14
  /**
5
15
  * What went wrong, on the `code` of every error this library throws (the message is for people and may change):
@@ -60,7 +70,7 @@ export const ditherSteps: readonly DitherSteps[];
60
70
  export function isCodedError(value: unknown): value is CodedError;
61
71
 
62
72
  /**
63
- * An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
73
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
64
74
  * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
65
75
  */
66
76
  export interface RawImage {
@@ -188,12 +198,13 @@ export interface ClusteringOptions extends ProgressOptions {
188
198
  */
189
199
  precision?: number | undefined;
190
200
  /**
191
- * How RGBA pixels count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
192
- * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x.
201
+ * How pixels of an image with alpha (RGBA or BGRA) count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
202
+ * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x. Clustering only:
203
+ * mapping still treats alpha-0 pixels as transparent, so for bytes whose fourth byte isn't alpha use `'rgbx'`/`'bgrx'`.
193
204
  */
194
205
  alpha?: AlphaMode | undefined;
195
206
  /**
196
- * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for RGBA images: pixels with alpha
207
+ * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
197
208
  * below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
198
209
  * whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
199
210
  * PNG), and it gives the same palette everywhere: `getPalette(image, k, { transparent })` is the palette
@@ -260,11 +271,11 @@ export type QuantizeOptions = ClusteringOptions & MappingOptions;
260
271
  export interface IndexOptions {
261
272
  /**
262
273
  * `false` (default): every pixel gets the index of its nearest colour, whatever its alpha.
263
- * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image is RGBA and has pixels with alpha
274
+ * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image has alpha (RGBA or BGRA) and has pixels with alpha
264
275
  * below the cutoff, they get an extra entry appended after the palette (black, taking no part in matching), as
265
276
  * GIFs and palette PNGs expect; its index is the result's `transparentIndex`. Every other pixel is shown fully
266
277
  * opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
267
- * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is always kept. Where
278
+ * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
268
279
  * this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
269
280
  * `ClusteringOptions.transparent`), so its palette is `getPalette(image, k - 1, { transparent })`'s. With a palette
270
281
  * you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
@@ -479,7 +490,8 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
479
490
  *
480
491
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
481
492
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
482
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
493
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
494
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
483
495
  */
484
496
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
485
497
 
@@ -488,7 +500,8 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
488
500
  *
489
501
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
490
502
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
491
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
503
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
504
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
492
505
  */
493
506
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
494
507
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,15 @@
1
- /** How pixel bytes are laid out: `'rgb'` is 3 bytes per pixel, `'rgba'` is 4 (red, green, blue, alpha). */
2
- export type ImageFormat = 'rgb' | 'rgba';
1
+ /**
2
+ * How pixel bytes are laid out:
3
+ * - `'rgb'`: 3 bytes per pixel, red, green, blue.
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with straight (not premultiplied) alpha last. BGRA is the order of Windows bitmaps and
5
+ * Electron's `nativeImage`, whose `toBitmap()` is premultiplied: convert it first (see Input in docs/api.md).
6
+ * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
+ * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
+ *
9
+ * Mapped images come back in the input's format; palettes are RGB whatever it is. New formats can come in a minor release,
10
+ * so take the names from `imageFormats` rather than spelling them out.
11
+ */
12
+ export type ImageFormat = 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx';
3
13
 
4
14
  /**
5
15
  * What went wrong, on the `code` of every error this library throws (the message is for people and may change):
@@ -60,7 +70,7 @@ export const ditherSteps: readonly DitherSteps[];
60
70
  export function isCodedError(value: unknown): value is CodedError;
61
71
 
62
72
  /**
63
- * An image as raw bytes with an explicit layout: for RGB data, a `Uint8ClampedArray`, or Node, where there is no
73
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
64
74
  * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
65
75
  */
66
76
  export interface RawImage {
@@ -188,12 +198,13 @@ export interface ClusteringOptions extends ProgressOptions {
188
198
  */
189
199
  precision?: number | undefined;
190
200
  /**
191
- * How RGBA pixels count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
192
- * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x.
201
+ * How pixels of an image with alpha (RGBA or BGRA) count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
202
+ * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x. Clustering only:
203
+ * mapping still treats alpha-0 pixels as transparent, so for bytes whose fourth byte isn't alpha use `'rgbx'`/`'bgrx'`.
193
204
  */
194
205
  alpha?: AlphaMode | undefined;
195
206
  /**
196
- * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for RGBA images: pixels with alpha
207
+ * `false` (default), `true`, or an alpha cutoff from 1 to 255 (`true` means 128), for images with alpha (RGBA or BGRA): pixels with alpha
197
208
  * below the cutoff don't exist as far as the palette is concerned. They are left out of clustering, and the rest count
198
209
  * whole instead of by opacity (so it replaces `alpha` for this call). That is the model of indexed output (GIF, palette
199
210
  * PNG), and it gives the same palette everywhere: `getPalette(image, k, { transparent })` is the palette
@@ -260,11 +271,11 @@ export type QuantizeOptions = ClusteringOptions & MappingOptions;
260
271
  export interface IndexOptions {
261
272
  /**
262
273
  * `false` (default): every pixel gets the index of its nearest colour, whatever its alpha.
263
- * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image is RGBA and has pixels with alpha
274
+ * `true`, or an alpha cutoff from 1 to 255 (`true` means 128): if the image has alpha (RGBA or BGRA) and has pixels with alpha
264
275
  * below the cutoff, they get an extra entry appended after the palette (black, taking no part in matching), as
265
276
  * GIFs and palette PNGs expect; its index is the result's `transparentIndex`. Every other pixel is shown fully
266
277
  * opaque in its nearest colour. `k` counts that entry, so `k = 256` gives at most 256 entries (255 colours and the
267
- * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is always kept. Where
278
+ * transparent one) and 8-bit indices, the limit of a GIF or palette PNG; at least one colour is kept when any pixel is visible (an image with none gives just the transparent entry). Where
268
279
  * this function builds the palette itself it also leaves the pixels below the cutoff out of clustering (see
269
280
  * `ClusteringOptions.transparent`), so its palette is `getPalette(image, k - 1, { transparent })`'s. With a palette
270
281
  * you supply (`quantizeToIndicesWithPalette`) there is no `k`: the entry is added to your palette as it is. In
@@ -479,7 +490,8 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
479
490
  *
480
491
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
481
492
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
482
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
493
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
494
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
483
495
  */
484
496
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
485
497
 
@@ -488,7 +500,8 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
488
500
  *
489
501
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
490
502
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
491
- * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
503
+ * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
504
+ * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
492
505
  */
493
506
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
494
507
 
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
2
+ import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
3
3
 
4
4
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
5
5
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -15,7 +15,31 @@ const isWasmModule = value => typeof value === 'object' && value !== null && (ty
15
15
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
16
16
  const codes = {
17
17
  'rgba': 0,
18
- 'rgb': 1
18
+ 'rgb': 1,
19
+ 'bgra': 2,
20
+ 'rgbx': 3,
21
+ 'bgrx': 4
22
+ };
23
+ // A hint for a format name that isn't one: the right case, the name other libraries use for the same bytes, or the nearest
24
+ // supported layout.
25
+ const formatHint = format => {
26
+ if (typeof format !== 'string') {
27
+ return '';
28
+ }
29
+ const lower = format.toLowerCase();
30
+ if (lower !== format && imageFormats.includes(lower)) {
31
+ return ` Format names are lower case: '${lower}'.`;
32
+ }
33
+ if (lower === 'xrgb' || lower === 'rgb24') {
34
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
35
+ }
36
+ if (lower === 'argb' || lower === 'argb32') {
37
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: convert it to straight alpha and pass 'bgra' (see Input in the API docs).";
38
+ }
39
+ if (lower === 'bgr' || lower === 'bgr24') {
40
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
41
+ }
42
+ return '';
19
43
  };
20
44
  const alphaModeCodes = {
21
45
  'ignore': 0,
@@ -131,6 +155,10 @@ const wasmLoadFailed = (cause, given) => {
131
155
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
132
156
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
133
157
  }
158
+ } else if (/dynamically imported module|node:module/i.test(text)) {
159
+ // The glue took its Node path somewhere that has Node's globals but not Node's module loader.
160
+ reason = `Node's module loader isn't available here, in a page or worker with Node's globals but not its loader (${reason})`;
161
+ advice = "Load the package where it can take its browser path, or report this environment as an issue.";
134
162
  } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
135
163
  // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
136
164
  reason = `the .wasm file could not be fetched${where}: ${reason}`;
@@ -455,7 +483,7 @@ const load = image => {
455
483
  throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
456
484
  }
457
485
  if (ArrayBuffer.isView(image) && isDetached(image)) {
458
- throw fail('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
486
+ throw detachedError('bare');
459
487
  }
460
488
  if (isUint8Array(image)) {
461
489
  const encoded = sniffImageFormat(image);
@@ -472,7 +500,7 @@ const load = image => {
472
500
  }
473
501
  if (isImageData(image)) {
474
502
  if (isDetached(image.data)) {
475
- throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
503
+ throw detachedError('imagedata');
476
504
  }
477
505
  checkImageDataPixels(image);
478
506
  return {
@@ -491,16 +519,16 @@ const load = image => {
491
519
  throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
492
520
  }
493
521
  if (isDetached(image.data)) {
494
- throw fail('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
522
+ throw detachedError('data');
495
523
  }
496
- if (!Object.keys(codes).includes(image.format)) {
497
- throw fail('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
524
+ if (!imageFormats.includes(image.format)) {
525
+ throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
498
526
  }
499
- const channels = image.format === 'rgb' ? 3 : 4;
500
- if (image.data.length % channels !== 0) {
501
- throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
527
+ const stride = channels(image.format);
528
+ if (image.data.length % stride !== 0) {
529
+ throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
502
530
  }
503
- const pixels = image.data.length / channels;
531
+ const pixels = image.data.length / stride;
504
532
  checkSize(pixels, image.width, 'image width', 'image');
505
533
  checkSize(pixels, image.height, 'image height', 'image');
506
534
  if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
@@ -637,15 +665,15 @@ const parseOptions = (options, allowed, image) => {
637
665
  throw fail('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
638
666
  }
639
667
  if (options.width !== undefined && image) {
640
- checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
668
+ checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
641
669
  }
642
670
  const width = options.width !== undefined ? options.width : image ? image.width : undefined;
643
671
  if (dither > 0) {
644
- const channels = image.format === 'rgb' ? 3 : 4;
672
+ const stride = channels(image.format);
645
673
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
646
674
  throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
647
675
  }
648
- if (image.data.length / channels % width !== 0) {
676
+ if (image.data.length / stride % width !== 0) {
649
677
  throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
650
678
  }
651
679
  }
@@ -701,8 +729,8 @@ const checkNotEmpty = (palette, image, cutoff) => {
701
729
  return;
702
730
  }
703
731
  const data = image.data;
704
- let visible = image.format === 'rgb' ? data.length > 0 : false;
705
- for (let i = 3; !visible && i < data.length; i += 4) {
732
+ let visible = hasAlpha(image.format) ? false : data.length > 0;
733
+ for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
706
734
  visible = data[i] >= cutoff;
707
735
  }
708
736
  if (visible) {
package/dist/shared.cjs CHANGED
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.alphaModes = void 0;
9
+ exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.alphaModes = void 0;
10
10
  // Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
11
11
  // header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
12
12
  // './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
13
13
 
14
14
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
15
15
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
16
- const version = exports.version = '3.1.1';
16
+ const version = exports.version = '3.2.0';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -21,7 +21,20 @@ const colorSpaceCodes = exports.colorSpaceCodes = {
21
21
  // Every option whose value is one of a fixed set of names has the set exported as a frozen list (like errorCodes,
22
22
  // ditherMethods and ditherSteps), for building a choice from it or checking a value against it.
23
23
  const colorSpaces = exports.colorSpaces = Object.freeze(Object.keys(colorSpaceCodes));
24
- const imageFormats = exports.imageFormats = Object.freeze(['rgb', 'rgba']);
24
+ const imageFormats = exports.imageFormats = Object.freeze(['rgb', 'rgba', 'bgra', 'rgbx', 'bgrx']);
25
+ // Bytes per pixel of an image format: 3 for 'rgb', 4 for the rest.
26
+ const channels = format => format === 'rgb' ? 3 : 4;
27
+ // Whether an image format's fourth byte is alpha ('rgbx' and 'bgrx' have a padding byte there instead).
28
+ exports.channels = channels;
29
+ const hasAlpha = format => format === 'rgba' || format === 'bgra';
30
+ // The accepted formats as text, for messages: 'rgb', 'rgba', 'bgra', 'rgbx' or 'bgrx'.
31
+ exports.hasAlpha = hasAlpha;
32
+ const formatNames = exports.formatNames = imageFormats.map(f => `'${f}'`).join(', ').replace(/, ([^,]*)$/, ' or $1');
33
+
34
+ // The error for an image whose pixels were transferred away (detached): `what` is 'bare' (a typed array passed as the
35
+ // image), 'imagedata' or 'data' (a { data, format } object). Both entries report it in these words.
36
+ const detachedError = what => fail('invalid-argument', what === 'imagedata' ? "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true." : `Invalid image${what === 'data' ? ' data' : ''}: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.`, 'image');
37
+ exports.detachedError = detachedError;
25
38
  const alphaModes = exports.alphaModes = Object.freeze(['weight', 'ignore']);
26
39
  const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
27
40
 
@@ -55,7 +68,7 @@ exports.fail = fail;
55
68
  const maxBytes = exports.maxBytes = 2 ** 31;
56
69
  const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
57
70
  exports.sizeText = sizeText;
58
- const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
71
+ const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels at 4 bytes per pixel). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
59
72
 
60
73
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
61
74
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
@@ -93,6 +106,21 @@ const isImageData = value => typeof value === 'object' && value !== null && (typ
93
106
  exports.isImageData = isImageData;
94
107
  const checkImageDataPixels = image => {
95
108
  if (isUint8ClampedArray(image.data)) {
109
+ // skia-canvas's ImageData can hold other layouts in the same clamped array ({ colorType: 'bgra' }, 'rgb888x',
110
+ // 'gray8', ...), and node-canvas's other pixel formats ('A8', 'RGB16_565') give fewer bytes: read as RGBA, they give
111
+ // swapped colours or the wrong pixel count, so they are rejected, with the { data, format } to pass where one fits.
112
+ // skia-canvas stores short and canonical spellings ('rgba' or 'RGBA8888', 'bgra' or 'BGRA8888', 'rgb' or 'RGB888x').
113
+ const colorType = image.colorType;
114
+ const kind = typeof colorType === 'string' ? colorType.toLowerCase() : colorType;
115
+ if (kind !== undefined && kind !== 'rgba' && kind !== 'rgba8888') {
116
+ const format = kind === 'bgra' || kind === 'bgra8888' ? 'bgra' : kind === 'rgb' || kind === 'rgb888x' ? 'rgbx' : null;
117
+ const instead = format ? ` Pass { data: imageData.data, format: '${format}', width, height } instead.` : " Ask for colorType 'rgba'.";
118
+ throw fail('invalid-argument', `Invalid image: this ImageData holds ${describe(colorType)} pixels, and an ImageData is read as 8-bit RGBA.${instead}`, 'image');
119
+ }
120
+ const needed = image.width * image.height * 4;
121
+ if (image.data.length !== needed) {
122
+ throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length} bytes, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
123
+ }
96
124
  return;
97
125
  }
98
126
  const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
@@ -144,11 +172,14 @@ const imageHint = image => {
144
172
  if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
145
173
  return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
146
174
  }
175
+ if (typeof image.copyTo === 'function' && typeof image.codedWidth === 'number') {
176
+ return " Got a VideoFrame: copy its pixels with frame.copyTo(buffer, { format: 'BGRA' }) and pass { data: buffer, format: 'bgra', width: frame.visibleRect.width, height: frame.visibleRect.height } (or 'BGRX' and 'bgrx' for frames without alpha).";
177
+ }
147
178
  if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
148
179
  return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
149
180
  }
150
181
  if (image.data && !image.format) {
151
- return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
182
+ return ` It has \`data\` but no \`format\`: add format: 'rgba' (or another of ${formatNames}) to use it as a RawImage.`;
152
183
  }
153
184
  return '';
154
185
  };
@@ -191,6 +222,7 @@ const describe = value => typeof value === 'string' ? `'${value}'` : typeof valu
191
222
  // Reads every form of the dither option: false/undefined (off), true or a strength from 0 to 1 (Floyd-Steinberg, as in
192
223
  // 3.0), a method name, or an object { method, strength, steps } that the plain forms are shorthands for.
193
224
  // Returns {strength, method, steps}, with strength 0 meaning no dithering and steps 0 meaning the default.
225
+ exports.describe = describe;
194
226
  const parseDither = value => {
195
227
  const invalid = (key, message) => fail('invalid-argument', message, key === undefined ? 'options.dither' : `options.dither.${key}`);
196
228
  // What a value from a form most likely meant: 'none' for no dithering, or a number given as a string.
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.1.1';
7
+ export const version = '3.2.0';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -12,7 +12,17 @@ export const colorSpaceCodes = {
12
12
  // Every option whose value is one of a fixed set of names has the set exported as a frozen list (like errorCodes,
13
13
  // ditherMethods and ditherSteps), for building a choice from it or checking a value against it.
14
14
  export const colorSpaces = Object.freeze(Object.keys(colorSpaceCodes));
15
- export const imageFormats = Object.freeze(['rgb', 'rgba']);
15
+ export const imageFormats = Object.freeze(['rgb', 'rgba', 'bgra', 'rgbx', 'bgrx']);
16
+ // Bytes per pixel of an image format: 3 for 'rgb', 4 for the rest.
17
+ export const channels = format => format === 'rgb' ? 3 : 4;
18
+ // Whether an image format's fourth byte is alpha ('rgbx' and 'bgrx' have a padding byte there instead).
19
+ export const hasAlpha = format => format === 'rgba' || format === 'bgra';
20
+ // The accepted formats as text, for messages: 'rgb', 'rgba', 'bgra', 'rgbx' or 'bgrx'.
21
+ export const formatNames = imageFormats.map(f => `'${f}'`).join(', ').replace(/, ([^,]*)$/, ' or $1');
22
+
23
+ // The error for an image whose pixels were transferred away (detached): `what` is 'bare' (a typed array passed as the
24
+ // image), 'imagedata' or 'data' (a { data, format } object). Both entries report it in these words.
25
+ export const detachedError = what => fail('invalid-argument', what === 'imagedata' ? "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true." : `Invalid image${what === 'data' ? ' data' : ''}: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.`, 'image');
16
26
  export const alphaModes = Object.freeze(['weight', 'ignore']);
17
27
  export const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
18
28
 
@@ -42,7 +52,7 @@ export const fail = (code, message, argument) => Object.assign(new Error(message
42
52
  // worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
43
53
  export const maxBytes = 2 ** 31;
44
54
  export const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
45
- export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
55
+ export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels at 4 bytes per pixel). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
46
56
 
47
57
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
48
58
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
@@ -74,6 +84,21 @@ export const isImageData = value => typeof value === 'object' && value !== null
74
84
  // pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
75
85
  export const checkImageDataPixels = image => {
76
86
  if (isUint8ClampedArray(image.data)) {
87
+ // skia-canvas's ImageData can hold other layouts in the same clamped array ({ colorType: 'bgra' }, 'rgb888x',
88
+ // 'gray8', ...), and node-canvas's other pixel formats ('A8', 'RGB16_565') give fewer bytes: read as RGBA, they give
89
+ // swapped colours or the wrong pixel count, so they are rejected, with the { data, format } to pass where one fits.
90
+ // skia-canvas stores short and canonical spellings ('rgba' or 'RGBA8888', 'bgra' or 'BGRA8888', 'rgb' or 'RGB888x').
91
+ const colorType = image.colorType;
92
+ const kind = typeof colorType === 'string' ? colorType.toLowerCase() : colorType;
93
+ if (kind !== undefined && kind !== 'rgba' && kind !== 'rgba8888') {
94
+ const format = kind === 'bgra' || kind === 'bgra8888' ? 'bgra' : kind === 'rgb' || kind === 'rgb888x' ? 'rgbx' : null;
95
+ const instead = format ? ` Pass { data: imageData.data, format: '${format}', width, height } instead.` : " Ask for colorType 'rgba'.";
96
+ throw fail('invalid-argument', `Invalid image: this ImageData holds ${describe(colorType)} pixels, and an ImageData is read as 8-bit RGBA.${instead}`, 'image');
97
+ }
98
+ const needed = image.width * image.height * 4;
99
+ if (image.data.length !== needed) {
100
+ throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length} bytes, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
101
+ }
77
102
  return;
78
103
  }
79
104
  const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
@@ -123,11 +148,14 @@ export const imageHint = image => {
123
148
  if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
124
149
  return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
125
150
  }
151
+ if (typeof image.copyTo === 'function' && typeof image.codedWidth === 'number') {
152
+ return " Got a VideoFrame: copy its pixels with frame.copyTo(buffer, { format: 'BGRA' }) and pass { data: buffer, format: 'bgra', width: frame.visibleRect.width, height: frame.visibleRect.height } (or 'BGRX' and 'bgrx' for frames without alpha).";
153
+ }
126
154
  if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
127
155
  return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
128
156
  }
129
157
  if (image.data && !image.format) {
130
- return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
158
+ return ` It has \`data\` but no \`format\`: add format: 'rgba' (or another of ${formatNames}) to use it as a RawImage.`;
131
159
  }
132
160
  return '';
133
161
  };
@@ -162,7 +190,7 @@ export const ditherMethods = Object.freeze(Object.keys(ditherMethodCodes));
162
190
  export const ditherSteps = Object.freeze([2, 4, 8, 16, 32, 64]);
163
191
 
164
192
  // A short description of a value for an error message.
165
- const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
193
+ export const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
166
194
 
167
195
  // Reads every form of the dither option: false/undefined (off), true or a strength from 0 to 1 (Floyd-Steinberg, as in
168
196
  // 3.0), a method name, or an object { method, strength, steps } that the plain forms are shorthands for.
package/dist/worker.cjs CHANGED
@@ -85,7 +85,9 @@ const formatVersion = exports.formatVersion = _shared.latestVersion;
85
85
  // bundlers don't take this for a use of Node's `process` and add a polyfill (Parcel installs one).
86
86
  const runtime = globalThis.process;
87
87
  const scriptUrl = typeof __agglomerativeWorkerUrl === 'string' ? __agglomerativeWorkerUrl : '';
88
- const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && (typeof window === 'undefined' || typeof Worker !== 'function');
88
+ // Electron's pages, their Web Workers and service-worker preload realms (process.type 'renderer', 'worker' and
89
+ // 'service-worker') have Node's globals but no worker_threads.
90
+ const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && !['renderer', 'worker', 'service-worker'].includes(runtime.type) && (typeof window === 'undefined' || typeof Worker !== 'function');
89
91
  const isNode = hasNode && scriptUrl.startsWith('file:');
90
92
  // Node itself (or Bun) with this script bundled into CommonJS, where __agglomerativeWorkerUrl is gone: worker_threads still works, with
91
93
  // the script given, or the package's own copy. Runtimes that imitate Node say what they are in navigator.userAgent.
@@ -322,7 +324,7 @@ const send = image => {
322
324
  // A detached buffer (transferred to a worker created with transfer: true, say) is reported as the main entry reports it.
323
325
  const pixels = ArrayBuffer.isView(image) ? image : image && typeof image === 'object' && ArrayBuffer.isView(image.data) ? image.data : null;
324
326
  if (pixels && (0, _shared.isDetached)(pixels)) {
325
- throw (0, _shared.fail)('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
327
+ throw (0, _shared.detachedError)(ArrayBuffer.isView(image) ? 'bare' : (0, _shared.isImageData)(image) ? 'imagedata' : 'data');
326
328
  }
327
329
  // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
328
330
  if (pixels && pixels.byteLength >= _shared.maxBytes) {
package/dist/worker.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  // handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
5
5
  // worker, started on first use.
6
6
 
7
- import { fail, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge } from "./shared.mjs";
7
+ import { fail, detachedError, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge } from "./shared.mjs";
8
8
 
9
9
  // The same version, types and data-format version as the main entry (one implementation, in shared.js).
10
10
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -17,7 +17,9 @@ export const formatVersion = latestVersion;
17
17
  // bundlers don't take this for a use of Node's `process` and add a polyfill (Parcel installs one).
18
18
  const runtime = globalThis.process;
19
19
  const scriptUrl = typeof import.meta.url === 'string' ? import.meta.url : '';
20
- const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && (typeof window === 'undefined' || typeof Worker !== 'function');
20
+ // Electron's pages, their Web Workers and service-worker preload realms (process.type 'renderer', 'worker' and
21
+ // 'service-worker') have Node's globals but no worker_threads.
22
+ const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && !['renderer', 'worker', 'service-worker'].includes(runtime.type) && (typeof window === 'undefined' || typeof Worker !== 'function');
21
23
  const isNode = hasNode && scriptUrl.startsWith('file:');
22
24
  // Node itself (or Bun) with this script bundled into CommonJS, where import.meta.url is gone: worker_threads still works, with
23
25
  // the script given, or the package's own copy. Runtimes that imitate Node say what they are in navigator.userAgent.
@@ -254,7 +256,7 @@ const send = image => {
254
256
  // A detached buffer (transferred to a worker created with transfer: true, say) is reported as the main entry reports it.
255
257
  const pixels = ArrayBuffer.isView(image) ? image : image && typeof image === 'object' && ArrayBuffer.isView(image.data) ? image.data : null;
256
258
  if (pixels && isDetached(pixels)) {
257
- throw fail('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
259
+ throw detachedError(ArrayBuffer.isView(image) ? 'bare' : isImageData(image) ? 'imagedata' : 'data');
258
260
  }
259
261
  // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
260
262
  if (pixels && pixels.byteLength >= maxBytes) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.1.1",
3
+ "version": "3.2.0",
4
4
  "description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
5
5
  "license": "MIT",
6
6
  "author": "Rohan Fredriksson",