agglomerative-clustering 3.5.0 → 3.7.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
@@ -16,7 +16,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
16
16
  - **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
17
17
  - **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
18
18
  - **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([benchmarks](#benchmarks)).
19
- - **Small and portable.** About 96 KB of WebAssembly (45 KB gzipped), Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
19
+ - **Small and portable.** About 86 KB of WebAssembly (41 KB gzipped)<!-- bench/spikes/slicing-mapping/results-size.txt -->, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
20
20
 
21
21
  ## Install
22
22
 
@@ -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"&&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();
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,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_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,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"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];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"&&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();
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,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_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,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"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];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
@@ -489,15 +489,15 @@ const checkSize = (pixels, size, name, argument) => {
489
489
  }
490
490
  };
491
491
 
492
- // The rgb-as-rgba warning for an image, decided before load() and given only once the call's own checks have passed,
492
+ // The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
493
493
  // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
494
494
  const noWarning = () => {};
495
495
  // A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
496
496
  const warningFor = image => {
497
- const code = (0, _shared.bareRgbWarning)(image);
498
- return code ? signal => {
497
+ const warning = (0, _shared.bareImageWarning)(image);
498
+ return warning ? signal => {
499
499
  if (!(signal && signal.aborted)) {
500
- (0, _shared.warnOnce)(code, image.byteLength);
500
+ (0, _shared.warnOnce)(warning, image.byteLength);
501
501
  }
502
502
  } : noWarning;
503
503
  };
@@ -645,7 +645,8 @@ const check = k => {
645
645
  // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
646
646
  // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
647
647
  // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
648
- // signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices (see clusterInSlices)
648
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
649
+ // (see clusterInSlices and mapInSlices)
649
650
  // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
650
651
  // indexed output also gives them their own entry, which counts towards k
651
652
 
@@ -662,7 +663,7 @@ const parseOptions = (options, allowed, image) => {
662
663
  options = (0, _shared.snapshot)(options);
663
664
  for (const key of Object.keys(options)) {
664
665
  if (!allowed.includes(key)) {
665
- const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal, checked before they start: for progress, map the image in strips of rows (https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#cancelling-or-showing-progress-while-mapping-a-large-image).' : '';
666
+ const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
666
667
  throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
667
668
  }
668
669
  }
@@ -740,9 +741,7 @@ const parseOptions = (options, allowed, image) => {
740
741
  const controlOptions = ['signal', 'onProgress'];
741
742
  const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
742
743
  const quantizeOptions = [...clusterOptions, 'dither', 'width'];
743
- // The functions that only map pixels take just `signal`, checked before they start: mapping runs in one piece (milliseconds
744
- // for a photo, seconds for a large image dithered; the guides show how to map in strips or cancel through a worker).
745
- const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
744
+ const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
746
745
  const quantizeIndexOptions = quantizeOptions;
747
746
  const mapIndexOptions = [...mapOptions, 'transparent'];
748
747
 
@@ -819,7 +818,7 @@ const call = (wasm, buffers, fn, precision) => {
819
818
  };
820
819
 
821
820
  // ----- Interruptible work -------------------------------------------------------------------------------------------
822
- // A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
821
+ // A call given a `signal` or an `onProgress` runs its clustering and its mapping in slices of about `sliceMs` milliseconds, giving the
823
822
  // event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
824
823
  // in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
825
824
  // result is the same either way: the slices are the same steps in the same order.
@@ -868,6 +867,20 @@ const reporter = o => {
868
867
  };
869
868
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
870
869
 
870
+ // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
871
+ // the progress bar, so it is internal and can be retuned. Mapping's time relative to clustering's, measured on the 24
872
+ // Kodak photos (medians; bench/spikes/slicing-mapping/split.mjs → results-split.txt): undithered 0.1, Floyd–Steinberg
873
+ // 0.45, Atkinson 0.37, ordered 0.8 at 16 steps and about proportional to the steps; clustering below full precision is
874
+ // about 2.5 times faster. Steps not given are 64 for a palette of two colours, else 16, as in the C.
875
+ const mappingCost = [0.45, 0.37];
876
+ const clusteringShare = (o, k) => {
877
+ const dithered = o.dither > 0 && o.width > 0;
878
+ const ordered = dithered && o.ditherMethod === 2;
879
+ const steps = o.ditherSteps || (k <= 2 ? 64 : 16);
880
+ const cost = (!dithered ? 0.1 : ordered ? 0.8 * steps / 16 : mappingCost[o.ditherMethod]) * (o.precision < 8 ? 2.5 : 1);
881
+ return 1 / (1 + cost);
882
+ };
883
+
871
884
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
872
885
  const clusterInSlices = async (wasm, image, o, report, share) => {
873
886
  checkAborted(o.signal);
@@ -911,6 +924,67 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
911
924
  }
912
925
  };
913
926
 
927
+ // Maps in slices and returns the output's payload, as `call` does for the one-shot exports. The palette is
928
+ // `source.palette`, or cut from `source.clustering` to `source.k` colours (a negative `colorSpace` then matches in the
929
+ // clustering's space). `indices` chooses indexed output, with `cutoff`. Progress goes from `from` to 1. A call that
930
+ // finishes in its first slice doesn't yield.
931
+ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o, report, from) => {
932
+ checkAborted(o.signal);
933
+ const bytes = source.palette || source.clustering;
934
+ const imagePointer = allocate(wasm, image.data.length);
935
+ let sourcePointer = 0;
936
+ let job = 0;
937
+ let aborted = false;
938
+ try {
939
+ sourcePointer = allocate(wasm, bytes.length);
940
+ wasm.HEAPU8.set(image.data, imagePointer);
941
+ wasm.HEAPU8.set(bytes, sourcePointer);
942
+ const palette = source.palette ? sourcePointer : 0,
943
+ clustering = source.clustering ? sourcePointer : 0;
944
+ job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
945
+ if (!job) {
946
+ throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
947
+ }
948
+ // The job has its own copy of the palette, so the source can go now.
949
+ wasm._free(sourcePointer);
950
+ sourcePointer = 0;
951
+ report(from);
952
+ while (true) {
953
+ const progress = wasm._mapping_job_step(job, sliceMs);
954
+ if (progress >= 1000) {
955
+ break;
956
+ }
957
+ report(from + (1 - from) * progress / 1000);
958
+ await yieldNow();
959
+ checkAborted(o.signal);
960
+ }
961
+ const pointer = wasm._mapping_job_result(job);
962
+ try {
963
+ return unpack(wasm, pointer);
964
+ } finally {
965
+ wasm._free(pointer);
966
+ }
967
+ } catch (error) {
968
+ if (!isAbort(error)) {
969
+ throw error;
970
+ }
971
+ aborted = true;
972
+ discard(wasm);
973
+ throw outOfMemory(image.data.length, o.precision);
974
+ } finally {
975
+ if (!aborted) {
976
+ if (job) {
977
+ wasm._mapping_job_free(job);
978
+ }
979
+ if (sourcePointer) {
980
+ wasm._free(sourcePointer);
981
+ }
982
+ wasm._free(imagePointer);
983
+ retireIfLarge(wasm);
984
+ }
985
+ }
986
+ };
987
+
914
988
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
915
989
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
916
990
  // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
@@ -1093,9 +1167,12 @@ const quantize = async (image, k, options) => {
1093
1167
  const wasm = Module || (await acquire());
1094
1168
  if (isControlled(o)) {
1095
1169
  const report = reporter(o);
1096
- const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
1097
- checkAborted(o.signal);
1098
- const mapped = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1170
+ const share = clusteringShare(o, k);
1171
+ const clustering = await clusterInSlices(wasm, image, o, report, share);
1172
+ const mapped = wrap(await mapInSlices(wasm, image, {
1173
+ clustering,
1174
+ k
1175
+ }, o.colorSpace, false, 0, o, report, share));
1099
1176
  report(1);
1100
1177
  return mapped;
1101
1178
  }
@@ -1114,6 +1191,15 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1114
1191
  const wasm = Module || (await acquire());
1115
1192
  checkAborted(o.signal);
1116
1193
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
1194
+ if (isControlled(o)) {
1195
+ const report = reporter(o);
1196
+ const mapped = wrap(await mapInSlices(wasm, image, {
1197
+ clustering,
1198
+ k
1199
+ }, colorSpace, false, 0, o, report, 0));
1200
+ report(1);
1201
+ return mapped;
1202
+ }
1117
1203
  const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1118
1204
  return result;
1119
1205
  };
@@ -1130,6 +1216,14 @@ const quantizeWithPalette = async (image, palette, options) => {
1130
1216
  warn(o.signal);
1131
1217
  const wasm = Module || (await acquire());
1132
1218
  checkAborted(o.signal);
1219
+ if (isControlled(o)) {
1220
+ const report = reporter(o);
1221
+ const mapped = wrap(await mapInSlices(wasm, image, {
1222
+ palette
1223
+ }, space, false, 0, o, report, 0));
1224
+ report(1);
1225
+ return mapped;
1226
+ }
1133
1227
  const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1134
1228
  return result;
1135
1229
  };
@@ -1144,9 +1238,12 @@ const quantizeToIndices = async (image, k, options) => {
1144
1238
  const wasm = Module || (await acquire());
1145
1239
  if (isControlled(o)) {
1146
1240
  const report = reporter(o);
1147
- const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
1148
- checkAborted(o.signal);
1149
- const indexed = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, (0, _shared.colorSpaceName)(o.colorSpace));
1241
+ const share = clusteringShare(o, k);
1242
+ const clustering = await clusterInSlices(wasm, image, o, report, share);
1243
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1244
+ clustering,
1245
+ k
1246
+ }, o.colorSpace, true, o.transparent, o, report, share), original, (0, _shared.colorSpaceName)(o.colorSpace));
1150
1247
  report(1);
1151
1248
  return indexed;
1152
1249
  }
@@ -1168,6 +1265,15 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1168
1265
 
1169
1266
  // The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
1170
1267
  const cutoff = o.transparentGiven ? o.transparent : header.transparent;
1268
+ if (isControlled(o)) {
1269
+ const report = reporter(o);
1270
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1271
+ clustering,
1272
+ k
1273
+ }, colorSpace, true, cutoff, o, report, 0), original, (0, _shared.colorSpaceName)(header.colorSpace));
1274
+ report(1);
1275
+ return indexed;
1276
+ }
1171
1277
  const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, (0, _shared.colorSpaceName)(header.colorSpace));
1172
1278
  return result;
1173
1279
  };
@@ -1185,6 +1291,14 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1185
1291
  warn(o.signal);
1186
1292
  const wasm = Module || (await acquire());
1187
1293
  checkAborted(o.signal);
1294
+ if (isControlled(o)) {
1295
+ const report = reporter(o);
1296
+ const indexed = unpackIndices(await mapInSlices(wasm, image, {
1297
+ palette
1298
+ }, space, true, o.transparent, o, report, 0), original, paletteSpace);
1299
+ report(1);
1300
+ return indexed;
1301
+ }
1188
1302
  const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
1189
1303
  return result;
1190
1304
  };
package/dist/index.d.cts CHANGED
@@ -175,27 +175,25 @@ export type ColorSpace = 'rgb' | 'oklab';
175
175
  /** How pixel opacity affects clustering. */
176
176
  export type AlphaMode = 'weight' | 'ignore';
177
177
 
178
- /** Cancelling a call. Every function that takes an image has it. */
178
+ /** Cancelling a call: the base of `ProgressOptions`, which every function that takes an image has. */
179
179
  export interface CancelOptions {
180
180
  /**
181
- * Cancels the call. A call given a `signal` clusters (where it clusters) in slices of about 10 ms and checks the
182
- * signal between them, so an abort takes effect within a slice, not after the whole clustering. It rejects with
183
- * the signal's `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it
184
- * has the signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. On the functions
185
- * that only map pixels (`quantizeFromClustering`, `quantizeWithPalette` and their indexed forms) it is checked once,
186
- * before the call starts. Pixel mapping, which follows the clustering, can't be
187
- * interrupted (the guides show how to map a large image in strips, or cancel it through a worker). The call's result is the same as without a signal. In the worker entry the worker stops
188
- * working on a call that clusters, and a call still waiting its turn never starts; a mapping already running finishes.
181
+ * Cancels the call. A call given a `signal` clusters and maps in slices of about 10 ms and checks the signal
182
+ * between them, so an abort takes effect within a slice, not after the whole call. It rejects with the signal's
183
+ * `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it has the
184
+ * signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. The call's result is the
185
+ * same as without a signal. In the worker entry the worker stops working on the call too, and a call still waiting
186
+ * its turn never starts.
189
187
  */
190
188
  signal?: AbortSignal | undefined;
191
189
  }
192
190
 
193
- /** Cancelling a long call and watching its progress, for the functions that cluster. Both are optional and can be used apart. */
191
+ /** Cancelling a long call and watching its progress, for every function that takes an image. Both are optional and can be used apart. */
194
192
  export interface ProgressOptions extends CancelOptions {
195
193
  /**
196
- * Called with the fraction done, from 0 to 1, as the call runs: a few times per slice at most, never going
197
- * backwards, ending with 1. It is approximate and not linear in time. Giving it also makes the call run in
198
- * slices, so other tasks (such as painting) get a turn while it works.
194
+ * Called with the fraction done, from 0 to 1, as the call runs: between slices (about every 10 ms; a small image
195
+ * may report only 0 and 1), never going backwards, ending with 1. It is approximate and not linear in time. Giving
196
+ * it also makes the call run in slices, so other tasks (such as painting) get a turn while it works.
199
197
  */
200
198
  onProgress?: ((progress: number) => void) | undefined;
201
199
  }
@@ -257,8 +255,8 @@ export type DitherOptions =
257
255
  | { method?: 'floyd-steinberg' | 'atkinson' | undefined; strength?: number | undefined; steps?: undefined }
258
256
  | { method: 'ordered'; strength?: number | undefined; steps?: DitherSteps | undefined };
259
257
 
260
- /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. They take `signal` (checked before mapping starts) but no `onProgress`: mapping runs in one piece. */
261
- export interface MappingOptions extends CancelOptions {
258
+ /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. With `signal` or `onProgress`, mapping runs in slices, as clustering does. */
259
+ export interface MappingOptions extends ProgressOptions {
262
260
  /**
263
261
  * The space pixels are matched to their nearest palette colour in. The default is the space the colours were made in:
264
262
  * the clustering's in `quantizeFromClustering`, a `Palette`'s own in `quantizeWithPalette` and
package/dist/index.d.ts CHANGED
@@ -175,27 +175,25 @@ export type ColorSpace = 'rgb' | 'oklab';
175
175
  /** How pixel opacity affects clustering. */
176
176
  export type AlphaMode = 'weight' | 'ignore';
177
177
 
178
- /** Cancelling a call. Every function that takes an image has it. */
178
+ /** Cancelling a call: the base of `ProgressOptions`, which every function that takes an image has. */
179
179
  export interface CancelOptions {
180
180
  /**
181
- * Cancels the call. A call given a `signal` clusters (where it clusters) in slices of about 10 ms and checks the
182
- * signal between them, so an abort takes effect within a slice, not after the whole clustering. It rejects with
183
- * the signal's `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it
184
- * has the signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. On the functions
185
- * that only map pixels (`quantizeFromClustering`, `quantizeWithPalette` and their indexed forms) it is checked once,
186
- * before the call starts. Pixel mapping, which follows the clustering, can't be
187
- * interrupted (the guides show how to map a large image in strips, or cancel it through a worker). The call's result is the same as without a signal. In the worker entry the worker stops
188
- * working on a call that clusters, and a call still waiting its turn never starts; a mapping already running finishes.
181
+ * Cancels the call. A call given a `signal` clusters and maps in slices of about 10 ms and checks the signal
182
+ * between them, so an abort takes effect within a slice, not after the whole call. It rejects with the signal's
183
+ * `reason` (an `AbortError` by default), like `fetch`; note that it is that reason that is thrown, so it has the
184
+ * signal's own `name`, not an `ErrorCode`. A signal that is already aborted does no work. The call's result is the
185
+ * same as without a signal. In the worker entry the worker stops working on the call too, and a call still waiting
186
+ * its turn never starts.
189
187
  */
190
188
  signal?: AbortSignal | undefined;
191
189
  }
192
190
 
193
- /** Cancelling a long call and watching its progress, for the functions that cluster. Both are optional and can be used apart. */
191
+ /** Cancelling a long call and watching its progress, for every function that takes an image. Both are optional and can be used apart. */
194
192
  export interface ProgressOptions extends CancelOptions {
195
193
  /**
196
- * Called with the fraction done, from 0 to 1, as the call runs: a few times per slice at most, never going
197
- * backwards, ending with 1. It is approximate and not linear in time. Giving it also makes the call run in
198
- * slices, so other tasks (such as painting) get a turn while it works.
194
+ * Called with the fraction done, from 0 to 1, as the call runs: between slices (about every 10 ms; a small image
195
+ * may report only 0 and 1), never going backwards, ending with 1. It is approximate and not linear in time. Giving
196
+ * it also makes the call run in slices, so other tasks (such as painting) get a turn while it works.
199
197
  */
200
198
  onProgress?: ((progress: number) => void) | undefined;
201
199
  }
@@ -257,8 +255,8 @@ export type DitherOptions =
257
255
  | { method?: 'floyd-steinberg' | 'atkinson' | undefined; strength?: number | undefined; steps?: undefined }
258
256
  | { method: 'ordered'; strength?: number | undefined; steps?: DitherSteps | undefined };
259
257
 
260
- /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. They take `signal` (checked before mapping starts) but no `onProgress`: mapping runs in one piece. */
261
- export interface MappingOptions extends CancelOptions {
258
+ /** Options for mapping pixels to a palette: `quantizeFromClustering`, `quantizeWithPalette`, and the mapping half of `quantize` and `quantizeToIndices`. With `signal` or `onProgress`, mapping runs in slices, as clustering does. */
259
+ export interface MappingOptions extends ProgressOptions {
262
260
  /**
263
261
  * The space pixels are matched to their nearest palette colour in. The default is the space the colours were made in:
264
262
  * the clustering's in `quantizeFromClustering`, a `Palette`'s own in `quantizeWithPalette` and